/**
 * NIS Asset Management System
 * Weapon Issue Module JavaScript
 */

// Initialize on document ready
document.addEventListener('DOMContentLoaded', function() {
    initializeWeaponIssue();
});

function initializeWeaponIssue() {
    // Set default dates
    setDefaultDates();
    
    // Initialize event listeners
    initializeEventListeners();
    
    // Initialize search functionality
    initializeSearch();
}

function setDefaultDates() {
    const today = new Date().toISOString().split('T')[0];
    
    const issueDateFields = ['issue_date', 'ammo_issue_date'];
    issueDateFields.forEach(id => {
        const field = document.getElementById(id);
        if (field && !field.value) {
            field.value = today;
        }
    });
    
    // Set default return date to 30 days from now
    const returnDate = document.getElementById('expected_return_date');
    if (returnDate && !returnDate.value) {
        const date = new Date();
        date.setDate(date.getDate() + 30);
        returnDate.value = date.toISOString().split('T')[0];
    }
}

function initializeEventListeners() {
    // Purpose other field toggles
    const purposeSelect = document.getElementById('purpose');
    if (purposeSelect) {
        purposeSelect.addEventListener('change', function() {
            toggleOtherField(this, 'purposeOtherGroup');
        });
    }
    
    const ammoPurposeSelect = document.getElementById('ammo_purpose');
    if (ammoPurposeSelect) {
        ammoPurposeSelect.addEventListener('change', function() {
            toggleOtherField(this, 'ammoPurposeOtherGroup');
        });
    }
    
    // Weapon select change
    const weaponSelect = document.getElementById('weapon_id');
    if (weaponSelect) {
        weaponSelect.addEventListener('change', function() {
            updateWeaponDetails(this);
        });
    }
    
    // Ammo select change
    const ammoSelect = document.getElementById('ammo_id');
    if (ammoSelect) {
        ammoSelect.addEventListener('change', function() {
            updateAmmoDetails(this);
            calculateTotalRounds();
        });
    }
    
    // Units issued change
    const unitsInput = document.getElementById('units_issued');
    if (unitsInput) {
        unitsInput.addEventListener('input', calculateTotalRounds);
    }
    
    // Requisition selects
    const reqSelect = document.getElementById('requisition_id');
    if (reqSelect) {
        reqSelect.addEventListener('change', function() {
            loadRequisitionDetails(this.value, 'weapon');
        });
    }
    
    const ammoReqSelect = document.getElementById('ammo_requisition_id');
    if (ammoReqSelect) {
        ammoReqSelect.addEventListener('change', function() {
            loadRequisitionDetails(this.value, 'ammo');
        });
    }
}

function toggleOtherField(select, targetId) {
    const otherGroup = document.getElementById(targetId);
    if (!otherGroup) return;
    
    if (select.value === 'Other') {
        otherGroup.style.display = 'block';
    } else {
        otherGroup.style.display = 'none';
    }
}

function updateWeaponDetails(select) {
    const option = select.options[select.selectedIndex];
    
    const typeDisplay = document.getElementById('weaponTypeDisplay');
    const modelDisplay = document.getElementById('weaponModelDisplay');
    const serialDisplay = document.getElementById('weaponSerialDisplay');
    const calibreDisplay = document.getElementById('weaponCalibreDisplay');
    
    if (typeDisplay) typeDisplay.textContent = option.getAttribute('data-type') || '-';
    if (modelDisplay) modelDisplay.textContent = option.getAttribute('data-model') || '-';
    if (serialDisplay) serialDisplay.textContent = option.getAttribute('data-serial') || '-';
    if (calibreDisplay) calibreDisplay.textContent = option.getAttribute('data-calibre') || '-';
}

function updateAmmoDetails(select) {
    const option = select.options[select.selectedIndex];
    
    const typeDisplay = document.getElementById('ammoTypeDisplay');
    const calibreDisplay = document.getElementById('ammoCalibreDisplay');
    const balanceDisplay = document.getElementById('ammoBalanceDisplay');
    const unitsInput = document.getElementById('units_issued');
    
    const balance = parseInt(option.getAttribute('data-balance')) || 0;
    
    if (typeDisplay) typeDisplay.textContent = option.getAttribute('data-type') || '-';
    if (calibreDisplay) calibreDisplay.textContent = option.getAttribute('data-calibre') || '-';
    if (balanceDisplay) balanceDisplay.textContent = balance;
    
    if (unitsInput) {
        unitsInput.max = balance;
        if (parseInt(unitsInput.value) > balance) {
            unitsInput.value = balance;
        }
    }
}

function calculateTotalRounds() {
    const units = document.getElementById('units_issued')?.value;
    const totalField = document.getElementById('total_rounds');
    
    if (units && totalField) {
        const roundsPerUnit = 30; // Standard
        totalField.value = parseInt(units) * roundsPerUnit;
    }
}

function loadRequisitionDetails(requisitionId, type) {
    if (!requisitionId) return;
    
    const select = document.getElementById(type === 'weapon' ? 'requisition_id' : 'ammo_requisition_id');
    const option = select.options[select.selectedIndex];
    
    if (type === 'weapon') {
        const officerField = document.getElementById('officer_name');
        const rankField = document.getElementById('officer_rank');
        const unitField = document.getElementById('unit');
        const purposeSelect = document.getElementById('purpose');
        
        if (officerField) officerField.value = option.getAttribute('data-officer') || '';
        if (rankField) rankField.value = option.getAttribute('data-rank') || '';
        if (unitField) unitField.value = option.getAttribute('data-unit') || '';
        
        const purpose = option.getAttribute('data-purpose') || '';
        if (purposeSelect && purpose) {
            let matched = false;
            for (let i = 0; i < purposeSelect.options.length; i++) {
                if (purposeSelect.options[i].value === purpose) {
                    purposeSelect.selectedIndex = i;
                    matched = true;
                    break;
                }
            }
            
            if (!matched) {
                purposeSelect.value = 'Other';
                document.getElementById('purpose_other').value = purpose;
                document.getElementById('purposeOtherGroup').style.display = 'block';
            }
        }
    } else {
        const issuedTo = document.getElementById('issued_to');
        if (issuedTo) issuedTo.value = option.getAttribute('data-officer') || '';
    }
}

function initializeSearch() {
    const searchInputs = [
        { id: 'searchReturns', tables: ['issuedWeaponsTable', 'issuedAmmoTable'] }
    ];
    
    searchInputs.forEach(item => {
        const input = document.getElementById(item.id);
        if (!input) return;
        
        input.addEventListener('input', function(e) {
            const searchTerm = e.target.value.toLowerCase();
            
            item.tables.forEach(tableId => {
                const table = document.getElementById(tableId);
                if (!table) return;
                
                const rows = table.querySelectorAll('tbody tr');
                rows.forEach(row => {
                    const text = row.textContent.toLowerCase();
                    row.style.display = text.includes(searchTerm) ? '' : 'none';
                });
            });
        });
    });
}

// Form validation
function validateWeaponForm() {
    const weaponId = document.getElementById('weapon_id')?.value;
    const officerName = document.getElementById('officer_name')?.value;
    
    if (!weaponId) {
        alert('Please select a weapon');
        return false;
    }
    
    if (!officerName) {
        alert('Please enter officer name');
        return false;
    }
    
    return true;
}

function validateAmmoForm() {
    const ammoId = document.getElementById('ammo_id')?.value;
    const units = parseInt(document.getElementById('units_issued')?.value) || 0;
    const balance = parseInt(document.getElementById('ammo_id')?.options[document.getElementById('ammo_id')?.selectedIndex]?.getAttribute('data-balance') || 0);
    
    if (!ammoId) {
        alert('Please select ammunition');
        return false;
    }
    
    if (units <= 0) {
        alert('Please enter valid units to issue');
        return false;
    }
    
    if (units > balance) {
        alert('Cannot issue more than available balance');
        return false;
    }
    
    return true;
}

// Reset forms
function resetWeaponForm() {
    if (!confirm('Reset weapon issue form?')) return;
    
    const form = document.getElementById('weaponIssueForm');
    if (form) {
        form.reset();
        
        // Reset weapon details display
        document.getElementById('weaponTypeDisplay').textContent = '-';
        document.getElementById('weaponModelDisplay').textContent = '-';
        document.getElementById('weaponSerialDisplay').textContent = '-';
        document.getElementById('weaponCalibreDisplay').textContent = '-';
        
        // Hide other field
        document.getElementById('purposeOtherGroup').style.display = 'none';
    }
}

function resetAmmoForm() {
    if (!confirm('Reset ammunition issue form?')) return;
    
    const form = document.getElementById('ammoIssueForm');
    if (form) {
        form.reset();
        
        // Reset ammo details display
        document.getElementById('ammoTypeDisplay').textContent = '-';
        document.getElementById('ammoCalibreDisplay').textContent = '-';
        document.getElementById('ammoBalanceDisplay').textContent = '-';
        
        // Hide other field
        document.getElementById('ammoPurposeOtherGroup').style.display = 'none';
        
        // Reset total rounds
        document.getElementById('total_rounds').value = '30';
    }
}

// Tab switching
function showTab(tabName) {
    document.querySelectorAll('.tab-content').forEach(tab => {
        tab.classList.remove('active');
    });
    
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    
    const tab = document.getElementById('tab-' + tabName);
    if (tab) tab.classList.add('active');
    
    const btn = event?.target.closest('.tab-btn');
    if (btn) btn.classList.add('active');
}

// Issue type switching
function showIssueType(type) {
    document.querySelectorAll('.issue-form').forEach(form => {
        form.classList.remove('active');
    });
    
    document.querySelectorAll('.type-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    
    const form = document.getElementById(type + '-issue-form');
    if (form) form.classList.add('active');
    
    const btn = event?.target.closest('.type-btn');
    if (btn) btn.classList.add('active');
}

// Filter functions for history page
function applyFilters() {
    const status = document.getElementById('filterStatus')?.value.toLowerCase();
    const dateFrom = document.getElementById('filterDateFrom')?.value;
    const dateTo = document.getElementById('filterDateTo')?.value;
    const searchTerm = document.getElementById('searchHistory')?.value.toLowerCase();
    
    // Filter weapons table
    const weaponRows = document.querySelectorAll('#weaponHistoryTable tbody tr');
    weaponRows.forEach(row => {
        let show = true;
        
        if (status) {
            const rowStatus = row.dataset.status?.toLowerCase() || '';
            show = show && rowStatus === status;
        }
        
        if (dateFrom) {
            const rowDate = row.dataset.date;
            show = show && rowDate >= dateFrom;
        }
        
        if (dateTo) {
            const rowDate = row.dataset.date;
            show = show && rowDate <= dateTo;
        }
        
        if (searchTerm) {
            const text = row.textContent.toLowerCase();
            show = show && text.includes(searchTerm);
        }
        
        row.style.display = show ? '' : 'none';
    });
    
    // Filter ammo table
    const ammoRows = document.querySelectorAll('#ammoHistoryTable tbody tr');
    ammoRows.forEach(row => {
        let show = true;
        
        if (status) {
            const rowStatus = row.dataset.status?.toLowerCase() || '';
            show = show && rowStatus === status;
        }
        
        if (dateFrom) {
            const rowDate = row.dataset.date;
            show = show && rowDate >= dateFrom;
        }
        
        if (dateTo) {
            const rowDate = row.dataset.date;
            show = show && rowDate <= dateTo;
        }
        
        if (searchTerm) {
            const text = row.textContent.toLowerCase();
            show = show && text.includes(searchTerm);
        }
        
        row.style.display = show ? '' : 'none';
    });
}

function resetFilters() {
    const filterIds = ['filterStatus', 'filterDateFrom', 'filterDateTo', 'searchHistory'];
    filterIds.forEach(id => {
        const el = document.getElementById(id);
        if (el) el.value = '';
    });
    
    document.querySelectorAll('#weaponHistoryTable tbody tr, #ammoHistoryTable tbody tr').forEach(row => {
        row.style.display = '';
    });
}