<?php
header("Content-Type: application/json; charset=UTF-8");
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);
    exit;
}

require_once __DIR__ . "/config.php";

// =============================
// FETCH FROM ib_withdraw_request
// =============================
$sql1 = "
    SELECT 
        id,
        email,
        trade_ids,
        total_commission,
        withdraw_type,
        company_bank,
        client_bank,
        account_holder_name,
        account_number,
        ifsc,
        type,
        random,
        status,
        walletaddress,
        network,
        created_at,
        updated_at
    FROM ib_withdraw_request
    ORDER BY id DESC
";

$result1 = $conn->query($sql1);
$withdraw_requests = [];

if ($result1) {
    while ($row = $result1->fetch_assoc()) {
        $withdraw_requests[] = $row;
    }
}

// =============================
// FETCH FROM ib_withdraw
// =============================
$sql2 = "
    SELECT 
        id,
        email,
        trade_id,
        withdraw_amount,
        withdraw_type,
        company_bank,
        client_bank,
        account_holder_name,
        account_number,
        ifsc,
        Status,
        AdminRemark,
        transaction_id,
        withdraw_date,
        Js_Admin_Remark_Date,
        type,
        random
    FROM ib_withdraw
    ORDER BY id DESC
";

$result2 = $conn->query($sql2);
$withdraw_history = [];

if ($result2) {
    while ($row = $result2->fetch_assoc()) {
        $withdraw_history[] = $row;
    }
}

// =============================
// FINAL JSON RESPONSE
// =============================
echo json_encode([
    "status" => true,
    "message" => "IB Withdraw History Fetched Successfully",
    "withdraw_requests" => $withdraw_requests,
    "withdraw_history" => $withdraw_history
], JSON_PRETTY_PRINT);

$conn->close();
?>
