<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kalender - <?php echo e(strtoupper(str_replace('_', ' ', $room))); ?></title>
    <link rel="icon" type="image/x-icon" href="<?php echo e(asset('images/logo.png')); ?>">

    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        // Konfigurasi Tailwind untuk palet warna kustom
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary': '#22c55e', // Hijau-500
                        'secondary': '#4f46e5', // Indigo-600
                    }
                }
            }
        }
    </script>

    <!-- Google Fonts - Inter -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">

    <!-- FullCalendar CSS -->
    <link href="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.8/index.global.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.8/index.global.min.js"></script>

    <style>
        body {
            font-family: 'Inter', sans-serif;
            transition: background 0.5s ease;
        }

        /* Override FullCalendar default styles */
        .fc-toolbar-title {
            font-weight: 700 !important;
            color: #1f2937 !important; 
        }

        .fc-button {
            border-radius: 9999px !important;
            padding: 8px 16px !important;
            font-size: 0.875rem !important;
            font-weight: 600 !important;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);
            transition: all 0.2s ease-in-out;
        }

        .fc-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1);
        }

        .fc-prev-button, .fc-next-button {
            background-color: #22c55e !important; /* Primary color */
            border: none !important;
            color: white !important;
        }

        .fc-today-button {
            background-color: #4f46e5 !important; /* Secondary color */
            border: none !important;
            color: white !important;
        }
        
        .fc-event {
            border: none !important;
            border-radius: 8px !important;
            padding: 4px 8px !important;
            font-size: 0.875rem !important;
            font-weight: 500 !important;
        }

        .fc-h-event .fc-event-main {
            color: white !important;
        }

        /* Responsiveness for FullCalendar toolbar */
        @media (max-width: 640px) {
            .fc-toolbar.fc-header-toolbar {
                flex-direction: column;
                align-items: center;
                gap: 1rem;
            }
            .fc-toolbar-chunk:nth-child(1) {
                order: 2; /* Pindahkan tombol prev/next/today ke bawah */
                width: 100%;
                display: flex;
                justify-content: center;
                margin-bottom: 0.5rem;
            }
            .fc-toolbar-chunk:nth-child(2) {
                order: 1; /* Pindahkan title ke atas */
                width: 100%;
                text-align: center;
                margin-bottom: 0.5rem;
            }
            .fc-toolbar-chunk:nth-child(3) {
                order: 3; /* Pindahkan tombol view ke bawah */
                width: 100%;
                display: flex;
                justify-content: center;
                flex-wrap: wrap; /* Tambahkan ini agar tombol bisa wrap ke baris baru */
            }
        }

        /* Modal styling */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background-color: #fefefe;
            margin: auto;
            padding: 24px;
            border-radius: 16px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            max-width: 400px;
            animation: fadeIn 0.3s ease-out;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #e5e7eb;
            padding-bottom: 1rem;
            margin-bottom: 1rem;
        }

        .modal-title {
            font-size: 1.25rem;
            font-weight: 600;
        }

        .modal-close {
            color: #aaa;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .modal-close:hover {
            color: #333;
        }
        
        .modal-body p {
            margin-bottom: 0.5rem;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen p-4 sm:p-6 lg:p-12 flex items-center justify-center">
    <div class="w-full h-full bg-white rounded-[2rem] shadow-2xl p-6 sm:p-8 lg:p-12 transform transition-transform duration-300 relative border border-gray-100">
        <!-- Header -->
        <div class="flex flex-col sm:flex-row sm:justify-between sm:items-center mb-8">
            <!-- Logo dan Beranda -->
            <div class="mb-4 sm:mb-0 flex justify-center sm:justify-start w-full sm:w-auto">
                <a href="<?php echo e(url('/calendar')); ?>" class="flex flex-col items-center group">
                    <!-- Ganti path gambar di bawah dengan path gambar .JPG Anda di dalam folder public -->
                    <img src="<?php echo e(asset('images/logo.png')); ?>" alt="Logo Perusahaan" class="w-16 h-16 rounded-full mb-1">
                    <!-- Teks Beranda -->
                    <span class="mt-1 text-sm font-bold text-gray-900 group-hover:text-gray-900 transition-colors duration-300">Beranda</span>
                </a>
            </div>
            <!-- Judul Halaman -->
            <div class="flex items-center justify-center sm:justify-end text-center w-full sm:w-auto">
                <h1 class="text-3xl sm:text-4xl font-extrabold text-gray-900 tracking-tight">
                    JADWAL <span class="text-primary"><?php echo e(strtoupper(str_replace('_', ' ', $room))); ?></span>
                </h1>
            </div>
        </div>
        
        <!-- Kalender -->
        <div id="calendar" class="mt-4 mb-8"></div>

        <!-- Formulir Jadwal Baru -->
        <form id="new-booking-form" class="p-6 bg-gray-50 rounded-2xl border border-gray-200 shadow-inner">
            <h3 class="text-xl font-semibold mb-4 text-gray-800 text-center">Buat Jadwal Meeting Baru</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
            <label for="start_date" class="block text-sm font-medium text-gray-700 mb-1">Tanggal Mulai</label>
            <input type="date" id="start_date" name="start_date" required
                class="w-full rounded-lg border-gray-300 shadow-sm focus:border-primary focus:ring-primary">
        </div>

        <div>
            <label for="end_date" class="block text-sm font-medium text-gray-700 mb-1">Tanggal Selesai (Opsional, apabila booking lebih dari 1 hari)</label>
            <input type="date" id="end_date" name="end_date" 
                class="w-full rounded-lg border-gray-300 shadow-sm focus:border-primary focus:ring-primary">
</div>

                <div>
                    <label for="pic" class="block text-sm font-medium text-gray-700 mb-1">Penanggung Jawab (PIC)</label>
                    <input type="text" id="pic" name="pic" required placeholder="Nama PIC"
                           class="w-full rounded-lg border-gray-300 shadow-sm focus:border-primary focus:ring-primary">
                </div>


                <div>
                    <label for="department" class="block text-sm font-medium text-gray-700 mb-1">Departemen</label>
                    <select id="department" name="department" required
                            class="w-full rounded-lg border-gray-300 shadow-sm focus:border-primary focus:ring-primary">
                        <option value="">-- Pilih Departemen --</option>
                        <option value="IT">IT</option>
                        <option value="Finance & Accounting">Finance & Accounting</option>
                        <option value="Casting">Casting</option>
                        <option value="Casting Engineering">Casting Engineering</option>
                        <option value="Finishing">Finishing</option>
                        <option value="HSE">HSE</option>
                        <option value="Machining">Machining</option>
                        <option value="Machining Engineering">Machining Engineering</option>
                        <option value="Maintenance">Maintenance</option>
                        <option value="PGA">PGA</option>
                        <option value="PPSC">PPSC</option>
                        <option value="Purchasing">Purchasing</option>
                        <option value="Quality">Quality</option>
                        <option value="Sales">Sales</option>
                        <option value="New Model">New Model</option>
                    </select>
                </div>

                <div>
                    <label for="start_time" class="block text-sm font-medium text-gray-700 mb-1">Jam Mulai</label>
                    <input type="time" id="start_time" name="start_time" required
                           class="w-full rounded-lg border-gray-300 shadow-sm focus:border-primary focus:ring-primary">
                </div>
                <div>
                    <label for="end_time" class="block text-sm font-medium text-gray-700 mb-1">Jam Selesai</label>
                    <input type="time" id="end_time" name="end_time" required
                           class="w-full rounded-lg border-gray-300 shadow-sm focus:border-primary focus:ring-primary">
                </div>
                

            

                <div class="md:col-span-2">
                    <label for="keterangan" class="block text-sm font-medium text-gray-700 mb-1">Keterangan</label>
                    <textarea id="keterangan" name="keterangan" rows="3" required
                    class="w-full rounded-lg border-gray-300 shadow-sm focus:border-primary focus:ring-primary"></textarea>
                </div>
            </div>
            <div class="mt-8 text-center">
                <button type="submit"
                        class="px-8 py-3 bg-primary text-white font-semibold rounded-full shadow-lg hover:bg-indigo-700 transition duration-300 ease-in-out transform hover:scale-105">
                    Buat Jadwal
                </button>
            </div>
        </form>
    </div>

    <!-- Modal for Event Details -->
    <div id="event-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">Detail Jadwal</h2>
                <span class="modal-close" id="close-modal">&times;</span>
            </div>
            <div class="modal-body">
                <p><strong>Tanggal:</strong> <span id="modal-date"></span></p>
                <p><strong>Jam Mulai:</strong> <span id="modal-start"></span></p>
                <p><strong>Jam Selesai:</strong> <span id="modal-end"></span></p>
                <p><strong>Penanggung Jawab:</strong> <span id="modal-pic"></span></p>
                <p><strong>Departemen:</strong> <span id="modal-department"></span></p>
                <p><strong>Keterangan:</strong> <span id="modal-keterangan"></span></p>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Set minimal tanggal input(hari ini saja dan kedepannya )
            const today = new Date();
            const year = today.getFullYear();
            const month = String(today.getMonth() + 1).padStart(2, '0');
            const day = String(today.getDate()).padStart(2, '0');
            const todayString = `${year}-${month}-${day}`;

            // ambil dua input tanggal
            const startDateInput = document.getElementById('start_date');
            const endDateInput = document.getElementById('end_date');

            // atur minimal tanggal hari ini
            if (startDateInput) startDateInput.min = todayString;
            if (endDateInput) endDateInput.min = todayString;

            // Validasi tambahan untuk mencegah backdate di iOS (Safari) — HANYA untuk TANGGAL MULAI
            startDateInput.addEventListener('change', function() {
                if (this.value < todayString) {
                    alert('Input ulang Tanggal , Tanggal tidak boleh mundur ke belakang!');
                    this.value = '';
                }
            });

            // VALIDASI untuk end_date (opsional) → hanya cek kalau end_date < start_date
            endDateInput.addEventListener('change', function() {
                const start = startDateInput.value;
                const end = this.value;

                // jangan validasi kalau end_date kosong
                if (!end) return;

                // cek hanya jika end_date < start_date
                if (start && end < start) {
                    alert('Tanggal selesai tidak boleh sebelum tanggal mulai!');
                    this.value = '';
                }
            });



            // ambil elemen penting
            var calendarEl = document.getElementById('calendar');
            var formEl = document.getElementById('new-booking-form');
            var modalEl = document.getElementById('event-modal');
            var closeModalBtn = document.getElementById('close-modal');

            // Atur tampilan kalender
            var initialView = 'timeGridDay';
            var headerToolbar = {
                left: 'prev,next today',
                center: 'title',
                right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
            };

            //Inisialisasi FullCalendar
            var calendar = new FullCalendar.Calendar(calendarEl, {
                initialView: initialView, 
                initialDate: new Date(), 
                headerToolbar: headerToolbar,
                events: '<?php echo e(url("/")); ?>/api/<?php echo e($room); ?>/bookings',
                height: "auto",
                expandRows: true,
                //Warna event Per Department
                eventDidMount: function(info) {
                    const department = info.event.extendedProps.department || 'Default';

                    const colors = {
                    'IT': '#eb00b8ff',        
                    'Finance & Accounting': '#22c55e',   
                    'Casting': '#c52222ff',
                    'Casting Engineering': '#ff9900ff',        
                    'Finishing': '#08edf5ff',   
                    'HSE': '#8b03faff',
                    'Machining': '#4f46e5',        
                    'Machining Engineering': '#2400f3ff',   
                    'Maintenance': '#ff3c00ff',
                    'PGA': '#22547cff',        
                    'PPSC': '#2b073aff',   
                    'Purchasing': '#b68686ff',
                    'Quality': '#0c2709ff',   
                    'Sales': '#9485ccff',
                    'New Model': '#48e908ff',
                    'Default': '#6b7280'    
        };
                    // Set warna sesuai departemen
                    info.el.style.backgroundColor = colors[department] || colors['Default'];
                    info.el.style.color = 'white';
                },
        //Tampilan event (isi)
            eventContent: function(info) {
                let picName = info.event.extendedProps.pic || info.event.title;
                return { html: '<div class="p-1 font-semibold">' + (picName) + '</div>' };
            },

            //Event Click → Buka Modal
            eventClick: function(info) {
                const event = info.event;
                const startDate = new Date(event.start);
                const endDate = new Date(event.end);
                
                document.getElementById('modal-date').innerText = startDate.toLocaleDateString();
                document.getElementById('modal-start').innerText = startDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                document.getElementById('modal-end').innerText = endDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                document.getElementById('modal-pic').innerText = event.title;
                document.getElementById('modal-department').innerText = event.extendedProps.department || '-';
                document.getElementById('modal-keterangan').innerText = event.extendedProps.keterangan || 'Tidak ada keterangan';

                modalEl.style.display = 'flex';
            }
        });

            calendar.render();

            // Sembunyikan modal saat tombol silang diklik
            closeModalBtn.addEventListener('click', function() {
                modalEl.style.display = 'none';
            });

            // Sembunyikan modal saat mengklik di luar area modal
            window.addEventListener('click', function(event) {
                if (event.target == modalEl) {
                    modalEl.style.display = 'none';
                }
            });

            // Handle pengiriman formulir(Submit Form Booking Baru)
    formEl.addEventListener('submit', async function(event) {
    event.preventDefault();

    // --- VALIDASI TAMBAHAN ---

    const startDate = document.getElementById('start_date').value;
    const endDate = document.getElementById('end_date').value;
    const keterangan = document.getElementById('keterangan').value.trim();

    // 🔒 Cek apakah keterangan diisi
    if (!keterangan) {
        alert('Keterangan wajib diisi!');
        return;
    }

    // 🔒 Cek validitas tanggal selesai (boleh kosong, tapi tidak boleh sebelum start)
    if (endDate && endDate < startDate) {
        alert('Tanggal selesai tidak boleh sebelum tanggal mulai!');
        return;
    }

    // Ambil semua data dari form (dengan fallback end_date = start_date)
    const formData = new FormData(formEl);
    const data = {
        start_date: formData.get('start_date'),
        end_date: endDate || startDate, // kalau kosong, disamakan dengan tanggal mulai
        start_time: formData.get('start_time'),
        end_time: formData.get('end_time'),
        pic: formData.get('pic'),
        department: formData.get('department'),
        keterangan: keterangan
    };

    try {
        // Kirim ke endpoint Laravel (POST)

        // Kirim ke endpoint Laravel (POST)
        const response = await fetch('<?php echo e(url("/")); ?>/api/<?php echo e($room); ?>/bookings', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
            },
            body: JSON.stringify(data),
        });

        // ✅ Jika sukses
        if (response.ok) {
            // Refresh kalender supaya semua tanggal tampil
            calendar.refetchEvents();

            // Ganti pesan biar sesuai fitur baru (multi-day)
            alert('Jadwal meeting berhasil!');
            formEl.reset();
        } 
        // ❌ Jika gagal (error dari backend)
        else {
            const errorData = await response.json();
            alert(`Gagal membuat jadwal: ${errorData.message || response.statusText}`);
        }

    } catch (error) {
        // 🚨 Error koneksi atau fetch
        alert('Terjadi kesalahan saat mengirim data ke server.');
        console.error('Error:', error);
    }
});

        });
    </script>
</body>
</html>
<?php /**PATH D:\Hafiiz\Project\Code Magang\Finall\Apps Asama Layer Security\booking-ruangan-tamu\resources\views/calendar/room.blade.php ENDPATH**/ ?>