<?php
declare(strict_types=1);

// Minimal endpoint to send a Telegram notification when user confirms the transfer
// Security: relies on session to identify the user; do NOT expose bot token in client

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/telegram.php';
require_once __DIR__ . '/../inc/database.php';

$username = isset($_SESSION['username']) ? (string)$_SESSION['username'] : '';

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);

$amount = isset($data['amount']) ? (float)$data['amount'] : 0.0;
$method = isset($data['method']) ? (string)$data['method'] : '';

if ($username === '') {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'not_logged_in']);
    exit;
}

if (!($amount > 0)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'invalid_amount']);
    exit;
}

// Admin panel entegrasyonu: parayatir tablosuna kayıt ekle
if (isset($conn) && $conn instanceof mysqli) {
    // Kullanıcı bilgilerini çek
    $stmt = $conn->prepare("SELECT id, first_name, surname FROM kullanicilar WHERE username = ?");
    if ($stmt) {
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $res = $stmt->get_result();
        $user = $res ? $res->fetch_assoc() : null;
        $stmt->close();
        if ($user) {
            $user_id = (int)($user['id'] ?? 0);
            $adsoyad = trim(($user['first_name'] ?? '') . ' ' . ($user['surname'] ?? ''));
            // Admin panel ile uyum: parayatir.user_id kolonu varsa onu kullan
            $hasUserIdCol = false;
            if ($check = $conn->query("SHOW COLUMNS FROM parayatir LIKE 'user_id'")) {
                $hasUserIdCol = ($check->num_rows > 0);
                $check->close();
            }
            if ($hasUserIdCol) {
                $ins = $conn->prepare("INSERT INTO parayatir (user_id, adsoyad, miktar, tur, tarih, durum) VALUES (?, ?, ?, ?, NOW(), 0)");
            } else {
                $ins = $conn->prepare("INSERT INTO parayatir (uye, adsoyad, miktar, tur, tarih, durum) VALUES (?, ?, ?, ?, NOW(), 0)");
            }
            if ($ins) {
                $ins->bind_param("isds", $user_id, $adsoyad, $amount, $method);
                $ins->execute();
                $ins->close();
            }
        }
    }
}

// Basit log
@file_put_contents(__DIR__ . '/requests_log.txt', '['.date('Y-m-d H:i:s')."] deposit_notify username={$username} amount={$amount} method={$method}\n", FILE_APPEND);

// Fallback token ve chat id (kullanıcı sağladı)
if (!telegram_get_token()) {
    putenv('TELEGRAM_BOT_TOKEN=8455896964:AAE8w2Cz9IL4CF2VmNU8rlHC6mOdTswkoq8');
}
$chat = getenv('TELEGRAM_CHAT_ID') ?: '-1003194931942';

// Build message
$formattedAmount = number_format($amount, 2, ',', '.');
$msg = "Yeni Yatırım Talebi\n" .
       "Kullanıcı: {$username}\n" .
       "Tutar: ₺{$formattedAmount}\n" .
       "Yöntem: " . ($method !== '' ? $method : '-') . "\n" .
       "Kaynak: Para Yatır Sayfası";

$ok = sendTelegramMessage($chat, $msg, 'HTML');

@file_put_contents(__DIR__ . '/requests_log.txt', '['.date('Y-m-d H:i:s')."] telegram_ok=".(int)$ok." chat={$chat}\n", FILE_APPEND);

echo json_encode(['ok' => (bool)$ok]);