<?php
ob_start();
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    ob_end_flush();
    exit;
}

include_once __DIR__ . '/connection.php';
include_once __DIR__ . "/config.php";
include_once __DIR__ . "/mt5_api/mt5_api.php"; 

$raw = file_get_contents("php://input");   
$data = json_decode($raw, true);
if (!is_array($data)) {
    $data = $_POST ?? [];
}

$user_id = $data['user_id'] ?? 0;

function fetch_accounts_list($conn, $user_id) {
    $accounts = [];
    $sql = "SELECT id, email, trade_id, account_name, account_type, deposit, bonusDeposit 
            FROM liveaccounts WHERE user_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $row['deposit'] = floatval($row['deposit']);
        $row['bonusDeposit'] = floatval($row['bonusDeposit']);
        $accounts[] = $row;
    }
    $stmt->close();
    return $accounts;
}

// Fetch accounts
if (isset($data['action']) && $data['action'] === 'fetch_accounts') {
    $accounts = fetch_accounts_list($conn, $user_id);
    echo json_encode([
        "success" => true,
        "accounts" => $accounts
    ]);
    exit;
}

// Recent withdrawals
if ((isset($_GET['action']) && $_GET['action'] === 'recent') || (isset($data['action']) && $data['action'] === 'recent')) {
    $recentWithdrawals = [];
    $recentStmt = $conn->prepare("
        SELECT wr.*, l.email, l.account_name, l.account_type
        FROM withdrawal_requests wr
        JOIN liveaccounts l ON l.trade_id = wr.trade_id
        WHERE wr.user_id = ?
        ORDER BY wr.created_at DESC
        LIMIT 5
    ");
    
    if ($recentStmt) {
        $recentStmt->bind_param("i", $user_id);
        $recentStmt->execute();
        $result = $recentStmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $recentWithdrawals[] = $row;
        }
    }
    echo json_encode([
        "success" => true,
        "withdrawals" => $recentWithdrawals
    ]);
    exit;
}

// Submit withdrawal request
if (isset($data['action']) && $data['action'] === 'withdraw') {
    $trade_id = trim($data['trade_id'] ?? '');
    $amount = floatval($data['amount'] ?? 0);
    $type = ($data['type'] ?? 'balance');
    $method = $data['withdrawal_method'] ?? '';
    $bank_details = $data['bank_details'] ?? null;
    $comment = $data['comment'] ?? 'Withdrawal request via UI';

    if ($trade_id === '' || $amount <= 0 || !in_array($type, ['balance', 'bonus'])) {
        echo json_encode(["success" => false, "error" => "Invalid parameters"]);
        exit;
    }

    // Check if user has sufficient balance
    $stmt = $conn->prepare("SELECT id, deposit, bonusDeposit FROM liveaccounts WHERE trade_id = ? AND user_id = ?");
    $stmt->bind_param("si", $trade_id, $user_id);
    $stmt->execute();
    $account = $stmt->get_result()->fetch_assoc();
    
    if (!$account) {
        echo json_encode(["success" => false, "error" => "Account not found"]);
        exit;
    }

    $available = ($type === 'bonus') ? $account['bonusDeposit'] : $account['deposit'];
    if ($amount > $available) {
        echo json_encode(["success" => false, "error" => "Insufficient balance"]);
        exit;
    }

    // Insert withdrawal request
    $stmt = $conn->prepare("
        INSERT INTO withdrawal_requests 
        (user_id, trade_id, amount, type, withdrawal_method, bank_details, comment, status) 
        VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')
    ");

    $bank_details_json = $bank_details ? json_encode($bank_details) : null;
    $stmt->bind_param("isdssss", 
        $user_id, 
        $trade_id, 
        $amount, 
        $type, 
        $method, 
        $bank_details_json, 
        $comment
    );

    if ($stmt->execute()) {
        $request_id = $conn->insert_id;
        echo json_encode([
            "success" => true,
            "message" => "Withdrawal request submitted successfully",
            "request_id" => $request_id
        ]);
    } else {
        echo json_encode([
            "success" => false,
            "error" => "Failed to submit withdrawal request"
        ]);
    }
    exit;
}

echo json_encode(["success" => false, "error" => "Invalid action"]);