// filepath: e:\Koding\lapor-mas-wapress_V1.1\public\js\quota-manager.js
/**
 * Quota Manager - Handles quota checking and time slot management
 * Works together with datepicker.js to provide a seamless quota checking experience
 */

document.addEventListener('DOMContentLoaded', function() {
    // Get DOM elements
    const submitButton = document.getElementById('submitButton');
    const quotaWarning = document.getElementById('quotaWarning');
    const dateInput = document.getElementById('selected_date');

    // Global state
    let timeSlots = {};
    let formState = {
        hasDate: false,
        hasAvailableTimeSlot: false
    };

    // Function to update submit button state
    function updateSubmitButtonState() {
        const isFormValid = formState.hasDate && formState.hasAvailableTimeSlot;
        submitButton.disabled = !isFormValid;
        quotaWarning.style.display = isFormValid ? 'none' : 'block';
    }

    // Function to load time slots
    function loadTimeSlots() {
        const timeSlotContainer = document.getElementById('timeSlotContainer');
        
        // Reset the time slots container
        if (timeSlotContainer) {
            timeSlotContainer.innerHTML = `
                <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>
            `;
        } else {
            return;
        }
        
        // Get the old visit time value for form validation errors
        const old_visit_time = document.querySelector('input[name="visit_time"]:checked')?.value || '';
        
        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
                        };
                        
                        // Add event handler for time slot radio buttons
                        const radioInput = document.getElementById(timeId);
                        if (radioInput) {
                            radioInput.addEventListener('change', function() {
                                if (this.checked) {
                                    // Update form validation state
                                    formState.hasAvailableTimeSlot = !this.disabled;
                                    updateSubmitButtonState();
                                }
                            });
                        }
                    });
                    
                    // Make date info available to datepicker.js
                    window.timeSlotInfo = {
                        timeSlots: timeSlots,
                        updateFormState: function(date) {
                            formState.hasDate = !!date;
                            updateSubmitButtonState();
                        }
                    };
                    
                    // Trigger a custom event for datepicker.js to know slots are loaded
                    const event = new CustomEvent('timeSlotsLoaded', { detail: timeSlots });
                    document.dispatchEvent(event);
                    
                    // If date is already selected, update quota info
                    if (dateInput && dateInput.value) {
                        formState.hasDate = true;
                        updateSubmitButtonState();
                    }
                } else {
                    timeSlotContainer.innerHTML = '<div class="alert alert-warning">Tidak ada slot waktu yang tersedia. Silakan hubungi admin.</div>';
                }
            })
            .catch(error => {
                timeSlotContainer.innerHTML = '<div class="alert alert-danger">Gagal memuat slot waktu. Silakan muat ulang halaman.</div>';
            });
    }

    // Register a custom event listener for date selection (from datepicker.js)
    document.addEventListener('dateSelected', function(e) {
        formState.hasDate = true;
        updateSubmitButtonState();
    });

    // Add CSS for disabled time slots and quota display
    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);

    // Initialize time slots
    loadTimeSlots();
});
