<?php
// ===== CORS =====
header("Access-Control-Allow-Origin: *"); 
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Access-Control-Max-Age: 86400"); 

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

header("Content-Type: application/json");

include "config.php";

// Filters
$search    = $_GET['search'] ?? '';
$status    = $_GET['status'] ?? 'all';
$startDate = $_GET['start_date'] ?? '';
$endDate   = $_GET['end_date'] ?? '';

// Combined query to get deposits and withdrawals with client info
$query = "
    SELECT 
        t.id,
        t.datetime,
        la.account_name AS client,
        t.trade_id,
        t.notes,
        CASE WHEN t.type = 'Deposit' THEN t.amount ELSE 0 END AS deposit,
        CASE WHEN t.type = 'Withdrawal' THEN t.amount ELSE 0 END AS withdraw,
        t.payment_method,
        t.status,
        la.email
    FROM (
        SELECT id, trade_id, deposit_amount AS amount, 'Deposit' AS type, deposed_date AS datetime, deposit_type AS payment_method, Status AS status, '' AS notes
        FROM wallet_deposit
        UNION ALL
        SELECT id, trade_id, withdraw_amount AS amount, 'Withdrawal' AS type, withdraw_date AS datetime, withdraw_type AS payment_method, Status AS status, '' AS notes
        FROM wallet_withdraw
    ) AS t
    LEFT JOIN liveaccounts la ON t.trade_id = la.trade_id
    WHERE 1
";

// Apply search filter
$params = [];
if (!empty($search)) {
    $query .= " AND (la.account_name LIKE ? OR t.trade_id LIKE ?)";
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

// Filter by status
if ($status !== 'all') {
    $query .= " AND t.status = ?";
    $params[] = $status;
}

// Date range filter
if (!empty($startDate) && !empty($endDate)) {
    $query .= " AND DATE(t.datetime) BETWEEN ? AND ?";
    $params[] = $startDate;
    $params[] = $endDate;
}

$query .= " ORDER BY t.datetime DESC";

$stmt = $conn->prepare($query);

// Bind parameters dynamically
if ($params) {
    $types = str_repeat("s", count($params));
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$result = $stmt->get_result();

$ledgerData = [];
$totalDeposits = 0;
$totalWithdrawals = 0;

while ($row = $result->fetch_assoc()) {
    $deposit = is_numeric($row['deposit']) ? (float)$row['deposit'] : 0;
    $withdraw = is_numeric($row['withdraw']) ? (float)$row['withdraw'] : 0;

    $ledgerData[] = [
        "id"             => $row['id'],
        "datetime"       => $row['datetime'],
        "client"         => $row['client'] ?? '',
        "trade_id"       => $row['trade_id'],
        "notes"          => $row['notes'],
        "deposit"        => $deposit,
        "withdraw"       => $withdraw,
        "payment_method" => $row['payment_method'] ?? '',
        "status"         => $row['status'] ?? '',
        "email"          => $row['email'] ?? ''
    ];

    $totalDeposits += $deposit;
    $totalWithdrawals += $withdraw;
}

$response = [
    "status"  => "success",
    "summary" => [
        "deposits"     => $totalDeposits,
        "withdrawals"  => $totalWithdrawals,
        "net_deposit"  => $totalDeposits - $totalWithdrawals
    ],
    "data" => $ledgerData
];

echo json_encode($response);

$stmt->close();
$conn->close();
?>
