<?php
// ===============================
// 🌐 CORS HEADERS
// ===============================
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";

// ===============================
// 🧾 INPUT FILTERS
// ===============================
$search    = trim($_GET['search'] ?? '');
$status    = trim($_GET['status'] ?? 'all');
$startDate = trim($_GET['start_date'] ?? '');
$endDate   = trim($_GET['end_date'] ?? '');

// ===============================
// 🧮 MAIN QUERY
// ===============================
$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,
        GROUP_CONCAT(DISTINCT dr.transaction_proof ORDER BY dr.id SEPARATOR ',') AS transaction_proof
    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
    LEFT JOIN deposit_requests dr ON t.trade_id = dr.trade_id
    WHERE 1
";

// ===============================
// 🔍 FILTER CONDITIONS
// ===============================
$params = [];

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

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

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

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

// ===============================
// ⚙️ PREPARE & EXECUTE
// ===============================
$stmt = $conn->prepare($query);

if ($stmt === false) {
    echo json_encode(["status" => "error", "message" => "Database query preparation failed"]);
    exit;
}

if (!empty($params)) {
    $types = str_repeat("s", count($params));
    $stmt->bind_param($types, ...$params);
}

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

// ===============================
// 📊 BUILD RESPONSE
// ===============================
$ledgerData = [];
$totalDeposits = 0;
$totalWithdrawals = 0;
$totalDepositCount = 0;      // ✅ new
$totalWithdrawalCount = 0;   // ✅ new

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

    // Convert comma-separated proofs to array
    $proofs = [];
    if (!empty($row['transaction_proof'])) {
        $proofs = array_map('trim', explode(',', $row['transaction_proof']));
    }

    $ledgerData[] = [
        "id"                => (int)$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"            => (int)($row['status'] ?? 0),
        "email"             => $row['email'] ?? '',
        "transaction_proof" => $proofs
    ];

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

    if ($deposit > 0) $totalDepositCount++;      // ✅ count deposits
    if ($withdraw > 0) $totalWithdrawalCount++;  // ✅ count withdrawals
}

// ===============================
// 🧾 FINAL OUTPUT
// ===============================
$response = [
    "status" => "success",
    "summary" => [
        "deposits"            => $totalDeposits,
        "withdrawals"         => $totalWithdrawals,
        "deposit_count"       => $totalDepositCount,      // ✅ added
        "withdrawal_count"    => $totalWithdrawalCount,   // ✅ added
        // "net_deposit"         => $totalDeposits - $totalWithdrawals,
        // "net_withdrawal"      => $totalWithdrawals
    ],
    "data" => $ledgerData
];

echo json_encode($response, JSON_PRETTY_PRINT);

// ===============================
// 🧹 CLEANUP
// ===============================
$stmt->close();
$conn->close();
?>
