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

// Set timezone agar sesuai dengan waktu Indonesia (WIB)
date_default_timezone_set('Asia/Jakarta');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $payload = authenticateJWT();
    $user_id = $payload['user_id'] ?? ''; 
    $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'] ?? '';
    $tambahan_orang = $_POST['tambahan_orang'] ?? 0;
    $sewa_kostum = !empty($_POST['sewa_kostum']) ? $_POST['sewa_kostum'] : "Tidak Sewa";
    $final_harga = $_POST['final_harga'] ?? 0;
    $catatan_tx = !empty($_POST['catatan_tx']) ? $_POST['catatan_tx'] : null;
    $metode_id = $_POST['metode_id'] ?? ''; 
    $reservasi_st = 'Pending';

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

    // --- CEK BENTROK JADWAL SEBELUM INSERT ---
    $cek_query = "SELECT reservasi_id FROM dat_reservasi WHERE booking_tgl = ? AND booking_jam = ? AND reservasi_st NOT IN ('Batal', 'Dibatalkan') AND deleted_st = 0";
    $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) {
        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();


    // Handle File Upload Syarat Promo (Jika Ada)
    $foto_syarat = null;
    if (isset($_FILES['foto_syarat']) && $_FILES['foto_syarat']['error'] == 0) {
        $upload_dir = '../uploads/syarat/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        $file_extension = strtolower(pathinfo($_FILES['foto_syarat']['name'], PATHINFO_EXTENSION));
        $allowed_extensions = array("jpg", "jpeg", "png");
        
        if (!in_array($file_extension, $allowed_extensions)) {
            echo json_encode(["status" => "gagal", "pesan" => "Hanya file JPG, JPEG, dan PNG yang diizinkan!"]);
            exit;
        }

        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $_FILES['foto_syarat']['tmp_name']);
        finfo_close($finfo);
        
        $allowed_mime_types = array("image/jpeg", "image/png");
        if (!in_array($mime, $allowed_mime_types)) {
            echo json_encode(["status" => "gagal", "pesan" => "File syarat promo bukan gambar yang valid!"]);
            exit;
        }

        $file_name = time() . '_' . rand(1000, 9999) . '_' . basename($_FILES['foto_syarat']['name']);
        $file_name = preg_replace('/[^A-Za-z0-9.\-_]/', '', $file_name);
        $target_file = $upload_dir . $file_name;
        
        if (move_uploaded_file($_FILES['foto_syarat']['tmp_name'], $target_file)) {
            $foto_syarat = $file_name;
        } else {
            echo json_encode(["status" => "gagal", "pesan" => "Gagal mengupload foto syarat promo!"]);
            exit;
        }
    }

    $reservasi_id = generateReservasiId($conn);
    $pembayaran_id = generatePembayaranId($conn);

    $conn->begin_transaction();

    try {
        // 1. INSERT RESERVASI
        $query_res = "INSERT INTO dat_reservasi (reservasi_id, user_id, paket_id, promo_id, diskon_nominal, foto_syarat_promo, booking_tgl, booking_jam, tambahan_orang, sewa_kostum, final_harga, catatan_tx, reservasi_st) 
                      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt_res = $conn->prepare($query_res);
        $stmt_res->bind_param("ssssdsssisdss", $reservasi_id, $user_id, $paket_id, $promo_id, $diskon_nominal, $foto_syarat, $booking_tgl, $booking_jam, $tambahan_orang, $sewa_kostum, $final_harga, $catatan_tx, $reservasi_st);
        
        if (!$stmt_res->execute()) {
            throw new Exception("Reservasi Error : " . $stmt_res->error);
        }
        $stmt_res->close();

        // 2. JIKA ADA PROMO, UPDATE KUOTA PROMO
        if (!empty($promo_id)) {
            $query_promo = "UPDATE mst_promo SET total_terpakai = total_terpakai + 1 WHERE promo_id = ?";
            $stmt_promo = $conn->prepare($query_promo);
            $stmt_promo->bind_param("s", $promo_id);
            $stmt_promo->execute();
            $stmt_promo->close();
        }

        // 3. TENTUKAN WAKTU EXPIRED (5 MENIT DARI SEKARANG)
        $expired_at = date('Y-m-d H:i:s', strtotime('+5 minutes'));

        // 4. INSERT PEMBAYARAN BESERTA EXPIRED_AT
        $query_pay = "INSERT INTO dat_pembayaran (pembayaran_id, reservasi_id, metode_id, pengirim_nm, asal_bank, transfer_bukti, validasi_st, expired_at) 
                      VALUES (?, ?, ?, '', '', '', 'Pending', ?)";
        $stmt_pay = $conn->prepare($query_pay);
        $stmt_pay->bind_param("ssss", $pembayaran_id, $reservasi_id, $metode_id, $expired_at);
        
        if (!$stmt_pay->execute()) {
            throw new Exception("Pembayaran Error : " . $stmt_pay->error);
        }
        $stmt_pay->close();

        $conn->commit();

        // --- LOGIKA NOTIFIKASI KE ADMIN (BOOKING BARU) ---
        $q_info = $conn->prepare("SELECT u.lengkap_nm, p.paket_nm FROM mst_user u, mst_paket p WHERE u.user_id = ? AND p.paket_id = ?");
        $q_info->bind_param("ss", $user_id, $paket_id);
        $q_info->execute();
        $r_info = $q_info->get_result();
        if ($row_info = $r_info->fetch_assoc()) {
            $nama_pelanggan = $row_info['lengkap_nm'];
            $nama_paket = $row_info['paket_nm'];
            
            $judul_notif = "Booking Baru Masuk 📸";
            $pesan_notif = "Pelanggan a/n " . $nama_pelanggan . " baru saja melakukan booking paket " . $nama_paket . " untuk jadwal " . $booking_tgl . " " . $booking_jam . ".";
            $tipe_notif = "transaksi";

            $query_admin = "SELECT user_id FROM mst_user WHERE role_nm = 'Admin' AND active_st = 1";
            $res_admin = $conn->query($query_admin);
            if ($res_admin && $res_admin->num_rows > 0) {
                $stmt_notif = $conn->prepare("INSERT INTO dat_notifikasi (notif_id, user_id, tipe_notif, target_id, judul_tx, pesan_tx) VALUES (?, ?, ?, ?, ?, ?)");
                while ($row_admin = $res_admin->fetch_assoc()) {
                    $target_admin = $row_admin['user_id'];
                    $notif_id = generateNotifId($conn);
                    $stmt_notif->bind_param("ssssss", $notif_id, $target_admin, $tipe_notif, $reservasi_id, $judul_notif, $pesan_notif);
                    $stmt_notif->execute();
                }
                $stmt_notif->close();
            }
        }
        $q_info->close();
        // -------------------------------------------------

        echo json_encode([
            "status" => "sukses",
            "pesan" => "Booking berhasil dibuat!",
            "data" => [
                "reservasi_id" => $reservasi_id,
                "pembayaran_id" => $pembayaran_id
            ]
        ]);

    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(["status" => "gagal", "pesan" => $e->getMessage()]);
    }
} else {
    echo json_encode(["status" => "gagal", "pesan" => "Metode request tidak valid"]);
}
$conn->close();
?>
