<?php
// File: API_KONEKSI/riwayat/get_riwayat.php
error_reporting(0);
header('Content-Type: application/json');
include '../config/koneksi.php';

include '../config/middleware.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $payload = authenticateJWT();
    $user_id = $payload['user_id'] ?? '';
    
    $status_filter = $_POST['status_filter'] ?? 'Semua';

    $query = "SELECT r.reservasi_id, r.created_at, r.reservasi_st, p.paket_nm, p.thumbnail_foto, r.booking_tgl, r.booking_jam, r.final_harga 
              FROM dat_reservasi r 
              JOIN mst_paket p ON r.paket_id = p.paket_id 
              WHERE r.user_id = ?";

    // Filter yang SANGAT KETAT: tidak ada penggabungan status yang ambigu
    if ($status_filter == 'Pending') {
        $query .= " AND r.reservasi_st = 'Pending'";
    } else if ($status_filter == 'Sukses') {
        $query .= " AND (r.reservasi_st = 'Selesai' OR r.reservasi_st = 'Selesai Sempurna' OR r.reservasi_st = 'Verified' OR r.reservasi_st = 'Proses')";
    } else if ($status_filter == 'Dibatalkan') {
        $query .= " AND r.reservasi_st IN ('Dibatalkan', 'Batal')";
    }

    $query .= " ORDER BY r.created_at DESC";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("s", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();

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

    echo json_encode(["status" => "sukses", "data" => $data]);
    $stmt->close();
    $conn->close();
}
?>