<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

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

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

// Read JSON input
$input = json_decode(file_get_contents("php://input"), true);
$email = trim($input['email'] ?? '');

if (!$email) {
    echo json_encode([
        "success" => false,
        "message" => "IB email is required"
    ]);
    exit;
}

// Prepare query to fetch withdrawals for this email
$stmt = $conn->prepare("SELECT id, email, total_commission, withdraw_type, company_bank, client_bank, account_holder_name, account_number, ifsc, type, random, status, created_at, updated_at, walletaddress, network 
                        FROM ib_withdraw_request 
                        WHERE email = ? 
                        ORDER BY created_at DESC");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

// Map status codes to readable text
$statusMap = [
    0 => "Pending",
    1 => "Approved",
    2 => "Rejected"
];

// Fetch all records
$withdrawals = [];
while ($row = $result->fetch_assoc()) {
    $row['status_text'] = $statusMap[$row['status']] ?? "Unknown";
    $withdrawals[] = $row;
}

$stmt->close();

// Return JSON
echo json_encode([
    "success" => true,
    "total" => count($withdrawals),
    "withdrawals" => $withdrawals
], JSON_PRETTY_PRINT);
?>
