<?php
// File: API_KONEKSI/admin/laporan/get_laporan.php
header('Content-Type: application/json');
include '../../config/koneksi.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $start_date = $_POST['start_date'] ?? '';
    $end_date = $_POST['end_date'] ?? '';

    if (empty($start_date) || empty($end_date)) {
        echo json_encode(["status" => "gagal", "pesan" => "Pilih tanggal awal dan akhir terlebih dahulu", "data" => []]);
        exit;
    }

    // REVISI: Hanya mengambil data yang status pembayarannya sudah 'Verified' (LUNAS)
    $query = "SELECT 
                u.lengkap_nm, 
                r.booking_tgl, 
                r.booking_jam, 
                r.final_harga, 
                p.validasi_st
              FROM dat_reservasi r
              JOIN mst_user u ON r.user_id = u.user_id
              JOIN dat_pembayaran p ON r.reservasi_id = p.reservasi_id
              WHERE r.booking_tgl BETWEEN ? AND ? 
              AND r.deleted_st = 0
              AND p.validasi_st = 'Verified' 
              ORDER BY r.booking_tgl ASC, r.booking_jam ASC";

    $stmt = $conn->prepare($query);
    $stmt->bind_param("ss", $start_date, $end_date);
    $stmt->execute();
    $result = $stmt->get_result();

    $data = [];
    $total_pendapatan = 0;

    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
        // Karena semua data yang ditarik pasti Verified, kita bisa langsung jumlahkan
        $total_pendapatan += $row['final_harga'];
    }

    if (count($data) > 0) {
        echo json_encode([
            "status" => "sukses", 
            "pesan" => "Data ditemukan", 
            "total_pendapatan" => $total_pendapatan,
            "data" => $data
        ]);
    } else {
        echo json_encode([
            "status" => "kosong", 
            "pesan" => "Tidak ada pendapatan pada tanggal tersebut", 
            "total_pendapatan" => 0,
            "data" => []
        ]);
    }
    $stmt->close();
}
$conn->close();
?>