@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('storage/' . $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++)
                                            <button type="button" class="btn-time"
                                                data-time="{{ sprintf('%02d:00', $hour) }}">
                                                {{ sprintf('%02d:00', $hour) }} WIB
                                            </button>
                                            <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">Lanjutkan Pemesanan</button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </section>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        let countdown;
        let isTimeUp = false;
        const durasiPaket = parseInt(document.getElementById('data-paket')?.dataset.durasi || 15);

        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;
            input.value = newValue;
        }

        function showCalendar() {
            document.getElementById('btn-booking-wrapper').style.display = 'none';
            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);
            }
        }

        function hideCalendar() {
            if (countdown) clearInterval(countdown);
            document.getElementById('calendar-column').classList.add('d-none');
            document.getElementById('btn-booking-wrapper').style.display = 'block';
            const leftColumn = document.getElementById('left-column');
            if (leftColumn) leftColumn.classList.remove('disabled-section');
            leftColumn.scrollIntoView({
                behavior: 'smooth'
            });
            document.getElementById('input_tgl_booking').value = "";
            document.getElementById('input_jam_mulai').value = "";
        }

        function startTimer(duration) {
            let timer = duration,
                minutes, seconds;
            const display = document.querySelector('#booking-timer');
            const submitBtn = document.querySelector('.btn-action-submit');
            isTimeUp = false;
            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;
                    if (submitBtn) {
                        submitBtn.disabled = true;
                        submitBtn.classList.add('disabled');
                    }
                    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();
                    });
                }
            }, 1000);
        }

        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')}`;
        }

        function changeMonth(month, year) {
            const wrapper = document.getElementById('calendar-grid-wrapper');
            wrapper.style.opacity = '0.5';
            fetch(`/load-calendar?month=${month}&year=${year}`)
                .then(response => response.json())
                .then(data => {
                    wrapper.innerHTML = data.html;
                    wrapper.style.opacity = '1';
                    reinitDateListeners();
                })
                .catch(err => {
                    console.error("Gagal load kalender:", err);
                    wrapper.style.opacity = '1';
                });
        }

        function reinitDateListeners() {
            const dateItems = document.querySelectorAll('.date-item:not(.disabled):not(.empty)');
            dateItems.forEach(item => {
                item.addEventListener('click', function() {
                    document.querySelectorAll('.date-item').forEach(el => el.classList.remove('selected'));
                    this.classList.add('selected');
                    const tgl = this.dataset.date;
                    const tglInput = document.getElementById('input_tgl_booking');
                    if (tglInput) tglInput.value = tgl;
                    checkSlotAvailability(tgl);
                });
            });
        }

        function checkSlotAvailability(tgl) {
            const allTimeBtns = document.querySelectorAll('.btn-time');
            allTimeBtns.forEach(btn => {
                btn.classList.remove('disabled', 'full', 'active');
                btn.disabled = false;
                btn.title = "";
            });
            document.getElementById('input_jam_mulai').value = "";
            const sekarang = new Date();
            const jamSekarang = sekarang.getHours();
            const menitSekarang = sekarang.getMinutes();
            const totalMenitSekarang = (jamSekarang * 60) + menitSekarang;
            const hariIni = sekarang.toISOString().split('T')[0];
            if (tgl === hariIni) {
                allTimeBtns.forEach(btn => {
                    const [jamBtn, menitBtn] = btn.dataset.time.split(':').map(Number);
                    const totalMenitBtn = (jamBtn * 60) + menitBtn;
                    if (totalMenitBtn <= totalMenitSekarang) {
                        btn.classList.add('disabled', 'full');
                        btn.disabled = true;
                        btn.title = "Waktu sudah terlewat";
                    }
                });
            }
            fetch(`/cek-slot-foto?tanggal=${tgl}`)
                .then(res => res.json())
                .then(data => {
                    data.forEach(booking => {
                        const jamPenuh = booking.jam_mulai.substring(0, 5);
                        const btnPenuh = document.querySelector(`.btn-time[data-time="${jamPenuh}"]`);
                        if (btnPenuh) {
                            btnPenuh.classList.add('disabled', 'full');
                            btnPenuh.disabled = true;
                            btnPenuh.title = "Slot Sudah Terisi";
                        }
                    });
                })
                .catch(err => console.error("Gagal cek slot:", err));
        }
        document.addEventListener('DOMContentLoaded', function() {
            reinitDateListeners();
            const timeButtons = document.querySelectorAll('.btn-time');
            timeButtons.forEach(btn => {
                btn.addEventListener('click', function(e) {
                    e.preventDefault();
                    if (this.disabled || this.classList.contains('disabled')) return;
                    timeButtons.forEach(el => el.classList.remove('active'));
                    this.classList.add('active');
                    const startTime = this.dataset.time;
                    document.getElementById('input_jam_mulai').value = startTime;
                    const endTime = calculateEndTime(startTime, durasiPaket);
                    document.getElementById('input_jam_selesai').value = endTime;
                });
            });
            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;
                    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
