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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

include_once __DIR__ . '/config.php';

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

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

try {
    $recentDeposits = [];

    // // Fetch deposit_requests with pending or approved
    // $depositQuery = "
    //     SELECT 
    //         dr.id,
    //         dr.user_id,
    //         dr.trade_id, 
    //         dr.amount, 
    //         dr.type, 
    //         dr.comment, 
    //         dr.transaction_proof, 
    //         dr.status, 
    //         dr.admin_comment, 
    //         dr.created_at AS date, 
    //         lu.email
    //     FROM deposit_requests dr
    //     JOIN loginusers lu ON dr.user_id = lu.id
    //     WHERE lu.email = ? AND dr.status IN ('pending','approved')
    //     ORDER BY dr.created_at DESC
    // ";
    
    $depositQuery = "
    SELECT 
        dr.id,
        dr.user_id,
        dr.trade_id, 
        dr.amount, 
        dr.type, 
        dr.comment, 
        dr.transaction_proof, 
        dr.status, 
        dr.admin_comment, 
        dr.created_at AS date, 
        lu.email
    FROM deposit_requests dr
    JOIN loginusers lu ON dr.user_id = lu.id
    JOIN liveaccounts la ON la.trade_id = dr.trade_id
    WHERE lu.email = ? 
        AND dr.status IN ('pending','approved')
        AND la.account_type != 'Demo'
    ORDER BY dr.created_at DESC
";

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

    while ($row = $result->fetch_assoc()) {
        $recentDeposits[] = $row;
    }

    // -----------------------------
    // No duplicate removal — keep all pending and approved
    // -----------------------------
    
    // -----------------------------
    // Sort all deposits by date descending
    // -----------------------------
    usort($recentDeposits, function($a, $b) {
        return strtotime($b['date']) - strtotime($a['date']);
    });

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

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