(function () {
    'use strict';

    document.addEventListener('DOMContentLoaded', function () {
        var typeButtons = Array.from(document.querySelectorAll('[data-pass-type]'));
        var form = document.getElementById('publicPassForm');
        var fieldsContainer = document.getElementById('publicFields');
        var passTypeInput = document.getElementById('pass_type');
        var title = document.getElementById('requestFormTitle');
        var subtitle = document.getElementById('requestFormSubtitle');
        var alertBox = document.getElementById('publicAlert');
        var clearButton = document.getElementById('clearRequestBtn');
        var selectedType = 'personnel';

        var configs = {
            personnel: {
                title: 'Personnel Pass',
                subtitle: 'Complete the personnel pass request form.',
                fields: [
                    { name: 'section_name', label: 'Section', type: 'text', required: true },
                    { name: 'id_number', label: 'ID No.', type: 'text', required: true },
                    { name: 'name', label: 'Name', type: 'text', required: true },
                    { name: 'signature', label: 'Signature', type: 'text', required: false },
                    { name: 'pass_date', label: 'Date', type: 'date', required: true },
                    { name: 'pass_time', label: 'Time', type: 'time', required: true },
                    { name: 'reason', label: 'Reason', type: 'textarea', required: true }
                ]
            },

            visitor: {
                title: "Visitor's Pass Slip",
                subtitle: 'Complete the visitor pass request form.',
                fields: [
                    { name: 'visitor_name', label: 'Visitor Name', type: 'text', required: true },
                    { name: 'visit_date', label: 'Date', type: 'date', required: true },
                    { name: 'time_in', label: 'Time In', type: 'time', required: true },
                    { name: 'time_out', label: 'Time Out', type: 'time', required: true },
                    { name: 'person_to_visit', label: 'Person to Visit', type: 'text', required: true },
                    { name: 'section_name', label: 'Section', type: 'text', required: true },
                    { name: 'purpose', label: 'Purpose of Visit', type: 'select', required: true,
                        options: ['Collection', 'Back-pay', 'Clearance', 'Meeting', 'Delivery', 'Pick-up items', 'Others']
                    },
                    { name: 'other_purpose', label: 'Others, Please Specify', type: 'text', required: false }
                ]
            },

            item: {
                title: 'Item Pass',
                subtitle: 'Complete the item pass request form.',
                fields: [
                    { name: 'description', label: 'Description', type: 'textarea', required: true },
                    { name: 'quantity', label: 'Quantity', type: 'number', required: true },
                    { name: 'measurement', label: 'Measurement', type: 'text', required: true },
                    { name: 'remarks', label: 'Remarks', type: 'textarea', required: false },
                    { name: 'checked_out', label: 'Checked By Out', type: 'text', required: false },
                    { name: 'checked_in', label: 'Checked By In', type: 'text', required: false }
                ]
            },

            food: {
                title: 'Food Pass',
                subtitle: 'Complete the food pass request form.',
                fields: [
                    { name: 'food_items', label: 'Food Items to Bring In', type: 'textarea', required: true },
                    { name: 'quantity_measurement', label: 'Qty. and Measurement', type: 'text', required: true },
                    { name: 'container_type', label: 'Type of Container', type: 'text', required: true },
                    { name: 'reason', label: 'Reason', type: 'textarea', required: true }
                ]
            },

            mealbreak: {
                title: 'Meal Break Pass',
                subtitle: 'Complete the meal break pass request form.',
                fields: [
                    { name: 'name', label: 'Name', type: 'text', required: true },
                    { name: 'line_section', label: 'Line / Section', type: 'text', required: true },
                    { name: 'time_out', label: 'Time Out', type: 'time', required: true },
                    { name: 'time_in', label: 'Time In', type: 'time', required: true },
                    { name: 'purpose', label: 'Purpose', type: 'textarea', required: true }
                ]
            }
        };

        function todayValue() {
            var now = new Date();
            return now.getFullYear() + '-' +
                String(now.getMonth() + 1).padStart(2, '0') + '-' +
                String(now.getDate()).padStart(2, '0');
        }

        function showAlert(message, type) {
            alertBox.className = 'alert alert-' + (type || 'success');
            alertBox.textContent = message;
            alertBox.classList.remove('d-none');
        }

        function hideAlert() {
            alertBox.classList.add('d-none');
            alertBox.textContent = '';
        }

        function toTitleCase(value) {
            return String(value || '')
                .toLowerCase()
                .replace(/\s+/g, ' ')
                .trim()
                .replace(/\b\w/g, function (letter) {
                    return letter.toUpperCase();
                });
        }

        function fieldMarkup(field) {
            var required = field.required ? ' required' : '';
            var value = field.type === 'date' ? ' value="' + todayValue() + '"' : '';

            if (field.type === 'textarea') {
                return '<div class="mb-3">' +
                    '<label class="form-label" for="' + field.name + '">' + field.label + '</label>' +
                    '<textarea class="form-control" id="' + field.name + '" name="' + field.name + '" rows="3"' + required + '></textarea>' +
                    '</div>';
            }

            if (field.type === 'select') {
                var options = '<option value="">Select</option>';
                field.options.forEach(function (option) {
                    options += '<option value="' + option + '">' + option + '</option>';
                });

                return '<div class="mb-3">' +
                    '<label class="form-label" for="' + field.name + '">' + field.label + '</label>' +
                    '<select class="form-control" id="' + field.name + '" name="' + field.name + '"' + required + '>' +
                    options +
                    '</select>' +
                    '</div>';
            }

            return '<div class="mb-3">' +
                '<label class="form-label" for="' + field.name + '">' + field.label + '</label>' +
                '<input class="form-control" type="' + field.type + '" id="' + field.name + '" name="' + field.name + '"' + value + required + '>' +
                '</div>';
        }

        function renderForm(type) {
            var config = configs[type];

            selectedType = type;
            passTypeInput.value = type;
            title.textContent = config.title;
            subtitle.textContent = config.subtitle;
            fieldsContainer.innerHTML = config.fields.map(fieldMarkup).join('');
            hideAlert();

            typeButtons.forEach(function (button) {
                var active = button.dataset.passType === type;
                button.classList.toggle('active', active);
                button.setAttribute('aria-pressed', active ? 'true' : 'false');
            });
        }

        typeButtons.forEach(function (button) {
            button.addEventListener('click', function () {
                renderForm(button.dataset.passType);
            });
        });

        clearButton.addEventListener('click', function () {
            renderForm(selectedType);
        });

        form.addEventListener('submit', async function (event) {
            event.preventDefault();
            hideAlert();

            form.querySelectorAll('input[type="text"], textarea').forEach(function (input) {
                input.value = toTitleCase(input.value);
            });

            var formData = new FormData(form);
            formData.append('action', 'create');

            try {
                var response = await fetch('api/public_passes.php', {
                    method: 'POST',
                    body: formData,
                    headers: { Accept: 'application/json' }
                });

                var result = await response.json();

                if (!response.ok || !result.success) {
                    showAlert(result.message || 'Unable to submit request.', 'danger');
                    return;
                }

                renderForm(selectedType);
                showAlert((result.message || 'Pass request submitted.') + ' Status: Pending.', 'success');
            } catch (error) {
                showAlert('Unable to connect to the server.', 'danger');
            }
        });

        renderForm(selectedType);
    });
})();