(function () {
    'use strict';

    document.addEventListener('DOMContentLoaded', function () {

        var config = window.crudConfig;

        if (!config) return;

        var tableBody = document.querySelector(config.tableBody);
        var form = document.querySelector(config.form);
        var modalElement = document.querySelector(config.modal);
        var modalTitle = document.querySelector(config.modalTitle);
        var addButton = document.querySelector(config.addButton);
        var alertBox = document.querySelector(config.alertBox);

        var modal = bootstrap.Modal.getOrCreateInstance(modalElement);

        var rows = [];

        function escapeHtml(value) {
            return String(value === null || value === undefined ? '' : value)
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#039;');
        }

        function showAlert(message, type) {

            if (!alertBox) return;

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

            setTimeout(function () {
                alertBox.classList.add('d-none');
            }, 3000);
        }

        function statusClass(status) {

            var map = {
                Pending: 'text-bg-warning',
                Approved: 'text-bg-success',
                Released: 'text-bg-primary',
                Rejected: 'text-bg-danger',
                Active: 'text-bg-success',
                Inactive: 'text-bg-secondary'
            };

            return map[status] || 'text-bg-secondary';
        }

        function toTitleCase(value) {

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

        function formatDateTime(value) {

            if (!value) return '-';

            var date = new Date(String(value).replace(' ', 'T'));

            if (isNaN(date.getTime())) return value;

            var month = String(date.getMonth() + 1).padStart(2, '0');
            var day = String(date.getDate()).padStart(2, '0');
            var year = date.getFullYear();

            var hours = date.getHours();
            var minutes = String(date.getMinutes()).padStart(2, '0');

            var period = hours >= 12 ? 'PM' : 'AM';

            hours = hours % 12;
            hours = hours ? hours : 12;

            return month + '/' + day + '/' + year + ' - ' + hours + ':' + minutes + ' ' + period;
        }

        function formatCell(row, column) {

            var value = row[column.key];

            if (column.badge) {
                return '<span class="badge status-badge ' + statusClass(value) + '">' +
                    escapeHtml(value || '-') +
                    '</span>';
            }

            if (column.format === 'datetime') {
                return value ? escapeHtml(formatDateTime(value)) : '-';
            }

            if (column.format === 'title') {
                return value ? escapeHtml(toTitleCase(value)) : '-';
            }

            return escapeHtml(value || '-');
        }

        function openQrWindow(row) {

            var ref = row.transaction_ref || '';

            if (!ref) {
                alert('No transaction reference found.');
                return;
            }

            var existingModal = document.getElementById('qrPreviewModal');

            if (existingModal) {
                existingModal.remove();
            }

            document.body.insertAdjacentHTML('beforeend', `
                <div class="modal fade" id="qrPreviewModal" tabindex="-1">
                    <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">

                            <div class="modal-header">
                                <h5 class="modal-title">Gatepass QR Code</h5>

                                <button type="button"
                                        class="btn-close"
                                        data-bs-dismiss="modal"></button>
                            </div>

                            <div class="modal-body text-center">

                                <div class="border rounded p-3 d-flex align-items-center justify-content-between gap-3">

                                    <div class="text-start">

                                        <div style="font-size:10px;color:#6b7280;text-transform:uppercase;">
                                            Reference Number
                                        </div>

                                        <div style="font-size:20px;font-weight:800;color:#111827;">
                                            ${escapeHtml(ref)}
                                        </div>

                                        <div style="font-size:12px;color:#374151;">
                                            Gatepass | Status:
                                            ${escapeHtml(row.status || 'Pending')}
                                        </div>

                                    </div>

                                    <canvas id="qrCanvas"></canvas>

                                </div>

                            </div>

                            <div class="modal-footer">

                                <button class="btn btn-primary"
                                        type="button"
                                        onclick="window.print()">
                                    Print QR
                                </button>

                            </div>

                        </div>
                    </div>
                </div>
            `);

            var qrModalElement = document.getElementById('qrPreviewModal');

            var qrModal = bootstrap.Modal.getOrCreateInstance(qrModalElement);

            qrModal.show();

            setTimeout(function () {

                var canvas = document.getElementById('qrCanvas');

                const qrData =
`Gatepass Reference: ${ref}
Pass Type: ${document.querySelector('.topbar h1')?.textContent || 'Gatepass'}
Date Request: ${row.pass_date || row.visit_date || row.date_request || 'N/A'}
Status: ${row.status || 'Pending'}`;

                QRCode.toCanvas(
                    canvas,
                    qrData,
                    {
                        width: 260,
                        margin: 2,
                        color: {
                            dark: '#000000',
                            light: '#ffffff'
                        }
                    },
                    function (error) {

                        if (error) {
                            console.error(error);
                        }

                    }
                );

            }, 300);
        }

        function renderRows() {

            if (!rows.length) {

                tableBody.innerHTML =
                    '<tr>' +
                    '<td colspan="' + (config.columns.length + 1) + '" class="empty-row">' +
                    escapeHtml(config.emptyMessage || 'No records found.') +
                    '</td>' +
                    '</tr>';

                return;
            }

            tableBody.innerHTML = rows.map(function (row) {

                var cells = config.columns.map(function (column) {
                    return '<td>' + formatCell(row, column) + '</td>';
                }).join('');

                return `
                    <tr>

                        ${cells}

                        <td>
                            <div class="table-actions">

                                <button class="btn btn-outline-success icon-btn"
                                        type="button"
                                        data-action="qr"
                                        data-id="${row.id}"
                                        title="QR Code">

                                    <i class="bi bi-qr-code"></i>

                                </button>

                                <button class="btn btn-outline-primary icon-btn"
                                        type="button"
                                        data-action="edit"
                                        data-id="${row.id}"
                                        title="Edit">

                                    <i class="bi bi-pencil"></i>

                                </button>

                                <button class="btn btn-outline-danger icon-btn"
                                        type="button"
                                        data-action="delete"
                                        data-id="${row.id}"
                                        title="Delete">

                                    <i class="bi bi-trash"></i>

                                </button>

                            </div>
                        </td>

                    </tr>
                `;
            }).join('');
        }

        async function loadRows() {

            try {

                var response = await fetch(config.api, {
                    headers: {
                        Accept: 'application/json'
                    }
                });

                var result = await response.json();

                if (!result.success) {

                    showAlert(result.message || 'Unable to load records.', 'danger');

                    return;
                }

                rows = result.data || [];

                renderRows();

            } catch (error) {

                console.error(error);

                showAlert('Unable to connect to the server.', 'danger');
            }
        }

        function resetForm() {

            form.reset();

            if (form.elements.id) {
                form.elements.id.value = '';
            }

            if (modalTitle) {
                modalTitle.textContent =
                    modalTitle.textContent.replace('Edit', 'Add');
            }
        }

        function fillForm(row) {

            config.fields.forEach(function (field) {

                var input = form.elements[field];

                if (!input) return;

                input.value = row[field] || '';
            });

            if (modalTitle) {
                modalTitle.textContent =
                    modalTitle.textContent.replace('Add', 'Edit');
            }

            modal.show();
        }

        addButton.addEventListener('click', function () {

            resetForm();

            modal.show();
        });

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

            event.preventDefault();

            var formData = new FormData(form);

            formData.append('action', 'save');

            try {

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

                var result = await response.json();

                if (!result.success) {

                    showAlert(result.message || 'Unable to save.', 'danger');

                    return;
                }

                modal.hide();

                showAlert(result.message || 'Saved successfully.', 'success');

                await loadRows();

            } catch (error) {

                console.error(error);

                showAlert('Unable to connect to server.', 'danger');
            }
        });

        tableBody.addEventListener('click', async function (event) {

            var button = event.target.closest('button[data-action]');

            if (!button) return;

            var id = button.getAttribute('data-id');

            var row = rows.find(function (item) {
                return String(item.id) === String(id);
            });

            if (button.dataset.action === 'qr' && row) {

                openQrWindow(row);

                return;
            }

            if (button.dataset.action === 'edit' && row) {

                fillForm(row);

                return;
            }

            if (button.dataset.action === 'delete') {

                if (!confirm('Delete this record?')) return;

                var formData = new FormData();

                formData.append('action', 'delete');
                formData.append('id', id);

                try {

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

                    var result = await response.json();

                    if (!result.success) {

                        showAlert(result.message || 'Unable to delete.', 'danger');

                        return;
                    }

                    showAlert(result.message || 'Deleted successfully.', 'success');

                    await loadRows();

                } catch (error) {

                    console.error(error);

                    showAlert('Unable to connect to server.', 'danger');
                }
            }
        });

        loadRows();

    });

})();