<?php
header('Content-Type: application/json');
include '../config/koneksi.php';

$filter = $_GET['filter'] ?? 'Semua';
$search = $_GET['search'] ?? '';
$tanggal = $_GET['tanggal'] ?? ''; // Sekarang defaultnya kosong

$conditions = ["p.validasi_st != 'Expired'"];
$params = [];
$types = "";

// HANYA filter tanggal jika $tanggal TIDAK kosong
if (!empty($tanggal)) {
    $conditions[] = "r.booking_tgl = ?";
    $params[] = $tanggal;
    $types .= "s";
}

// Filter Status
if ($filter === 'Pending') {
    $conditions[] = "p.validasi_st = 'Pending'";
} else if ($filter === 'Lunas') {
    $conditions[] = "p.validasi_st = 'Verified'";
} else if ($filter === 'Batal') {
    $conditions[] = "p.validasi_st = 'Rejected'";
}

// Filter Search
if (!empty($search)) {
    $conditions[] = "u.lengkap_nm LIKE ?";
    $params[] = "%$search%";
    $types .= "s";
}

$whereSql = count($conditions) > 0 ? "WHERE " . implode(" AND ", $conditions) : "";

$query = "SELECT p.pembayaran_id, r.reservasi_id, r.booking_tgl, r.final_harga, p.validasi_st, 
                 u.lengkap_nm AS nama_lengkap, pk.paket_nm AS nama_paket 
          FROM dat_pembayaran p 
          JOIN dat_reservasi r ON p.reservasi_id = r.reservasi_id 
          JOIN mst_user u ON r.user_id = u.user_id 
          JOIN mst_paket pk ON r.paket_id = pk.paket_id 
          $whereSql 
          ORDER BY p.bayar_tgl DESC";

$stmt = $conn->prepare($query);
if (!empty($params)) $stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();

$data = [];
while ($row = $result->fetch_assoc()) {
    $row['invoice'] = $row['reservasi_id'];
    $data[] = $row;
}

// STATISTIK (Bisa tetap harian atau buat global, di sini saya buat global jika tanggal kosong)
$statQuery = "SELECT COUNT(*) as total_data, 
                     SUM(CASE WHEN p.validasi_st = 'Pending' THEN 1 ELSE 0 END) as menunggu, 
                     SUM(CASE WHEN p.validasi_st = 'Verified' THEN 1 ELSE 0 END) as lunas, 
                     SUM(CASE WHEN p.validasi_st = 'Rejected' THEN 1 ELSE 0 END) as dibatalkan 
              FROM dat_pembayaran p
              JOIN dat_reservasi r ON p.reservasi_id = r.reservasi_id
              WHERE p.validasi_st != 'Expired'";

if (!empty($tanggal)) {
    $statQuery .= " AND r.booking_tgl = '$tanggal'";
}

$stats = $conn->query($statQuery)->fetch_assoc();

echo json_encode(["status" => "sukses", "statistik" => $stats, "data" => $data]);
?>