<?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";

// Include unified config for email system
include_once __DIR__ . '/unified_config.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'] ?? '';
    $payout_method = $data['payout_method'] ?? '';       // <-- added
    $wallet_address = $data['wallet_address'] ?? '';     // <-- added
    $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) : "";

    // Updated INSERT to include payout_method and wallet_address
    $stmt = $conn->prepare("
        INSERT INTO withdrawal_requests 
        (trade_id, email, amount, type, withdrawal_method, payout_method, wallet_address, bank_details, comment, status) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
    ");
    $stmt->bind_param("ssdssssss", 
    $trade_id,
    $email,
    $amount,
    $type,
    $method,
    $payout_method,
    $wallet_address,
    $bank_details_json,
    $comment
);


    if ($stmt->execute()) {
        $request_id = $conn->insert_id;

        // ------------------
        // Send withdrawal request submission email (now includes type)
        // ------------------
        $emailSent = false;
        if (EMAIL_AUTOMATION_ENABLED) {
            $stmtUserDetails = $conn->prepare("SELECT first_name, last_name FROM loginusers WHERE email = ?");
            $stmtUserDetails->bind_param("s", $email);
            $stmtUserDetails->execute();
            $userResult = $stmtUserDetails->get_result();
            
            if ($userDetails = $userResult->fetch_assoc()) {
                $mailSystem = getMailSystem();
                $fullName = trim($userDetails['first_name'] . ' ' . $userDetails['last_name']);
                
                $emailResult = $mailSystem->sendWithdrawalRequestSubmitted(
                    $email, 
                    $fullName, 
                    $amount, 
                    'USD',
                    $method,
                    'WTH-' . $request_id,
                    $type
                );
                
                $emailSent = $emailResult['success'] ?? (bool)$emailResult;
                if (!$emailSent) {
                    error_log("Failed to send withdrawal request email to " . $email . ": " . (is_array($emailResult) ? ($emailResult['message'] ?? 'unknown') : 'unknown'));
                }
            }
            $stmtUserDetails->close();
        }
        
        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,
            "email_sent" => $emailSent
        ]);
    } else {
        echo json_encode([
            "success" => false,
            "error" => "Failed to submit withdrawal request: " . $stmt->error
        ]);
    }
    exit;
}

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