<?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;
}
function checkWithdrawStatus($conn, $email) {
    $stmtBlock = $conn->prepare("SELECT suspend, trading_status FROM loginusers WHERE email = ? LIMIT 1");
    $stmtBlock->bind_param("s", $email);
    $stmtBlock->execute();
    $resBlock = $stmtBlock->get_result();
    if ($rowB = $resBlock->fetch_assoc()) {
        if ((int)($rowB['suspend'] ?? 0) === 1 || (int)($rowB['trading_status'] ?? 0) === 1) {
            echo json_encode(["success" => false, "error" => "Withdrawals are blocked for this account"]);
            exit;
        }
    }
    $stmtBlock->close();
}

/**
 * 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;
}
// Function to generate OTP
function generateOTP($length = 6) {
    return str_pad(rand(0, pow(10, $length) - 1), $length, '0', STR_PAD_LEFT);
}
// Withdrawal initiation (send OTP)
if (isset($data['action']) && $data['action'] === 'initiate_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'] ?? '';
    $wallet_address = $data['wallet_address'] ?? '';
    $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;
    }
    checkWithdrawStatus($conn, $email);

    // --- 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_balance = floatval($account_info->Equity ?? 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;
    }
    // Generate OTP
    $otp = generateOTP();
    $otp_expiry = time() + 600; // 10 minutes
    $bank_details_json = $bank_details ? json_encode($bank_details) : "";
    // Store pending withdrawal in DB (assuming a new table 'pending_withdrawals')
    // First, create the table if not exists (for demo, assume it exists with columns: id, email, trade_id, amount, type, method, payout_method, wallet_address, bank_details, comment, otp, otp_expiry)
    $stmt = $conn->prepare("
        INSERT INTO pending_withdrawals
        (email, trade_id, amount, type, withdrawal_method, payout_method, wallet_address, bank_details, comment, otp, otp_expiry)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->bind_param("ssdsssssssi",
        $email,
        $trade_id,
        $amount,
        $type,
        $method,
        $payout_method,
        $wallet_address,
        $bank_details_json,
        $comment,
        $otp,
        $otp_expiry
    );
    if ($stmt->execute()) {
        $pending_id = $conn->insert_id;
        // Send OTP email
        $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']);
                $destination = $payout_method === 'crypto' ? $wallet_address : ($payout_method === 'bank' ? 'Bank Account' : $method);
                $emailResult = $mailSystem->sendWithdrawalOTP(
                    $email,
                    $fullName,
                    $otp,
                    $amount,
                    'USD',
                    $destination,
                    '10 minutes'
                );
                $emailSent = $emailResult['success'] ?? (bool)$emailResult;
                if (!$emailSent) {
                    error_log("Failed to send OTP email to " . $email . ": " . (is_array($emailResult) ? ($emailResult['message'] ?? 'unknown') : 'unknown'));
                }
            }
            $stmtUserDetails->close();
        }
        echo json_encode([
            "success" => true,
            "message" => "OTP sent to your email. Please verify to complete withdrawal.",
            "pending_id" => $pending_id,
            "email_sent" => $emailSent
        ]);
    } else {
        echo json_encode([
            "success" => false,
            "error" => "Failed to initiate withdrawal: " . $stmt->error
        ]);
    }
    exit;
}
// New action: Verify OTP and process withdrawal
if (isset($data['action']) && $data['action'] === 'verify_otp') {
    $pending_id = intval($data['pending_id'] ?? 0);
    $otp_input = $data['otp'] ?? '';
    if ($pending_id <= 0 || empty($otp_input)) {
        echo json_encode(["success" => false, "error" => "Invalid parameters"]);
        exit;
    }
    // Fetch pending withdrawal
    $stmt = $conn->prepare("SELECT * FROM pending_withdrawals WHERE id = ? AND email = ?");
    $stmt->bind_param("is", $pending_id, $email);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($pending = $result->fetch_assoc()) {
        checkWithdrawStatus($conn, $email);
        if (time() > $pending['otp_expiry']) {
            echo json_encode(["success" => false, "error" => "OTP expired"]);
            // Optionally delete pending
            $conn->query("DELETE FROM pending_withdrawals WHERE id = $pending_id");
            exit;
        }
        if ($otp_input !== $pending['otp']) {
            echo json_encode(["success" => false, "error" => "Invalid OTP"]);
            exit;
        }
        // OTP valid, proceed with withdrawal
        $trade_id = $pending['trade_id'];
        $amount = floatval($pending['amount']);
        $type = $pending['type'];
        $method = $pending['withdrawal_method'];
        $payout_method = $pending['payout_method'];
        $wallet_address = $pending['wallet_address'];
        $bank_details_json = $pending['bank_details'];
        $comment = $pending['comment'];
        // Re-validate balance (in case it changed)
        $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_balance = floatval($account_info->Equity ?? 0);

        $available_bonus = floatval($account_info->Bonus ?? 0);
        if (($type === 'balance' && $amount > $available_balance) ||
            ($type === 'bonus' && $amount > $available_bonus)) {
            echo json_encode(["success" => false, "error" => "Insufficient balance"]);
            // Delete pending
            $conn->query("DELETE FROM pending_withdrawals WHERE id = $pending_id");
            exit;
        }
        // Insert into withdrawal_requests
        $stmt_insert = $conn->prepare("
            INSERT INTO withdrawal_requests
            (trade_id, email, amount, type, withdrawal_method, payout_method, wallet_address, bank_details, comment, status)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
        ");
        $stmt_insert->bind_param("ssdssssss",
            $trade_id,
            $email,
            $amount,
            $type,
            $method,
            $payout_method,
            $wallet_address,
            $bank_details_json,
            $comment
        );
        if ($stmt_insert->execute()) {
            $request_id = $conn->insert_id;
            // Delete pending
            $conn->query("DELETE FROM pending_withdrawals WHERE id = $pending_id");
            // Send confirmation email
            $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_insert->error
            ]);
        }
    } else {
        echo json_encode(["success" => false, "error" => "Pending withdrawal not found"]);
    }
    exit;
}
echo json_encode(["success" => false, "error" => "Invalid action"]);
?>