<?php
// File: api_koneksi/reservasi/batalkan_reservasi.php
header('Content-Type: application/json');
include '../config/koneksi.php';

date_default_timezone_set('Asia/Jakarta');

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

    if (empty($reservasi_id)) {
        echo json_encode(["status" => "gagal", "pesan" => "ID Reservasi tidak boleh kosong!"]);
        exit;
    }

    // 1. Ambil status, promo, tanggal, jam dari reservasi
    $query = "SELECT reservasi_st, promo_id, booking_tgl, booking_jam FROM dat_reservasi WHERE reservasi_id = ? AND deleted_st = 0";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("s", $reservasi_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $reservasi = $result->fetch_assoc();
    $stmt->close();

    if (!$reservasi) {
        echo json_encode(["status" => "gagal", "pesan" => "Data reservasi tidak ditemukan!"]);
        exit;
    }

    $status_sekarang = $reservasi['reservasi_st'];
    $promo_id = $reservasi['promo_id'];
    $booking_tgl = $reservasi['booking_tgl'];
    $booking_jam = $reservasi['booking_jam'];

    // Validasi status yang boleh dibatalkan
    if (in_array(strtolower($status_sekarang), ['selesai', 'selesai sempurna', 'dibatalkan', 'batal'])) {
        echo json_encode(["status" => "gagal", "pesan" => "Reservasi sudah selesai atau sudah dibatalkan tidak bisa dibatalkan lagi!"]);
        exit;
    }

    // Cek apakah reservasi sudah dibayar (punya bukti bayar dan berstatus Verified atau Pending)
    $query_pay = "SELECT validasi_st, transfer_bukti FROM dat_pembayaran WHERE reservasi_id = ?";
    $stmt_pay = $conn->prepare($query_pay);
    $stmt_pay->bind_param("s", $reservasi_id);
    $stmt_pay->execute();
    $result_pay = $stmt_pay->get_result();
    $pay = $result_pay->fetch_assoc();
    $stmt_pay->close();

    $bukti_bayar = $pay['transfer_bukti'] ?? '';
    $validasi_st = $pay['validasi_st'] ?? 'Pending';
    $is_paid = (!empty($bukti_bayar) && in_array($validasi_st, ['Verified', 'Pending']));

    // Enforce check if the session has already started or passed
    if ($is_paid) {
        $jadwal_str = $booking_tgl . ' ' . $booking_jam;
        $waktu_booking = new DateTime($jadwal_str);
        $waktu_sekarang = new DateTime();
        
        if ($waktu_booking <= $waktu_sekarang) {
            echo json_encode(["status" => "gagal", "pesan" => "Pembatalan tidak dapat dilakukan setelah sesi pemotretan dimulai atau terlewati!"]);
            exit;
        }
    }

    $conn->begin_transaction();

    try {
        $reservasi_st_baru = $is_paid ? 'Dibatalkan' : 'Batal';

        // 2. Update status reservasi
        $query_update = "UPDATE dat_reservasi SET reservasi_st = ? WHERE reservasi_id = ?";
        $stmt_update = $conn->prepare($query_update);
        $stmt_update->bind_param("ss", $reservasi_st_baru, $reservasi_id);
        if (!$stmt_update->execute()) {
            throw new Exception("Gagal mengupdate status reservasi.");
        }
        $stmt_update->close();

        // 3. Update status pembayaran menjadi Rejected/Expired jika dibatalkan
        $validasi_st_baru = $is_paid ? 'Rejected' : 'Expired';
        $query_pay = "UPDATE dat_pembayaran SET validasi_st = ? WHERE reservasi_id = ?";
        $stmt_pay = $conn->prepare($query_pay);
        $stmt_pay->bind_param("ss", $validasi_st_baru, $reservasi_id);
        $stmt_pay->execute();
        $stmt_pay->close();

        // 4. Kembalikan kuota promo jika digunakan
        if (!empty($promo_id)) {
            $query_promo = "UPDATE mst_promo SET total_terpakai = GREATEST(0, 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();
        }

        $conn->commit();

        echo json_encode([
            "status" => "sukses",
            "pesan" => "Reservasi berhasil dibatalkan!"
        ]);

    } 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();
?>
