<?php
header('Content-Type: application/json');

// -------------------- CORS --------------------
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

// -------------------- DB INCLUDE --------------------
include_once __DIR__ . '/../config.php';

// -------------------- GET INPUT --------------------
$input = file_get_contents("php://input");
$data = json_decode($input, true);
$filterStatus = isset($data['status']) ? strtolower($data['status']) : null;

// -------------------- BASE QUERY --------------------
$query = "
    SELECT * FROM (
        SELECT dr.id AS request_id,
               dr.trade_id,
               COALESCE(lu.email, 'N/A') AS email,
               dr.amount,
               dr.type,
               dr.status,
               dr.transaction_proof,
               dr.deposit_address,           -- added deposit_address
               dr.comment AS admin_comment,
               dr.created_at,
               'request' AS source
        FROM deposit_requests dr
        LEFT JOIN liveaccounts l ON l.trade_id = dr.trade_id
        LEFT JOIN loginusers lu ON lu.id = l.user_id

        UNION ALL

        SELECT wd.id AS request_id,
               wd.trade_id,
               wd.email,
               wd.deposit_amount AS amount,
               wd.deposit_type AS type,
               CASE wd.Status
                    WHEN 1 THEN 'approved'
                    WHEN 2 THEN 'rejected'
                    ELSE 'unknown'
               END AS status,
               wd.image AS transaction_proof,
               '' AS deposit_address,       -- placeholder for wallet_deposit
               wd.AdminRemark AS admin_comment,
               wd.deposed_date AS created_at,
               'approved' AS source
        FROM wallet_deposit wd
    ) AS combined
";

if ($filterStatus) {
    $filterStatus = $conn->real_escape_string($filterStatus);
    $query .= " WHERE status = '$filterStatus'";
}

$query .= " ORDER BY created_at DESC";

// -------------------- EXECUTE --------------------
$result = $conn->query($query);

if ($result) {
    $deposits = [];
    while ($row = $result->fetch_assoc()) {
        $deposits[] = $row;
    }
    echo json_encode(["status" => "success", "data" => $deposits]);
} else {
    echo json_encode(["status" => "error", "message" => $conn->error]);
}
