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

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

include_once __DIR__ . '/config.php'; // Make sure $conn is defined in config.php

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

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

try {
    $recentWithdrawals = [];

    // Query
    $withdrawQuery = "
        SELECT 
            wr.id,
            wr.user_id,
            wr.trade_id,
            wr.amount,
            wr.type,
            wr.comment,
            wr.withdrawal_method,
            wr.status,
            wr.admin_comment,
            wr.created_at AS date,
            wr.email,
            la.account_name,
            la.account_type
        FROM withdrawal_requests wr
        JOIN liveaccounts la ON la.trade_id = wr.trade_id
        WHERE wr.email = ?
          AND la.account_type != 'Demo'
        ORDER BY wr.created_at DESC
    ";

    $stmt = $conn->prepare($withdrawQuery);
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {

        // Detect CENT account
        $isCent = stripos($row['account_type'], 'cent') !== false;

        // Convert amount: CENT → USD (divide by 100)
        $convertedAmount = floatval($row['amount']); // already correct USD


        // Replace amount with converted value
        $row['amount'] = number_format($convertedAmount, 2, '.', '');

        $recentWithdrawals[] = $row;
    }

    echo json_encode([
        "success" => true,
        "recentWithdrawals" => $recentWithdrawals
    ]);

} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "message" => "Error fetching withdrawals: " . $e->getMessage(),
        "recentWithdrawals" => []
    ]);
}
?>
