/**
 * Form Handling JavaScript
 */

// =============================================
// DYNAMIC DROPDOWNS
// =============================================
function initDynamicDropdowns() {
    // State to LGA
    const stateSelect = document.getElementById('state_id');
    const lgaSelect = document.getElementById('lga_id');
    
    if (stateSelect && lgaSelect) {
        stateSelect.addEventListener('change', function() {
            const stateId = this.value;
            
            if (!stateId) {
                lgaSelect.innerHTML = '<option value="">Select State First</option>';
                return;
            }
            
            ajaxRequest(`/api/get_lgas?state_id=${stateId}`)
                .then(lgas => {
                    lgaSelect.innerHTML = '<option value="">Select LGA</option>';
                    lgas.forEach(lga => {
                        const option = document.createElement('option');
                        option.value = lga.id;
                        option.textContent = lga.lga_name;
                        lgaSelect.appendChild(option);
                    });
                });
        });
    }
    
    // Zone to Command
    const zoneSelect = document.getElementById('zone_id');
    const commandSelect = document.getElementById('command_id');
    
    if (zoneSelect && commandSelect) {
        zoneSelect.addEventListener('change', function() {
            const zoneId = this.value;
            
            if (!zoneId) {
                commandSelect.innerHTML = '<option value="">Select Zone First</option>';
                return;
            }
            
            ajaxRequest(`/api/get_commands?zone_id=${zoneId}`)
                .then(commands => {
                    commandSelect.innerHTML = '<option value="">Select Command</option>';
                    commands.forEach(cmd => {
                        const option = document.createElement('option');
                        option.value = cmd.id;
                        option.textContent = cmd.command_name;
                        commandSelect.appendChild(option);
                    });
                });
        });
    }
}

// =============================================
// FILE UPLOAD AREA
// =============================================
function initFileUpload() {
    const uploadAreas = document.querySelectorAll('.file-upload-area');
    
    uploadAreas.forEach(area => {
        const input = area.querySelector('input[type="file"]');
        const fileList = area.nextElementSibling;
        
        if (!input || !fileList) return;
        
        // Click to upload
        area.addEventListener('click', () => input.click());
        
        // File selection
        input.addEventListener('change', function() {
            handleFiles(this.files, fileList);
        });
        
        // Drag and drop
        area.addEventListener('dragover', (e) => {
            e.preventDefault();
            area.classList.add('dragover');
        });
        
        area.addEventListener('dragleave', () => {
            area.classList.remove('dragover');
        });
        
        area.addEventListener('drop', (e) => {
            e.preventDefault();
            area.classList.remove('dragover');
            
            if (e.dataTransfer.files.length) {
                input.files = e.dataTransfer.files;
                handleFiles(e.dataTransfer.files, fileList);
            }
        });
    });
}

function handleFiles(files, container) {
    container.innerHTML = '';
    
    Array.from(files).forEach(file => {
        const fileItem = document.createElement('div');
        fileItem.className = 'file-item';
        
        const fileSize = (file.size / 1024).toFixed(2);
        const icon = getFileIcon(file.type);
        
        fileItem.innerHTML = `
            <div class="file-info">
                <i class="fas ${icon}"></i>
                <span class="file-name">${file.name}</span>
                <span class="file-size">(${fileSize} KB)</span>
            </div>
            <button type="button" class="btn btn-sm btn-danger" onclick="this.parentElement.remove()">
                <i class="fas fa-times"></i>
            </button>
        `;
        
        container.appendChild(fileItem);
    });
}

function getFileIcon(mimeType) {
    if (mimeType.includes('pdf')) return 'fa-file-pdf';
    if (mimeType.includes('image')) return 'fa-file-image';
    if (mimeType.includes('word')) return 'fa-file-word';
    if (mimeType.includes('excel')) return 'fa-file-excel';
    return 'fa-file';
}

// =============================================
// CALCULATE AMMUNITION BALANCE
// =============================================
function calculateAmmunitionBalance(row) {
    const received = row.querySelector('.quantity-received');
    const issued = row.querySelector('.quantity-issued');
    const balance = row.querySelector('.balance');
    
    if (received && issued && balance) {
        const receivedVal = parseInt(received.value) || 0;
        const issuedVal = parseInt(issued.value) || 0;
        const balanceVal = Math.max(0, receivedVal - issuedVal);
        
        balance.value = balanceVal;
    }
}

// =============================================
// CALCULATE AUDIT VARIANCE
// =============================================
function calculateAuditVariance(row) {
    const system = row.querySelector('.system-units');
    const physical = row.querySelector('.physical-units');
    const variance = row.querySelector('.variance-display');
    const varianceValue = row.querySelector('.variance-value');
    
    if (system && physical && variance && varianceValue) {
        const systemVal = parseInt(system.value) || 0;
        const physicalVal = parseInt(physical.value) || 0;
        const varianceVal = physicalVal - systemVal;
        
        variance.value = varianceVal;
        varianceValue.value = varianceVal;
        
        // Color code
        if (varianceVal < 0) {
            variance.style.color = '#e74c3c';
            variance.style.fontWeight = 'bold';
        } else if (varianceVal > 0) {
            variance.style.color = '#27ae60';
            variance.style.fontWeight = 'bold';
        } else {
            variance.style.color = '#2c3e50';
            variance.style.fontWeight = 'normal';
        }
    }
}

// =============================================
// DYNAMIC ROW ADDITION
// =============================================
function addTableRow(tableId, templateRow) {
    const table = document.getElementById(tableId);
    if (!table) return;
    
    const tbody = table.querySelector('tbody');
    const newRow = templateRow.cloneNode(true);
    const rowCount = tbody.children.length + 1;
    
    // Update S/N
    newRow.querySelector('.sn').textContent = rowCount;
    
    // Clear inputs
    newRow.querySelectorAll('input:not([type="hidden"]), select').forEach(field => {
        field.value = '';
    });
    
    tbody.appendChild(newRow);
    updateRemoveButtons(tableId);
}

function removeTableRow(button, tableId) {
    const row = button.closest('tr');
    const tbody = row.parentNode;
    
    if (tbody.children.length > 1) {
        row.remove();
        updateRowNumbers(tbody);
        updateRemoveButtons(tableId);
    } else {
        showNotification('warning', 'At least one row is required');
    }
}

function updateRowNumbers(tbody) {
    Array.from(tbody.children).forEach((row, index) => {
        const snCell = row.querySelector('.sn');
        if (snCell) snCell.textContent = index + 1;
    });
}

function updateRemoveButtons(tableId) {
    const table = document.getElementById(tableId);
    if (!table) return;
    
    const rows = table.querySelectorAll('tbody tr');
    const removeButtons = table.querySelectorAll('.remove-row');
    
    if (rows.length <= 1) {
        removeButtons.forEach(btn => btn.disabled = true);
    } else {
        removeButtons.forEach(btn => btn.disabled = false);
    }
}

// =============================================
// FORM RESET
// =============================================
function resetForm(formId) {
    const form = document.getElementById(formId);
    if (!form) return;
    
    if (confirm('Are you sure you want to reset the form? All unsaved data will be lost.')) {
        form.reset();
        
        // Clear file previews
        const fileLists = form.querySelectorAll('.file-list');
        fileLists.forEach(list => list.innerHTML = '');
        
        // Reset dynamic selects
        const lgaSelect = document.getElementById('lga_id');
        if (lgaSelect) lgaSelect.innerHTML = '<option value="">Select State First</option>';
        
        const commandSelect = document.getElementById('command_id');
        if (commandSelect) commandSelect.innerHTML = '<option value="">Select Zone First</option>';
        
        showNotification('info', 'Form has been reset');
    }
}