<?php
session_start();
require_once(__DIR__ . "/../config/db.php");
require_once(__DIR__ . "/../session.php");
// require_once(__DIR__ . "/../api/AuraGaming-API.php");

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die("CSRF token tidak valid");
    }

    $amount = (int) $_POST['Amount'];
    $to = $_POST['ToAccount'];
    $type = 'withdraw';

    $stmt = $db->prepare("SELECT COUNT(*) FROM transaction WHERE user_id = :user_id AND type = :type AND status = 0");
    $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
    $stmt->bindParam(':type', $type, PDO::PARAM_STR);
    $stmt->execute();

    if ($stmt->fetchColumn() > 0) {
        $_SESSION['error'] = "Kamu masih memiliki transaksi tertunda.";
        header("Location: /");
        exit();
    }

    if ($amount > $saldo_aktif) {
        $_SESSION['error'] = "Saldo kamu tidak mencukupi.";
        header("Location: /");
        exit();
    }

    if ($amount < 100000) {
        $_SESSION['error'] = "Minimal withdrawal adalah Rp 100.000.";
        header("Location: /");
        exit();
    }

    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    do {
        $trxid = '';
        for ($i = 0; $i < 8; $i++) {
            $trxid .= $characters[random_int(0, strlen($characters) - 1)];
        }
        $stmt = $db->prepare("SELECT COUNT(*) FROM transaction WHERE trxid = :trxid");
        $stmt->bindParam(':trxid', $trxid, PDO::PARAM_STR);
        $stmt->execute();
    } while ($stmt->fetchColumn() > 0);

    // if ($AG->withdraw($agent_code, $agent_token, $extplayer, $amount)) {
        $stmt = $db->prepare("INSERT INTO transaction (user_id, trxid, type, Amount, ToAccount, created_at, updated_at) 
                              VALUES (:user_id, :trxid, :type, :Amount, :ToAccount, NOW(), NOW())");
        $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
        $stmt->bindParam(':trxid', $trxid, PDO::PARAM_STR);
        $stmt->bindParam(':type', $type, PDO::PARAM_STR);
        $stmt->bindParam(':Amount', $amount, PDO::PARAM_INT);
        $stmt->bindParam(':ToAccount', $to, PDO::PARAM_STR);

        if ($stmt->execute()) {
            $stmt = $db->prepare("UPDATE balance SET total_balance = total_balance - :Amount WHERE user_id = :user_id");
            $stmt->bindParam(':Amount', $amount, PDO::PARAM_INT);
            $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);

            if ($stmt->execute()) {
                $_SESSION['message'] = "Permintaan withdraw berhasil dikirim.";
                header("Location: /");
                exit();
            } else {
                $_SESSION['error'] = "Gagal memperbarui saldo.";
            }
        } else {
            $_SESSION['error'] = "Gagal menyimpan transaksi.";
        }
    // } else {
    //     echo $act['msg'];
    // }

    header("Location: /");
    exit();
}
?>