<?php
// File: API_KONEKSI/reservasi/buat_pesanan.php
header('Content-Type: application/json');
include '../config/koneksi.php';
include '../config/middleware.php';
include '../config/id_generator.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $payload = authenticateJWT();
    $user_id = $payload['user_id'] ?? ''; // Sesuaikan dengan session/auth
    $paket_id = $_POST['paket_id'] ?? '';
    $promo_id = !empty($_POST['promo_id']) ? $_POST['promo_id'] : null;
    $diskon_nominal = $_POST['diskon_nominal'] ?? 0;
    $booking_tgl = $_POST['booking_tgl'] ?? '';
    $booking_jam = $_POST['booking_jam'] ?? '';
    $final_harga = $_POST['final_harga'] ?? 0;
    $catatan_tx = $_POST['catatan_tx'] ?? null;
    $reservasi_st = 'Pending'; // Default state

    if (empty($paket_id) || empty($booking_tgl) || empty($booking_jam) || empty($final_harga)) {
        echo json_encode(["status" => "gagal", "pesan" => "Data wajib (Jadwal & Paket) tidak boleh kosong!", "data" => []]);
        exit;
    }

    // --- CEK BENTROK JADWAL SEBELUM INSERT ---
    // Menggunakan prepared statement juga agar tetap aman
    $cek_query = "SELECT reservasi_id FROM dat_reservasi WHERE booking_tgl = ? AND booking_jam = ? AND reservasi_st != 'Batal'";
    $stmt_cek = $conn->prepare($cek_query);
    $stmt_cek->bind_param("ss", $booking_tgl, $booking_jam);
    $stmt_cek->execute();
    $stmt_cek->store_result();

    if ($stmt_cek->num_rows > 0) {
        // Jika jadwal sudah ada yang punya, hentikan proses dan kirim response gagal
        echo json_encode(["status" => "gagal", "pesan" => "Mohon maaf, jadwal pada tanggal dan jam tersebut sudah dibooking. Silakan pilih jam lain.", "data" => []]);
        $stmt_cek->close();
        exit;
    }
    $stmt_cek->close();
    // -----------------------------------------

    // JIKA JADWAL KOSONG, LANJUTKAN PROSES INSERT
    $reservasi_id = generateReservasiId($conn);
    $query = "INSERT INTO dat_reservasi (reservasi_id, user_id, paket_id, promo_id, diskon_nominal, booking_tgl, booking_jam, final_harga, catatan_tx, reservasi_st) 
              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param("ssssdssdss", $reservasi_id, $user_id, $paket_id, $promo_id, $diskon_nominal, $booking_tgl, $booking_jam, $final_harga, $catatan_tx, $reservasi_st);

    if ($stmt->execute()) {
        echo json_encode([
            "status" => "sukses", 
            "pesan" => "Booking berhasil dibuat.", 
            "data" => ["reservasi_id" => $reservasi_id]
        ]);
    } else {
        echo json_encode(["status" => "gagal", "pesan" => "Gagal menyimpan data: " . $stmt->error, "data" => []]);
    }
    $stmt->close();
} else {
    echo json_encode(["status" => "gagal", "pesan" => "Metode tidak diizinkan", "data" => []]);
}
$conn->close();
?>
