<!-- resources/views/register.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registrasi - Lapor Mas Wapres</title>
    <link href="{{ asset('css/lib/bootstrap.min.css') }}" rel="stylesheet">
    <link href="{{ asset('css/lib/bootstrap-icons.css') }}" rel="stylesheet">
    <link href="{{ asset('css/styles.css') }}" rel="stylesheet">
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
    <script src="{{ asset('js/lib/jquery-3.6.0.min.js') }}"></script>
    <script src="{{ asset('js/lib/moment.min.js') }}"></script>
    <script src="{{ asset('js/lib/moment-timezone.min.js') }}"></script>
    <script src="{{ asset('js/datepicker.js') }}" defer></script>
    <script src="{{ asset('js/quota-manager.js') }}" defer></script>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <span class="navbar-brand">Lapor Mas Wapres</span>
        </div>
    </nav>

    <div class="container text-center my-4">
        <img src="{{ asset('images/logo.png') }}" alt="Logo" height="120" class="img-fluid">
    </div>

    <div class="container py-3">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h4 class="mb-0 text-center">Formulir Registrasi Lapor Mas Wapres</h4>
                    </div>
                    <div class="card-body">
                        @if ($errors->any())
                            <div class="alert alert-danger">
                                <ul class="mb-0">
                                    @foreach ($errors->all() as $error)
                                        <li>{{ $error }}</li>
                                    @endforeach
                                </ul>
                            </div>
                        @endif

                        <form action="{{ route('register.store') }}" method="POST" enctype="multipart/form-data">
                            @csrf
                            <div class="mb-3">
                                <label class="form-label">Nama Lengkap <span class="text-danger">*</span></label>
                                <input type="text" name="name" class="form-control" value="{{ old('name') }}" required>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Jenis Kelamin <span class="text-danger">*</span></label>
                                <div class="d-flex gap-3">
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="gender" id="genderL" value="L" {{ old('gender') == 'L' ? 'checked' : '' }} required>
                                        <label class="form-check-label" for="genderL">
                                            Laki-laki
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="gender" id="genderP" value="P" {{ old('gender') == 'P' ? 'checked' : '' }}>
                                        <label class="form-check-label" for="genderP">
                                            Perempuan
                                        </label>
                                    </div>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Nomor KTP <span class="text-danger">*</span></label>
                                <input type="text" name="nik" class="form-control" pattern="[0-9]{16}" maxlength="16" value="{{ old('nik') }}" required>
                                <small class="text-muted">Harus 16 digit angka</small>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Nomor KK <span class="text-danger">*</span></label>
                                <input type="text" name="no_kk" class="form-control" pattern="[0-9]{16}" maxlength="16" value="{{ old('no_kk') }}" required>
                                <small class="text-muted">Harus 16 digit angka</small>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">No. Telepon <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <input type="text" name="phone" class="form-control" 
                                           pattern="^62\d+" 
                                           value="{{ old('phone') }}" 
                                           placeholder="628123456789"
                                           required>
                                </div>
                                <small class="text-muted">Format: 62 diikuti nomor telepon (contoh: 628123456789)</small>
                            </div>                            <div class="mb-3">
                                <label class="form-label">Email</label>
                                <input type="email" 
                                       name="email" 
                                       class="form-control @error('email') is-invalid @enderror" 
                                       value="{{ old('email') }}">
                                <small class="text-muted">Masukkan alamat email (opsional)</small>
                                @error('email')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Alamat <span class="text-danger">*</span></label>
                                <textarea 
                                    name="address" 
                                    class="form-control @error('address') is-invalid @enderror" 
                                    rows="3" 
                                    required>{{ old('address') }}</textarea>
                                @error('address')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Topik Aduan <span class="text-danger">*</span></label>
                                <input type="text" 
                                       name="topic" 
                                       class="form-control @error('topic') is-invalid @enderror" 
                                       value="{{ old('topic') }}" 
                                       required>
                                @error('topic')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="mb-3">
                                <div class="form-check">
                                    <input type="checkbox" 
                                           class="form-check-input" 
                                           id="priority" 
                                           name="priority" 
                                           value="1" 
                                           {{ old('priority') ? 'checked' : '' }}>
                                    <label class="form-check-label" for="priority">
                                        Saya adalah Kelompok Rentan/Difabel yang membutuhkan Pendamping
                                    </label>
                                </div>
                            </div>

                            <div class="mb-3" id="pendampingField" style="display: none;">
                                <label class="form-label">Nama Pendamping</label>
                                <input type="text" 
                                       name="pendamping" 
                                       class="form-control @error('pendamping') is-invalid @enderror" 
                                       value="{{ old('pendamping') }}">
                                @error('pendamping')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>                            <div class="mb-3">
                                <label class="form-label">Masukan Foto KTP anda <span class="text-danger">*</span></label>
                                <input type="file" name="ktp_image" class="form-control @error('ktp_image') is-invalid @enderror" accept="image/jpeg,image/jpg,image/png" required>
                                <small class="text-muted">Format yang didukung: JPG, JPEG, PNG. Maksimal 5MB.</small>
                                @error('ktp_image')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="row">
                                <!-- Date Picker Column -->
                                <div class="col-md-6">
                                    <div class="mb-4">
                                        <label class="form-label fw-bold">Tanggal Kunjungan <span class="text-danger">*</span></label>
                                        <input type="hidden" name="visit_date" id="selected_date" value="{{ old('visit_date') }}" required>
                                        
                                        <div class="date-picker-container">
                                            <div class="date-picker-header">
                                                <button type="button" class="month-nav" id="prevMonth">
                                                    <i class="bi bi-chevron-left"></i>
                                                </button>
                                                <div id="currentMonth"></div>
                                                <button type="button" class="month-nav" id="nextMonth">
                                                    <i class="bi bi-chevron-right"></i>
                                                </button>
                                            </div>
                                            
                                            <div class="calendar-grid">
                                                <div class="weekday-header">Min</div>
                                                <div class="weekday-header">Sen</div>
                                                <div class="weekday-header">Sel</div>
                                                <div class="weekday-header">Rab</div>
                                                <div class="weekday-header">Kam</div>
                                                <div class="weekday-header">Jum</div>
                                                <div class="weekday-header">Sab</div>
                                            </div>
                                            
                                            <div class="calendar-grid" id="calendarDays"></div>
                                            
                                            <div class="date-info">
                                                <div class="selected-date" id="selectedDateText">
                                                    Pilih tanggal kunjungan
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Time Slots Column -->
                                <div class="col-md-6">
                                    <div class="mb-4">
                                        <label class="form-label fw-bold">Jam Kunjungan <span class="text-danger">*</span></label>                                <div class="d-flex flex-column gap-3" id="timeSlotContainer">
                                            <!-- Time slots will be loaded here dynamically -->
                                            <div class="text-center p-3">
                                                <div class="spinner-border text-primary" role="status">
                                                    <span class="visually-hidden">Loading...</span>
                                                </div>
                                                <p class="mt-2">Memuat slot waktu tersedia...</p>
                                            </div>
                                        
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="mb-4">
                                <div class="g-recaptcha" data-sitekey="{{ env('RECAPTCHA_SITE_KEY') }}"></div>
                            </div>                            <div class="d-grid">
                                <button type="submit" id="submitButton" class="btn btn-primary" disabled>Daftar Sekarang</button>
                                <small id="quotaWarning" class="text-danger text-center mt-2" style="display: none;">
                                    Anda belum memilih tanggal dan waktu kunjungan yang tersedia
                                </small>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Pendamping field handling
        const priorityCheck = document.getElementById('priority');
        const pendampingField = document.getElementById('pendampingField');
        // Submit button state will be managed by datepicker.js

        function togglePendamping() {
            pendampingField.style.display = priorityCheck.checked ? 'block' : 'none';
        }

        priorityCheck.addEventListener('change', togglePendamping);
        togglePendamping(); // Initial state        // Time slot handling with dynamic slots
        let selectedDate = '';
        let timeSlots = {};
        
        // Update form state definition was moved to quota-manager.js
        
        // Store old visit time value for form validation errors
        const old_visit_time = "{{ old('visit_time') }}";

        // Function to load time slots
        function loadTimeSlots() {
            const timeSlotContainer = document.getElementById('timeSlotContainer');
            
            fetch('/get-time-slots')
                .then(response => response.json())
                .then(data => {
                    // Clear existing content
                    timeSlotContainer.innerHTML = '';
                    timeSlots = {};
                    
                    if (data.slots && data.slots.length > 0) {
                        // Create time slot elements
                        data.slots.forEach(slot => {
                            const timeValue = slot.time;
                            const timeId = `time_${timeValue.replace(':', '_')}`;
                            
                            const slotDiv = document.createElement('div');
                            slotDiv.className = 'w-100';
                            
                            const checked = old_visit_time === timeValue ? 'checked' : '';
                              slotDiv.innerHTML = `
                                <input type="radio" class="btn-check" name="visit_time" id="${timeId}" value="${timeValue}" ${checked} required>
                                <label class="btn btn-outline-primary w-100 time-slot-card" for="${timeId}">
                                    <div class="d-flex align-items-center">
                                        <i class="bi bi-clock fs-4 me-3"></i>
                                        <div>
                                            <h5 class="mb-0">${timeValue}</h5>
                                            <small class="text-muted">${slot.label}</small>
                                        </div>
                                        <div class="quota-info ms-auto text-end">
                                            <span class="quota-badge badge bg-primary">
                                                <span class="quota-available">?</span>/<span class="quota-total">?</span>
                                            </span>
                                            <br>
                                            <small class="quota-text text-muted">Memeriksa kuota...</small>
                                        </div>
                                    </div>
                                </label>
                            `;
                              timeSlotContainer.appendChild(slotDiv);
                            
                            // Store reference to the slot data with ID for easier access
                            timeSlots[timeValue] = {
                                id: timeId,
                                time: timeValue,
                                label: slot.label
                            };
                            // Event listener for individual radio buttons removed - handled by delegation in datepicker.js
                        }); // End forEach

                        // Signal datepicker.js that time slots are rendered
                        document.dispatchEvent(new CustomEvent('timeSlotsRendered'));
                        console.log("Blade: Time slots rendered and event dispatched.");

                    } else { // Handle case where no slots are returned
                        timeSlotContainer.innerHTML = '<div class="alert alert-warning">Tidak ada slot waktu yang tersedia. Silakan hubungi admin.</div>';
                         // Still signal datepicker, even if no slots
                         document.dispatchEvent(new CustomEvent('timeSlotsRendered'));
                         console.log("Blade: No time slots available, event dispatched.");
                    }
                }) // End .then()
                .catch(error => { // Handle fetch error
                    console.error('Error loading time slots:', error);
                    timeSlotContainer.innerHTML = '<div class="alert alert-danger">Gagal memuat slot waktu. Silakan muat ulang halaman.</div>';
                     // Still signal datepicker on error
                     document.dispatchEvent(new CustomEvent('timeSlotsRendered'));
                     console.log("Blade: Error loading time slots, event dispatched.");
                 }); // End .catch()
         } // End loadTimeSlots function

         // Initial loading of time slots
         loadTimeSlots();

        // Date selection and quota checks are now fully handled by datepicker.js
        // Removed listeners for hiddenDateField and 'dateSelected' event

         // Add CSS
        const style = document.createElement('style');
        style.textContent = `
            .disabled-time-slot {
                opacity: 0.6;
                cursor: not-allowed !important;
                background-color: #f8f9fa !important;
                border-color: #dee2e6 !important;
                color: #6c757d !important;
            }
            
            .quota-badge {
                min-width: 44px;
                display: inline-block;
            }
            
            .quota-text {
                font-size: 0.85rem;
                font-weight: 500;
                display: inline-block;
            }
            
            .time-slot-card {
                transition: all 0.3s ease;
            }
            
            .time-slot-card:hover:not(.disabled-time-slot) {
                transform: translateY(-2px);
                box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            }
        `;
        document.head.appendChild(style);
    });
    </script>
</body>
</html>
