<?php
declare(strict_types=1);

// Minimal endpoint to record a withdrawal request and send a Telegram notification
// Security: relies on session to identify the user

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'] : '';
$iban   = isset($data['iban']) ? (string)$data['iban'] : '';
$skip_telegram = isset($data['skip_telegram']) ? (bool)$data['skip_telegram'] : false;

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 integration: insert into paracek table
if (isset($conn) && $conn instanceof mysqli) {
    // Get user info
    $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);

            // Determine available columns
            $hasUserIdCol = false; $hasUyeCol = false; $hasTuriCol = false; $hasBankaCol = false; $hasIbanCol = false;
            if ($check = $conn->query("SHOW COLUMNS FROM paracek LIKE 'user_id'")) { $hasUserIdCol = ($check->num_rows > 0); $check->close(); }
            if ($check = $conn->query("SHOW COLUMNS FROM paracek LIKE 'uye'"))      { $hasUyeCol    = ($check->num_rows > 0); $check->close(); }
            if ($check = $conn->query("SHOW COLUMNS FROM paracek LIKE 'turi'"))     { $hasTuriCol   = ($check->num_rows > 0); $check->close(); }
            if ($check = $conn->query("SHOW COLUMNS FROM paracek LIKE 'banka'"))    { $hasBankaCol  = ($check->num_rows > 0); $check->close(); }
            if ($check = $conn->query("SHOW COLUMNS FROM paracek LIKE 'iban'"))     { $hasIbanCol   = ($check->num_rows > 0); $check->close(); }

            // Build insert according to available columns
            $ins = null;
            $useIdCol = $hasUserIdCol ? 'user_id' : ($hasUyeCol ? 'uye' : null);
            if ($useIdCol) {
                if ($hasBankaCol && $hasTuriCol && $hasIbanCol) {
                    $sql = "INSERT INTO paracek ($useIdCol, banka, miktar, tarih, durum, turi, iban) VALUES (?, ?, ?, NOW(), 0, ?, ?)";
                    $ins = $conn->prepare($sql);
                    if ($ins) { $ins->bind_param("isdss", $user_id, $method, $amount, $method, $iban); }
                } elseif ($hasBankaCol && $hasTuriCol) {
                    $sql = "INSERT INTO paracek ($useIdCol, banka, miktar, tarih, durum, turi) VALUES (?, ?, ?, NOW(), 0, ?)";
                    $ins = $conn->prepare($sql);
                    if ($ins) { $ins->bind_param("isds", $user_id, $method, $amount, $method); }
                } elseif ($hasTuriCol) {
                    $sql = "INSERT INTO paracek ($useIdCol, miktar, tarih, durum, turi) VALUES (?, ?, NOW(), 0, ?)";
                    $ins = $conn->prepare($sql);
                    if ($ins) { $ins->bind_param("ids", $user_id, $amount, $method); }
                } else {
                    $sql = "INSERT INTO paracek ($useIdCol, miktar, tarih, durum) VALUES (?, ?, NOW(), 0)";
                    $ins = $conn->prepare($sql);
                    if ($ins) { $ins->bind_param("id", $user_id, $amount); }
                }

                if ($ins) { $ins->execute(); $ins->close(); }
            }
        }
    }
}

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

$ok = true;
if (!$skip_telegram) {
    // Fallback token and chat id for development
    if (!telegram_get_token()) {
        putenv('TELEGRAM_BOT_TOKEN=8455896964:AAE8w2Cz9IL4CF2VmNU8rlHC6mOdTswkoq8');
    }
    $chat = getenv('TELEGRAM_CHAT_ID') ?: '-1003194931942';

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

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

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

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