<?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 wr.id AS request_id,
               wr.trade_id,
               COALESCE(lu.email, l.email, wr.email) AS email,
               wr.amount,
               wr.type,
               wr.status,
               wr.bank_details,
               wr.wallet_address,          -- added wallet_address
               wr.comment AS admin_comment,
               wr.created_at,
               'request' AS source
        FROM withdrawal_requests wr
        LEFT JOIN liveaccounts l ON l.trade_id = wr.trade_id
        LEFT JOIN loginusers lu ON lu.id = l.user_id

        UNION ALL

        SELECT ww.id AS request_id,
               ww.trade_id,
               ww.email,
               ww.withdraw_amount AS amount,
               ww.withdraw_type AS type,
               CASE ww.Status
                    WHEN 1 THEN 'approved'
                    WHEN 2 THEN 'rejected'
                    ELSE 'unknown'
               END AS status,
               '' AS bank_details,
               '' AS wallet_address,       -- placeholder for wallet_withdraw
               ww.AdminRemark AS admin_comment,
               ww.withdraw_date AS created_at,
               'approved' AS source
        FROM wallet_withdraw ww
    ) 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) {
    $withdrawals = [];
    while ($row = $result->fetch_assoc()) {
        $withdrawals[] = $row;
    }
    echo json_encode(["status" => "success", "data" => $withdrawals]);
} else {
    echo json_encode(["status" => "error", "message" => $conn->error]);
}
