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

    const modal = new bootstrap.Modal(document.getElementById('unitModal'));
    const form = document.getElementById('unitForm');

    document.getElementById('addUnitButton').addEventListener('click', function () {
        form.reset();
        document.getElementById('unit_id').value = '';
        document.getElementById('unitModalTitle').textContent = 'Add Unit';
        modal.show();
    });

    document.querySelectorAll('.edit-unit').forEach(function (button) {
        button.addEventListener('click', function () {
            document.getElementById('unit_id').value = this.dataset.id;
            document.getElementById('unit_name').value = this.dataset.name;
            document.getElementById('description').value = this.dataset.description;
            document.getElementById('display_order').value = this.dataset.order;
            document.getElementById('is_required').value = this.dataset.required;
            document.getElementById('status').value = this.dataset.status;
            document.getElementById('unitModalTitle').textContent = 'Edit Unit';
            modal.show();
        });
    });

    form.addEventListener('submit', async function (event) {
        event.preventDefault();
        const response = await fetch('ajax/save_unit.php', { method: 'POST', body: new FormData(form) });
        const result = await response.json();
        if (result.success) { await Swal.fire('Saved', result.message, 'success'); window.location.reload(); }
        else { Swal.fire('Error', result.message, 'error'); }
    });

    document.querySelectorAll('.delete-unit').forEach(function (button) {
        button.addEventListener('click', async function () {
            const confirm = await Swal.fire({ title: 'Delete ' + this.dataset.name + '?', text: 'This action cannot be undone.', icon: 'warning', showCancelButton: true, confirmButtonText: 'Delete' });
            if (!confirm.isConfirmed) return;
            const data = new FormData();
            data.append('id', this.dataset.id);
            data.append('csrf_token', document.querySelector('[name="csrf_token"]').value);
            const response = await fetch('ajax/delete_unit.php', { method: 'POST', body: data });
            const result = await response.json();
            if (result.success) { await Swal.fire('Deleted', result.message, 'success'); window.location.reload(); }
            else { Swal.fire('Error', result.message, 'error'); }
        });
    });
});
