<?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 ?? [];
}

$email = $data['email'] ?? '';
if (empty($email)) {
    echo json_encode(["success" => false, "error" => "Email is required"]);
    exit;
}

/**
 * Fetch accounts using MT5 API directly
 */
function fetch_accounts_list_mt5($conn, $email) {
    $accounts = [];

    // Get all trade_ids for this email from DB
    $sql = "SELECT DISTINCT trade_id FROM wallet_deposit WHERE email = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $res = $stmt->get_result();

    // Connect to MT5
    $mt5 = new MT5Connection();
    if (!$mt5->connect()) {
        return ["error" => "Failed to connect to MT5 server"];
    }

    while ($row = $res->fetch_assoc()) {
        $trade_id = $row['trade_id'];
        $account_info = null;
        $ret = $mt5->api->UserAccountGet((int)$trade_id, $account_info);

        if ($ret !== MTRetCode::MT_RET_OK || !$account_info) {
            continue; // skip if account not found
        }

        $accounts[] = [
            'trade_id' => $trade_id,
            'account_name' => $account_info->Login ?? $trade_id,
            'account_type' => $account_info->Group ?? '',
            'email' => $email,
            'available_balance' => floatval($account_info->Balance ?? 0),
            'bonus_balance' => floatval($account_info->Bonus ?? 0)
        ];
    }

    $stmt->close();
    return $accounts;
}

// Fetch accounts action using MT5
if (isset($data['action']) && $data['action'] === 'fetch_accounts') {
    $accounts = fetch_accounts_list_mt5($conn, $email);

    if (isset($accounts['error'])) {
        echo json_encode(["success" => false, "error" => $accounts['error']]);
    } else {
        echo json_encode([
            "success" => true,
            "accounts" => $accounts
        ]);
    }
    exit;
}

// Withdrawal logic — validate against MT5 balance
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;
    }

    // --- FETCH BALANCE FROM MT5 ---
    $mt5 = new MT5Connection();
    if (!$mt5->connect()) {
        echo json_encode(["success" => false, "error" => "Failed to connect to MT5 server"]);
        exit;
    }

    $account_info = null;
    $ret = $mt5->api->UserAccountGet((int)$trade_id, $account_info);
    if ($ret !== MTRetCode::MT_RET_OK || !$account_info) {
        echo json_encode(["success" => false, "error" => "User account not found on MT5"]);
        exit;
    }

    $available_balance = floatval($account_info->Balance ?? 0);
    $available_bonus = floatval($account_info->Bonus ?? 0);

    // Check if requested amount is available
    if (($type === 'balance' && $amount > $available_balance) ||
        ($type === 'bonus' && $amount > $available_bonus)) {
        echo json_encode(["success" => false, "error" => "Insufficient balance"]);
        exit;
    }

    $bank_details_json = $bank_details ? json_encode($bank_details) : "";

    $stmt = $conn->prepare("
        INSERT INTO withdrawal_requests 
        (trade_id, email, amount, type, withdrawal_method, bank_details, comment, status) 
        VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')
    ");
    $stmt->bind_param("ssdssss", 
        $trade_id,
        $email,
        $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,
            "withdraw_amount" => $amount,
            "available_balance" => $available_balance,
            "available_bonus" => $available_bonus
        ]);
    } else {
        echo json_encode([
            "success" => false,
            "error" => "Failed to submit withdrawal request: " . $stmt->error
        ]);
    }
    exit;
}

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