@extends('layouts.user')

@section('title', 'Detail Paket Foto - Florist dan Self Photo Studio Nganjuk')

@section('content')
    <section class="section-detailfoto">
        <div class="container">
            <div class="row mb-3">
                <div class="col-12">
                    <a href="{{ route('booking.foto') }}" class="text-decoration-none text-muted small">
                        <i class="bi bi-arrow-left me-1"></i> Kembali ke Katalog
                    </a>
                </div>
            </div>

            {{-- Seluruh Konten dalam Form agar data Add-ons & Slot terkirim --}}
            <form id="form-booking" action="{{ route('formulir.foto') }}" method="GET">
                @csrf
                {{-- Kotak simpan data sementara di dalam form --}}
                <input type="hidden" name="tgl_booking" id="input_tgl_booking">
                <input type="hidden" name="jam_mulai" id="input_jam_mulai">
                <input type="hidden" name="jam_selesai" id="input_jam_selesai">
                <div id="data-paket" data-durasi="15"></div>
                <div class="row">
                    <div class="col-lg-6 mb-5" id="left-column">
                        <input type="hidden" name="id_paket" value="{{ $foto->id_paket }}">

                        <div class="row gx-3">
                            <div class="col-auto">
                                <div class="detailfoto-card p-2">
                                    <img src="{{ asset($foto->foto) }}" alt="{{ $foto->nama }}"
                                        class="detailfoto-thumb rounded-4">
                                </div>
                            </div>
                            <div class="col">
                                <div class="detailfoto-card p-3 h-100">
                                    <h3 class="detailfoto-product-title">{{ $foto->nama }}</h3>
                                    <div class="d-flex align-items-center gap-2">
                                        <h4 class="detailfoto-product-price mb-0">
                                            Rp {{ number_format($foto->harga, 0, ',', '.') }}
                                        </h4>
                                        <span class="text-muted">|</span>
                                        <span class="badge rounded-pill"
                                            style="background-color: #e6f0f0; color: #3B8181; font-weight: 500;">
                                            <i class="bi bi-clock me-1"></i> {{ $foto->durasi }} Menit Sesi
                                        </span>
                                    </div>
                                    <p class="detailfoto-product-desc mb-0 text-justify">{{ $foto->deskripsi }}</p>
                                </div>
                            </div>
                        </div>

                        <h5 class="detailfoto-addons-title mt-4">Additional</h5>
                        <div class="detailfoto-addons-wrapper">
                            @foreach ($additionals as $add)
                                <div class="detailfoto-addon-item">
                                    <div class="d-flex flex-column">
                                        <span class="detailfoto-addon-name">{{ $add->nama }}</span>
                                        <span class="detailfoto-addon-price">Rp
                                            {{ number_format($add->harga, 0, ',', '.') }}</span>
                                    </div>
                                    <div class="detailfoto-counter">
                                        <button type="button" class="btn-counter"
                                            onclick="updateCounter(this, -1)">-</button>
                                        <input type="text" name="addons[{{ $add->id_additional }}]" value="0"
                                            readonly>
                                        <button type="button" class="btn-counter"
                                            onclick="updateCounter(this, 1)">+</button>
                                    </div>
                                </div>
                            @endforeach
                        </div>

                        <div class="mt-4 text-center" id="btn-booking-wrapper">
                            <button type="button" class="btn btn-detailfoto-primary" onclick="showCalendar()">
                                Booking Slot Foto
                            </button>
                        </div>
                    </div>

                    <div class="col-lg-6 d-none" id="calendar-column">
                        <div class="detailfoto-calendar-box">
                            <div class="mb-4">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <span class="timer-alert-text">Slot Anda akan dibatalkan otomatis dalam</span>
                                    <span class="timer-badge" id="booking-timer">10:00</span>
                                </div>
                                <h4 class="schedule-title">Pilih Tanggal dan Waktu</h4>
                                <p class="small">Slot abu-abu berarti jadwal sudah penuh. Silakan pilih waktu lain yang
                                    tersedia.</p>
                            </div>

                            <div class="row g-4">
                                <div class="col-md-9 border-end pe-md-4" id="calendar-grid-wrapper">
                                    @include('user.components.calendar-grid')
                                </div>

                                <div class="col-md-3">
                                    <h6 class="mb-3 small">Jam Tersedia</h6>
                                    <div class="time-slot-container">
                                        @for ($hour = 9; $hour <= 20; $hour++)
                                            {{-- Slot Jam Genap (contoh: 09:00) --}}
                                            <button type="button" class="btn-time"
                                                data-time="{{ sprintf('%02d:00', $hour) }}">
                                                {{ sprintf('%02d:00', $hour) }} WIB
                                            </button>

                                            {{-- Slot Jam Setengah (contoh: 09:30) --}}
                                            <button type="button" class="btn-time"
                                                data-time="{{ sprintf('%02d:30', $hour) }}">
                                                {{ sprintf('%02d:30', $hour) }} WIB
                                            </button>
                                        @endfor
                                    </div>
                                </div>
                            </div>

                            <div class="d-flex gap-3 mt-4 pt-4">
                                <button type="button" class="btn btn-action-cancel flex-fill"
                                    onclick="hideCalendar()">Batalkan</button>
                                <button type="submit" class="btn btn-action-submit flex-fill">Pesan Sekarang</button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </section>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        // ============================================================
        // 1. VARIABLE GLOBAL & UTILITIES
        // ============================================================
        let countdown; // Variabel untuk menyimpan timer
        let isTimeUp = false;
        const durasiPaket = parseInt(document.getElementById('data-paket')?.dataset.durasi || 15);

        // Fungsi Update Counter (+/-) untuk Additional
        function updateCounter(btn, change) {
            const input = btn.parentElement.querySelector('input');
            let currentValue = parseInt(input.value) || 0;
            let newValue = currentValue + change;

            if (newValue < 0) newValue = 0; // Cegah minus
            input.value = newValue;
        }

        // Fungsi Tampilkan Kalender (Step 1 -> Step 2)
        function showCalendar() {
            document.getElementById('btn-booking-wrapper').style.display = 'none';

            // DISABLE KOLOM KIRI
            const leftColumn = document.getElementById('left-column');
            if (leftColumn) leftColumn.classList.add('disabled-section');

            const calendarCol = document.getElementById('calendar-column');
            if (calendarCol) {
                calendarCol.classList.remove('d-none');
                calendarCol.classList.add('fade-in-right');
                calendarCol.scrollIntoView({
                    behavior: 'smooth'
                });
                startTimer(10 * 60);
            }
        }

        // Fungsi Sembunyikan Kalender (Tombol Batalkan)
        function hideCalendar() {
            if (countdown) clearInterval(countdown);

            document.getElementById('calendar-column').classList.add('d-none');
            document.getElementById('btn-booking-wrapper').style.display = 'block';

            // ENABLE KEMBALI KOLOM KIRI
            const leftColumn = document.getElementById('left-column');
            if (leftColumn) leftColumn.classList.remove('disabled-section');

            // Scroll kembali ke atas (opsional, agar user sadar kolom kiri aktif lagi)
            leftColumn.scrollIntoView({
                behavior: 'smooth'
            });

            // Reset pilihan tanggal & jam di input hidden
            document.getElementById('input_tgl_booking').value = "";
            document.getElementById('input_jam_mulai').value = "";
        }

        // Fungsi Timer Mundur
        function startTimer(duration) {
            let timer = duration,
                minutes, seconds;
            const display = document.querySelector('#booking-timer');
            const submitBtn = document.querySelector('.btn-action-submit'); // Pastikan class tombol benar

            isTimeUp = false; // Reset status setiap timer mulai
            if (countdown) clearInterval(countdown);

            countdown = setInterval(function() {
                minutes = parseInt(timer / 60, 10);
                seconds = parseInt(timer % 60, 10);

                minutes = minutes < 10 ? "0" + minutes : minutes;
                seconds = seconds < 10 ? "0" + seconds : seconds;

                if (display) display.textContent = minutes + ":" + seconds;

                if (--timer < 0) {
                    clearInterval(countdown);
                    isTimeUp = true; // Kunci status

                    // Matikan tombol submit secara visual
                    if (submitBtn) {
                        submitBtn.disabled = true;
                        submitBtn.classList.add('disabled');
                    }

                    // Tampilkan alert
                    Swal.fire({
                        title: 'Waktu Habis!',
                        text: 'Sesi booking Anda telah berakhir. Silakan pilih ulang jadwal.',
                        icon: 'warning',
                        confirmButtonText: 'Oke',
                        confirmButtonColor: '#3B8181',
                        allowOutsideClick: false
                    }).then(() => {
                        location.reload(); // Refresh halaman
                    });
                }
            }, 1000);
        }

        // Helper: Hitung Jam Selesai
        function calculateEndTime(startTime, duration) {
            let [hours, minutes] = startTime.split(':').map(Number);
            minutes += duration;

            if (minutes >= 60) {
                hours += Math.floor(minutes / 60);
                minutes = minutes % 60;
            }
            return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
        }


        // ============================================================
        // 2. LOGIC AJAX & INTERAKSI KALENDER
        // ============================================================

        // A. Fungsi Ganti Bulan (Tanpa Refresh)
        function changeMonth(month, year) {
            const wrapper = document.getElementById('calendar-grid-wrapper');

            // Efek loading
            wrapper.style.opacity = '0.5';

            // Panggil Controller via AJAX
            fetch(`/load-calendar?month=${month}&year=${year}`)
                .then(response => response.json()) // Pastikan controller return JSON { html: "..." }
                .then(data => {
                    // Ganti isi wrapper dengan HTML baru dari server
                    wrapper.innerHTML = data.html;
                    wrapper.style.opacity = '1';

                    // PENTING: Pasang ulang listener karena elemen HTML-nya baru
                    reinitDateListeners();
                })
                .catch(err => {
                    console.error("Gagal load kalender:", err);
                    wrapper.style.opacity = '1';
                });
        }

        // B. Pasang Event Listener ke Tanggal (Re-usable)
        function reinitDateListeners() {
            const dateItems = document.querySelectorAll('.date-item:not(.disabled):not(.empty)');

            dateItems.forEach(item => {
                item.addEventListener('click', function() {
                    // UI: Reset warna selected lama
                    document.querySelectorAll('.date-item').forEach(el => el.classList.remove('selected'));
                    this.classList.add('selected');

                    // Logic: Simpan tanggal ke input hidden
                    const tgl = this.dataset.date;
                    const tglInput = document.getElementById('input_tgl_booking');
                    if (tglInput) tglInput.value = tgl;

                    // Logic: Cek Slot ke Database
                    checkSlotAvailability(tgl);
                });
            });
        }

        // C. Cek Slot Penuh via AJAX
        function checkSlotAvailability(tgl) {
            // 1. Reset semua tombol jam jadi aktif dulu
            const allTimeBtns = document.querySelectorAll('.btn-time');
            allTimeBtns.forEach(btn => {
                btn.classList.remove('disabled', 'full', 'active');
                btn.disabled = false;
                btn.title = "";
            });

            // 2. Kosongkan input jam (karena user ganti tanggal)
            document.getElementById('input_jam_mulai').value = "";
            const sekarang = new Date();
            const jamSekarang = sekarang.getHours();
            const menitSekarang = sekarang.getMinutes();
            const totalMenitSekarang = (jamSekarang * 60) + menitSekarang;

            // Format tanggal hari ini (YYYY-MM-DD) untuk perbandingan
            const hariIni = sekarang.toISOString().split('T')[0];

            // 3. LOGIKA JAM LEWAT: Jika tanggal yang diklik adalah hari ini
            if (tgl === hariIni) {
                allTimeBtns.forEach(btn => {
                    const [jamBtn, menitBtn] = btn.dataset.time.split(':').map(Number);
                    const totalMenitBtn = (jamBtn * 60) + menitBtn;

                    // Jika waktu pada tombol sudah lewat dari waktu sekarang
                    if (totalMenitBtn <= totalMenitSekarang) {
                        btn.classList.add('disabled', 'full');
                        btn.disabled = true;
                        btn.title = "Waktu sudah terlewat";
                    }
                });
            }
            // 3. Panggil Server
            fetch(`/cek-slot-foto?tanggal=${tgl}`)
                .then(res => res.json())
                .then(data => {
                    data.forEach(booking => {
                        // Ambil jam depan saja (09:00:00 -> 09:00)
                        const jamPenuh = booking.jam_mulai.substring(0, 5);

                        // Cari tombol yg punya data-time sama
                        const btnPenuh = document.querySelector(`.btn-time[data-time="${jamPenuh}"]`);

                        if (btnPenuh) {
                            btnPenuh.classList.add('disabled', 'full'); // Tambah class styling
                            btnPenuh.disabled = true; // Matikan klik
                            btnPenuh.title = "Slot Sudah Terisi";
                        }
                    });
                })
                .catch(err => console.error("Gagal cek slot:", err));
        }


        // ============================================================
        // 3. INISIALISASI SAAT HALAMAN DIMUAT (DOM READY)
        // ============================================================
        document.addEventListener('DOMContentLoaded', function() {

            // 1. Jalankan Listener Tanggal (Untuk kalender mulai)
            reinitDateListeners();

            // 2. Pasang Listener Tombol Jam (Cukup sekali)
            const timeButtons = document.querySelectorAll('.btn-time');
            timeButtons.forEach(btn => {
                btn.addEventListener('click', function(e) {
                    e.preventDefault();

                    // Cek jika tombol disabled (safety)
                    if (this.disabled || this.classList.contains('disabled')) return;

                    // UI: Reset active
                    timeButtons.forEach(el => el.classList.remove('active'));
                    this.classList.add('active');

                    // Logic: Simpan Jam
                    const startTime = this.dataset.time;
                    document.getElementById('input_jam_mulai').value = startTime;

                    // Logic: Hitung Jam Selesai
                    const endTime = calculateEndTime(startTime, durasiPaket);
                    document.getElementById('input_jam_selesai').value = endTime;
                });
            });

            // 3. Validasi Submit Form
            // 3. Validasi Submit Form
            const bookingForm = document.getElementById('form-booking');
            if (bookingForm) {
                bookingForm.addEventListener('submit', function(e) {
                    const tgl = document.getElementById('input_tgl_booking').value;
                    const jam = document.getElementById('input_jam_mulai').value;

                    // CEK APAKAH WAKTU HABIS
                    if (isTimeUp) {
                        e.preventDefault();
                        Swal.fire('Maaf!', 'Waktu booking sudah habis, halaman akan dimuat ulang.', 'error')
                            .then(() => location.reload());
                        return;
                    }

                    if (!tgl || !jam) {
                        e.preventDefault();
                        Swal.fire({
                            title: 'Jadwal Belum Dipilih!',
                            text: 'Silakan pilih tanggal dan jam pemotretan terlebih dahulu.',
                            icon: 'warning',
                            confirmButtonColor: '#20c997'
                        });
                    }
                });
            }
        });
    </script>
@endsection
