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

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

    if (empty($reservasi_id)) {
        echo json_encode(["status" => "gagal", "pesan" => "ID tidak valid", "data" => []]);
        exit;
    }

    // PERBAIKAN: Menambahkan pb.transfer_bukti untuk cek apakah sudah upload bukti
    $query = "SELECT r.reservasi_id, r.created_at as tgl_transaksi, r.reservasi_st, r.booking_tgl, r.booking_jam, r.catatan_tx, r.final_harga, r.diskon_nominal,
                     r.reschedule_count, r.booking_tgl_lama, r.booking_jam_lama, r.tambahan_orang, r.sewa_kostum, pr.kode_promo, r.promo_id,
                     p.paket_id, p.paket_nm, p.normal_harga, p.durasi_menit, p.thumbnail_foto, 
                     mb.nama_metode, pb.metode_id, pb.pembayaran_id,
                     pb.transfer_bukti, pb.expired_at,
                     d.gdrive_link, d.upload_tgl
              FROM dat_reservasi r 
              JOIN mst_paket p ON r.paket_id = p.paket_id 
              LEFT JOIN mst_promo pr ON r.promo_id = pr.promo_id
              LEFT JOIN dat_pembayaran pb ON r.reservasi_id = pb.reservasi_id
              LEFT JOIN mst_metode_bayar mb ON pb.metode_id = mb.metode_id
              LEFT JOIN dat_distribusi d ON r.reservasi_id = d.reservasi_id
              WHERE r.reservasi_id = ?";

    $stmt = $conn->prepare($query);
    $stmt->bind_param("s", $reservasi_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        if (empty($row['reservasi_st'])) $row['reservasi_st'] = 'Pending';
        $row['nama_metode'] = $row['nama_metode'] ?? 'Belum Dipilih';
        $row['transfer_bukti'] = $row['transfer_bukti'] ?? '';
        $row['gdrive_link'] = $row['gdrive_link'] ?? '';
        
        // Hitung sisa_detik untuk countdown pembayaran
        date_default_timezone_set('Asia/Jakarta');
        $expired_at = $row['expired_at'] ?? '';
        if (!empty($expired_at)) {
            $expired_time = strtotime($expired_at);
            $current_time = time();
            $sisa_detik = $expired_time - $current_time;
            $row['sisa_detik'] = $sisa_detik > 0 ? $sisa_detik : 0;
        } else {
            $row['sisa_detik'] = 0;
        }
        
        echo json_encode(["status" => "sukses", "pesan" => "Data ditemukan", "data" => [$row]]);
    } else {
        echo json_encode(["status" => "gagal", "pesan" => "Data tidak ditemukan", "data" => []]);
    }
    $stmt->close();
    $conn->close();
}
?>
