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

date_default_timezone_set('Asia/Jakarta');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $reservasi_id = $_POST['reservasi_id'] ?? '';
    $booking_tgl = $_POST['booking_tgl'] ?? ''; // Format: YYYY-MM-DD
    $booking_jam = $_POST['booking_jam'] ?? ''; // Format: HH:MM:SS atau HH:MM

    if (empty($reservasi_id) || empty($booking_tgl) || empty($booking_jam)) {
        echo json_encode(["status" => "gagal", "pesan" => "ID Reservasi, Tanggal Baru, dan Jam Baru wajib diisi!"]);
        exit;
    }

    // 1. Ambil detail reservasi yang sekarang
    $query = "SELECT reservasi_st, reschedule_count, 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" => "Reservasi tidak ditemukan!"]);
        exit;
    }

    $status_sekarang = $reservasi['reservasi_st'];
    $reschedule_count = intval($reservasi['reschedule_count']);
    $tgl_sebelumnya = $reservasi['booking_tgl'];
    $jam_sebelumnya = $reservasi['booking_jam'];

    // 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']));

    // 2. Validasi Batasan Status (Hanya Verified, Proses, atau Pending yang sudah dibayar)
    $status_lower = strtolower($status_sekarang);
    if (!in_array($status_lower, ['verified', 'proses', 'pending']) || ($status_lower === 'pending' && !$is_paid)) {
        echo json_encode(["status" => "gagal", "pesan" => "Hanya pesanan yang sudah dibayar yang dapat di-reschedule!"]);
        exit;
    }

    // 3. Validasi Batasan Kuota Reschedule (Maksimal 1 kali)
    if ($reschedule_count >= 1) {
        echo json_encode(["status" => "gagal", "pesan" => "Batas maksimal reschedule (1 kali) telah tercapai untuk pesanan ini!"]);
        exit;
    }

    $waktu_sekarang = time();

    // 4. Validasi Waktu Jadwal Awal (Harus belum terlewati)
    // Hanya dievaluasi jika status pesanan adalah Verified atau Proses (Sudah ACC)
    if (in_array($status_lower, ['verified', 'proses'])) {
        $jadwal_awal_str = $tgl_sebelumnya . ' ' . $jam_sebelumnya;
        $waktu_awal = strtotime($jadwal_awal_str);

        $selisih_detik = $waktu_awal - $waktu_sekarang;
        
        // Hanya cek jika jadwal awal sudah terlewati
        if ($selisih_detik < 0) {
            echo json_encode(["status" => "gagal", "pesan" => "Reschedule tidak dapat dilakukan setelah jadwal pemotretan asli terlewati!"]);
            exit;
        }
    }

    // 4.5. Validasi jadwal baru (harus di masa depan)
    $jadwal_baru_str = $booking_tgl . ' ' . $booking_jam;
    $waktu_baru = strtotime($jadwal_baru_str);

    if ($waktu_baru <= $waktu_sekarang) {
        echo json_encode(["status" => "gagal", "pesan" => "Jadwal baru harus dipilih di masa depan!"]);
        exit;
    }

    // Validasi Batas Maksimal 30 Hari dari Sekarang
    $waktu_max = strtotime('+30 days 23:59:59');

    if ($waktu_baru > $waktu_max) {
        echo json_encode(["status" => "gagal", "pesan" => "Reschedule hanya dapat dilakukan maksimal 30 hari ke depan dari sekarang!"]);
        exit;
    }

    // 5. Cek Apakah Tanggal Baru Tutup (Jadwal Tutup)
    $query_tutup = "SELECT tutup_id FROM dat_jadwal_tutup WHERE tgl_tutup = ? AND deleted_st = 0";
    $stmt_tutup = $conn->prepare($query_tutup);
    $stmt_tutup->bind_param("s", $booking_tgl);
    $stmt_tutup->execute();
    $stmt_tutup->store_result();
    if ($stmt_tutup->num_rows > 0) {
        echo json_encode(["status" => "gagal", "pesan" => "Tanggal yang Anda pilih sedang libur/tutup. Silakan pilih tanggal lain!"]);
        $stmt_tutup->close();
        exit;
    }
    $stmt_tutup->close();

    // 6. Cek Apakah Jam & Tanggal Baru Bentrok dengan booking lain
    $query_bentrok = "SELECT reservasi_id FROM dat_reservasi WHERE booking_tgl = ? AND booking_jam = ? AND reservasi_st NOT IN ('Batal', 'Dibatalkan') AND reservasi_id != ? AND deleted_st = 0";
    $stmt_bentrok = $conn->prepare($query_bentrok);
    $stmt_bentrok->bind_param("sss", $booking_tgl, $booking_jam, $reservasi_id);
    $stmt_bentrok->execute();
    $stmt_bentrok->store_result();
    if ($stmt_bentrok->num_rows > 0) {
        echo json_encode(["status" => "gagal", "pesan" => "Jadwal pada jam tersebut sudah dipesan. Silakan pilih jam lain!"]);
        $stmt_bentrok->close();
        exit;
    }
    $stmt_bentrok->close();

    $conn->begin_transaction();

    try {
        $reschedule_count_baru = $reschedule_count + 1;
        $status_baru = $status_sekarang; // Tetap Verified / Proses

        $query_update = "UPDATE dat_reservasi 
                          SET booking_tgl = ?, 
                              booking_jam = ?, 
                              booking_tgl_lama = ?, 
                              booking_jam_lama = ?, 
                              reservasi_st = ?,
                              reschedule_count = ?,
                              created_at = CURRENT_TIMESTAMP
                          WHERE reservasi_id = ?";
        $stmt_update = $conn->prepare($query_update);
        $stmt_update->bind_param("sssssis", $booking_tgl, $booking_jam, $tgl_sebelumnya, $jam_sebelumnya, $status_baru, $reschedule_count_baru, $reservasi_id);
        
        if (!$stmt_update->execute()) {
            throw new Exception("Gagal mengupdate jadwal reservasi.");
        }
        $stmt_update->close();

        // --- NOTIFIKASI KE ADMIN (RESCHEDULE) ---
        $q_info = $conn->prepare("
            SELECT u.lengkap_nm, p.paket_nm 
            FROM dat_reservasi r
            JOIN mst_user u ON r.user_id = u.user_id
            JOIN mst_paket p ON r.paket_id = p.paket_id
            WHERE r.reservasi_id = ?
        ");
        $q_info->bind_param("s", $reservasi_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 = "Jadwal Reschedule 🗓️";
            $pesan_notif = "Pelanggan a/n " . $nama_pelanggan . " memindahkan jadwal pemotretan " . $nama_paket . " ke " . $booking_tgl . " jam " . $booking_jam . " (sebelumnya " . $tgl_sebelumnya . " " . $jam_sebelumnya . ").";
            $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();
        // -------------------------------------------------

        $conn->commit();

        // Fetch pembayaran_id
        $query_pembayaran = "SELECT pembayaran_id FROM dat_pembayaran WHERE reservasi_id = ?";
        $stmt_pembayaran = $conn->prepare($query_pembayaran);
        $stmt_pembayaran->bind_param("s", $reservasi_id);
        $stmt_pembayaran->execute();
        $result_pembayaran = $stmt_pembayaran->get_result();
        $row_pembayaran = $result_pembayaran->fetch_assoc();
        $pembayaran_id = $row_pembayaran['pembayaran_id'] ?? 0;
        $stmt_pembayaran->close();

        echo json_encode([
            "status" => "sukses",
            "pesan" => "Jadwal berhasil dipindahkan!",
            "data" => [
                "booking_tgl" => $booking_tgl,
                "booking_jam" => $booking_jam,
                "pembayaran_id" => $pembayaran_id,
                "reservasi_st" => $status_baru
            ]
        ]);

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