<?php
$title = 'Weapons Inventory';
$active = 'weapons';
require_once __DIR__ . '/../layouts/header.php';
require_once __DIR__ . '/../layouts/sidebar.php';

// These variables should come from the controller
$weapons = isset($weapons) ? $weapons : [];
$statistics = isset($statistics) ? $statistics : [
    'total' => 0,
    'issued' => 0,
    'serviceable' => 0,
    'unserviceable' => 0
];

// Filter data should come from the controller
$weaponTypes = isset($weaponTypes) ? $weaponTypes : [];
$calibres = isset($calibres) ? $calibres : [];

// Get zones and commands from database
$zones = Database::fetchAll("SELECT id, zone_name FROM zones ORDER BY zone_name");
if ($zones === false) $zones = [];

$commands = Database::fetchAll("SELECT id, command_name, zone_id FROM commands ORDER BY command_name");
if ($commands === false) $commands = [];

// Group commands by zone
$commandsByZone = [];
foreach ($commands as $command) {
    $zoneId = $command['zone_id'];
    if (!isset($commandsByZone[$zoneId])) {
        $commandsByZone[$zoneId] = [];
    }
    $commandsByZone[$zoneId][] = $command;
}

// Get success/error messages from controller
$success = isset($success) ? $success : '';
$error = isset($error) ? $error : '';
?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-content">
            <h1>
                <i class="fas fa-gun"></i>
                Weapons Inventory
            </h1>
            <p>Manage all weapons and firearms inventory</p>
        </div>
        <div class="header-actions">
            <?php if (Auth::can('weapons.create')): ?>
            <a href="<?php echo BASE_URL; ?>/weapons/create" class="btn btn-success">
                <i class="fas fa-plus-circle"></i> Add New Weapon
            </a>
            <?php endif; ?>
            <a href="<?php echo BASE_URL; ?>/weapons/dashboard" class="btn btn-info">
                <i class="fas fa-chart-pie"></i> Dashboard
            </a>
            <?php if (Auth::can('reports.export')): ?>
            <a href="<?php echo BASE_URL; ?>/weapons/export" class="btn btn-outline">
                <i class="fas fa-download"></i> Export
            </a>
            <?php endif; ?>
        </div>
    </div>

    <!-- Success/Error Messages -->
    <?php if (!empty($success)): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert" id="successAlert">
        <i class="fas fa-check-circle"></i>
        <?php echo Security::escape($success); ?>
        <button type="button" class="btn-close" onclick="this.parentElement.style.display='none'">&times;</button>
    </div>
    <?php endif; ?>

    <?php if (!empty($error)): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert" id="errorAlert">
        <i class="fas fa-exclamation-circle"></i>
        <?php echo Security::escape($error); ?>
        <button type="button" class="btn-close" onclick="this.parentElement.style.display='none'">&times;</button>
    </div>
    <?php endif; ?>

    <!-- Statistics Cards -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon total">
                <i class="fas fa-gun"></i>
            </div>
            <div class="stat-details">
                <h4>Total Weapons</h4>
                <p class="stat-number"><?php echo number_format($statistics['total'] ?? 0); ?></p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon issued">
                <i class="fas fa-hand-holding"></i>
            </div>
            <div class="stat-details">
                <h4>Issued</h4>
                <p class="stat-number"><?php echo number_format($statistics['issued'] ?? 0); ?></p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon serviceable">
                <i class="fas fa-check-circle"></i>
            </div>
            <div class="stat-details">
                <h4>Serviceable</h4>
                <p class="stat-number"><?php echo number_format($statistics['serviceable'] ?? 0); ?></p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon unserviceable">
                <i class="fas fa-exclamation-triangle"></i>
            </div>
            <div class="stat-details">
                <h4>Unserviceable</h4>
                <p class="stat-number"><?php echo number_format($statistics['unserviceable'] ?? 0); ?></p>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="filter-section">
        <div class="filter-header" onclick="toggleFilters()">
            <h3><i class="fas fa-filter"></i> Filter Weapons</h3>
            <i class="fas fa-chevron-down" id="filterToggleIcon"></i>
        </div>
        <div class="filter-body" id="filterBody" style="display: block;">
            <div class="filter-grid">
                <div class="filter-group">
                    <label>Search</label>
                    <input type="text" id="searchWeapons" class="form-control" placeholder="Search by ID, serial, model...">
                </div>
                <div class="filter-group">
                    <label>Weapon Type</label>
                    <select id="filterType" class="form-control">
                        <option value="">All Types</option>
                        <?php if (!empty($weaponTypes) && is_array($weaponTypes)): ?>
                            <?php foreach ($weaponTypes as $type): ?>
                                <option value="<?php echo $type['id'] ?? ''; ?>">
                                    <?php echo Security::escape($type['type_name'] ?? ''); ?>
                                </option>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Condition</label>
                    <select id="filterCondition" class="form-control">
                        <option value="">All Conditions</option>
                        <option value="Serviceable">Serviceable</option>
                        <option value="Unserviceable">Unserviceable</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Location</label>
                    <select id="filterLocation" class="form-control">
                        <option value="">All Locations</option>
                        <option value="HQ Armoury">Armoury</option>
                        <!--<option value="Zonal Armoury" id="zonalArmouryOption">Zonal Armoury</option>-->
                        <!--<option value="Command Armoury" id="commandArmouryOption">Command Armoury</option>-->
                        <option value="Issued">Issued</option>
                        <option value="Lost">Lost</option>
                    </select>
                </div>
            </div>
            
            <!-- Dynamic Zone Filter - Shows when Zonal Armoury is selected -->
            <div id="zoneFilterContainer" style="display: none; margin-top: 15px;">
                <div class="filter-group">
                    <label><i class="fas fa-map-marker-alt"></i> Select Zone</label>
                    <select id="filterZone" class="form-control">
                        <option value="">All Zones</option>
                        <?php foreach ($zones as $zone): ?>
                            <option value="<?php echo Security::escape($zone['zone_name']); ?>">
                                <?php echo Security::escape($zone['zone_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            
            <!-- Dynamic Command Filter - Shows when Command Armoury is selected -->
            <div id="commandFilterContainer" style="display: none; margin-top: 15px;">
                <div class="filter-group">
                    <label><i class="fas fa-building"></i> Select Command</label>
                    <select id="filterCommand" class="form-control">
                        <option value="">All Commands</option>
                        <?php foreach ($commands as $command): ?>
                            <option value="<?php echo Security::escape($command['command_name']); ?>" data-zone-id="<?php echo $command['zone_id']; ?>">
                                <?php echo Security::escape($command['command_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            
            <div class="filter-actions">
                <button class="btn btn-primary" onclick="applyFilters()">
                    <i class="fas fa-filter"></i> Apply Filters
                </button>
                <button class="btn btn-outline" onclick="resetFilters()">
                    <i class="fas fa-times"></i> Clear Filters
                </button>
            </div>
        </div>
    </div>

    <!-- Weapons Table -->
    <div class="content-card">
        <div class="section-title">
            <h2><i class="fas fa-list"></i> Weapons Register</h2>
            <div class="card-actions">
                <span class="record-count">Showing <span id="recordCount"><?php echo count($weapons); ?></span> records</span>
            </div>
        </div>

        <div class="table-responsive">
            <?php if (empty($weapons)): ?>
                <div class="empty-state">
                    <i class="fas fa-gun"></i>
                    <p>No weapons found</p>
                    <?php if (Auth::can('weapons.create')): ?>
                    <a href="<?php echo BASE_URL; ?>/weapons/create" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Add First Weapon
                    </a>
                    <?php endif; ?>
                </div>
            <?php else: ?>
            <table class="asset-table" id="weaponsTable">
                <thead>
                    <tr>
                        <th data-sort="text">S/N</th>
                        <th data-sort="text">Weapon ID</th>
                        <th data-sort="text">Type</th>
                        <th data-sort="text">Make/Model</th>
                        <th data-sort="text">Serial Number</th>
                        <th data-sort="text">Calibre</th>
                        <th data-sort="text">Location</th>
                        <th data-sort="text">Zone/Command</th>
                        <th data-sort="text">Custodian</th>
                        <th data-sort="text">Condition</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($weapons as $index => $weapon): ?>
                    <?php
                    // Extract zone and command from location if applicable
                    $location = $weapon['current_location'] ?? '';
                    $zoneName = '';
                    $commandName = '';
                    
                    if (strpos($location, 'Zone:') !== false) {
                        preg_match('/Zone:\s*([^|]+)/', $location, $zoneMatch);
                        $zoneName = trim($zoneMatch[1] ?? '');
                    }
                    if (strpos($location, 'Command:') !== false) {
                        preg_match('/Command:\s*([^|]+)/', $location, $commandMatch);
                        $commandName = trim($commandMatch[1] ?? '');
                    }
                    ?>
                    <tr data-type="<?php echo $weapon['weapon_type_id'] ?? ''; ?>" 
                        data-calibre="<?php echo $weapon['calibre_id'] ?? ''; ?>"
                        data-location="<?php echo strtolower($location); ?>"
                        data-condition="<?php echo strtolower($weapon['condition'] ?? ''); ?>"
                        data-zone="<?php echo strtolower($zoneName); ?>"
                        data-command="<?php echo strtolower($commandName); ?>">
                        <td><?php echo $index + 1; ?></td>
                        <td>
                            <span class="asset-code"><?php echo Security::escape($weapon['weapon_id'] ?? ''); ?></span>
                         </td>
                        <td>
                            <span class="badge badge-primary"><?php echo Security::escape($weapon['weapon_type_name'] ?? $weapon['weapon_type_other'] ?? 'Other'); ?></span>
                         </td>
                        <td><?php echo Security::escape($weapon['make_model'] ?? ''); ?></td>
                        <td>
                            <span class="serial-number"><?php echo Security::escape($weapon['serial_no'] ?? ''); ?></span>
                         </td>
                        <td><?php echo Security::escape($weapon['calibre_name'] ?? $weapon['calibre_other'] ?? 'N/A'); ?></td>
                        <td>
                            <?php 
                            $locationClass = '';
                            if (strpos($location, 'Armoury') !== false) $locationClass = 'status-active';
                            elseif ($location == 'Issued') $locationClass = 'status-warning';
                            elseif ($location == 'In Repair') $locationClass = 'status-maintenance';
                            elseif ($location == 'Lost') $locationClass = 'status-rejected';
                            ?>
                            <span class="status-badge <?php echo $locationClass; ?>">
                                <?php 
                                // Display simplified location
                                if (strpos($location, 'Zonal Armoury') !== false) {
                                    echo 'Zonal Armoury';
                                } elseif (strpos($location, 'Command Armoury') !== false) {
                                    echo 'Command Armoury';
                                } else {
                                    echo Security::escape($location);
                                }
                                ?>
                            </span>
                         </td>
                        <td>
                            <?php
                            $zoneCommandDisplay = '';
                            if (!empty($zoneName)) {
                                $zoneCommandDisplay = '<span class="badge badge-info">Zone: ' . Security::escape($zoneName) . '</span>';
                            }
                            if (!empty($commandName)) {
                                if (!empty($zoneCommandDisplay)) $zoneCommandDisplay .= '<br>';
                                $zoneCommandDisplay .= '<span class="badge badge-success">Command: ' . Security::escape($commandName) . '</span>';
                            }
                            echo $zoneCommandDisplay ?: '-';
                            ?>
                         </td>
                        <td><?php echo Security::escape($weapon['custodian'] ?? '-'); ?></td>
                        <td>
                            <?php 
                            $condition = $weapon['condition'] ?? '';
                            $conditionClass = '';
                            if ($condition == 'Serviceable') $conditionClass = 'status-active';
                            elseif ($condition == 'Unserviceable') $conditionClass = 'status-rejected';
                            elseif ($condition == 'Under Repair') $conditionClass = 'status-warning';
                            ?>
                            <span class="status-badge <?php echo $conditionClass; ?>">
                                <?php echo Security::escape($condition); ?>
                            </span>
                         </td>
                        <td>
                            <div class="action-buttons">
                                <a href="<?php echo BASE_URL; ?>/weapons/show/<?php echo $weapon['id'] ?? ''; ?>" 
                                   class="btn-icon" title="View Details">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <?php if (Auth::can('weapons.edit')): ?>
                                <a href="<?php echo BASE_URL; ?>/weapons/edit/<?php echo $weapon['id'] ?? ''; ?>" 
                                   class="btn-icon" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <?php endif; ?>
                                <?php if (Auth::can('weapons.delete')): ?>
                                <a href="<?php echo BASE_URL; ?>/weapons/delete/<?php echo $weapon['id'] ?? ''; ?>" 
                                   class="btn-icon delete" title="Delete"
                                   onclick="return confirm('Are you sure you want to delete this weapon? This action cannot be undone.')">
                                    <i class="fas fa-trash"></i>
                                </a>
                                <?php endif; ?>
                            </div>
                         </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
        
        <!-- Pagination -->
        <div class="pagination" id="pagination"></div>
    </div>
</div>

<style>
/* Alert Styles */
.alert {
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 10px;
    animation: slideIn 0.3s ease;
}

.alert-success {
    background: #d4edda;
    border: 1px solid #c3e6cb;
    color: #155724;
}

.alert-danger {
    background: #f8d7da;
    border: 1px solid #f5c6cb;
    color: #721c24;
}

.alert i {
    font-size: 1.2rem;
}

.btn-close {
    margin-left: auto;
    background: none;
    border: none;
    font-size: 1.2rem;
    cursor: pointer;
    color: inherit;
    opacity: 0.7;
}

.btn-close:hover {
    opacity: 1;
}

@keyframes slideIn {
    from {
        transform: translateY(-20px);
        opacity: 0;
    }
    to {
        transform: translateY(0);
        opacity: 1;
    }
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 25px;
}

.stat-card {
    background: white;
    border-radius: 10px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 15px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
}

.stat-icon.total {
    background: #e3f2fd;
    color: #1976d2;
}

.stat-icon.issued {
    background: #fff3e0;
    color: #f57c00;
}

.stat-icon.serviceable {
    background: #e8f5e9;
    color: #388e3c;
}

.stat-icon.unserviceable {
    background: #ffebee;
    color: #c62828;
}

.stat-details h4 {
    margin: 0 0 5px 0;
    font-size: 0.9rem;
    color: var(--text-secondary);
}

.stat-number {
    font-size: 1.8rem;
    font-weight: bold;
    margin: 0;
    color: var(--text-primary);
    line-height: 1.2;
}

/* Filter Section */
.filter-section {
    background: white;
    border-radius: 10px;
    margin-bottom: 25px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    overflow: hidden;
}

.filter-header {
    padding: 15px 20px;
    background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-light) 100%);
    color: white;
    cursor: pointer;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.filter-header h3 {
    margin: 0;
    font-size: 1rem;
    display: flex;
    align-items: center;
    gap: 8px;
}

.filter-header i {
    transition: transform 0.3s ease;
}

.filter-body {
    padding: 20px;
    border-bottom: 1px solid var(--border-color);
}

.filter-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    margin-bottom: 15px;
}

.filter-group {
    display: flex;
    flex-direction: column;
}

.filter-group label {
    font-size: 0.85rem;
    color: var(--text-secondary);
    margin-bottom: 5px;
    font-weight: 600;
}

.filter-group input,
.filter-group select {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    font-size: 0.9rem;
}

.filter-actions {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
    margin-top: 15px;
}

/* Badge Styles */
.badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 0.8rem;
    font-weight: 500;
}

.badge-primary {
    background: #e3f2fd;
    color: #1976d2;
}

.badge-info {
    background: #e0f2f1;
    color: #00695c;
    font-size: 0.75rem;
}

.badge-success {
    background: #e8f5e9;
    color: #2e7d32;
    font-size: 0.75rem;
}

.serial-number {
    font-family: 'Courier New', monospace;
    font-size: 0.85rem;
    background: var(--light-bg);
    padding: 2px 6px;
    border-radius: 4px;
}

/* Status Badges */
.status-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.85rem;
    font-weight: 600;
}

.status-active {
    background: #d4edda;
    color: #155724;
}

.status-warning {
    background: #fff3cd;
    color: #856404;
}

.status-maintenance {
    background: #fff3cd;
    color: #856404;
}

.status-rejected {
    background: #f8d7da;
    color: #721c24;
}

/* Pagination */
.pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid var(--border-color);
}

.page-link {
    padding: 8px 12px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    color: var(--text-primary);
    text-decoration: none;
    transition: all 0.3s;
    cursor: pointer;
}

.page-link:hover {
    background: var(--light-bg);
    border-color: var(--success-color);
}

.page-link.active {
    background: var(--success-color);
    color: white;
    border-color: var(--success-color);
}

.page-link:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.page-info {
    color: var(--text-secondary);
    font-size: 0.9rem;
}

/* Empty State */
.empty-state {
    text-align: center;
    padding: 40px;
    color: var(--text-secondary);
}

.empty-state i {
    font-size: 3rem;
    margin-bottom: 15px;
    opacity: 0.5;
}

.empty-state p {
    font-size: 1rem;
    margin: 0 0 15px 0;
}

.record-count {
    font-size: 0.9rem;
    color: var(--text-secondary);
}

/* Animation for filter containers */
#zoneFilterContainer, #commandFilterContainer {
    animation: slideDown 0.3s ease;
}

@keyframes slideDown {
    from {
        opacity: 0;
        transform: translateY(-10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }
    
    .filter-grid {
        grid-template-columns: 1fr;
    }
    
    .filter-actions {
        flex-direction: column;
    }
}
</style>

<script>
let currentPage = 1;
const rowsPerPage = 10;
let filteredRows = [];

function toggleFilters() {
    const filterBody = document.getElementById('filterBody');
    const toggleIcon = document.getElementById('filterToggleIcon');
    
    if (filterBody.style.display === 'none') {
        filterBody.style.display = 'block';
        toggleIcon.className = 'fas fa-chevron-up';
    } else {
        filterBody.style.display = 'none';
        toggleIcon.className = 'fas fa-chevron-down';
    }
}

// Handle location selection change
document.getElementById('filterLocation').addEventListener('change', function() {
    const selectedValue = this.value;
    const zoneContainer = document.getElementById('zoneFilterContainer');
    const commandContainer = document.getElementById('commandFilterContainer');
    
    // Hide both containers initially
    zoneContainer.style.display = 'none';
    commandContainer.style.display = 'none';
    
    // Show appropriate container based on selection
    if (selectedValue === 'Zonal Armoury') {
        zoneContainer.style.display = 'block';
        // Reset command filter when switching
        document.getElementById('filterCommand').value = '';
    } else if (selectedValue === 'Command Armoury') {
        commandContainer.style.display = 'block';
        // Reset zone filter when switching
        document.getElementById('filterZone').value = '';
    }
});

// Optional: Filter commands by zone when zone is selected
document.getElementById('filterZone')?.addEventListener('change', function() {
    const selectedZone = this.value;
    const commandSelect = document.getElementById('filterCommand');
    
    if (commandSelect) {
        // Get all command options
        const options = commandSelect.querySelectorAll('option');
        
        if (!selectedZone) {
            // Show all commands
            options.forEach(option => {
                option.style.display = '';
            });
        } else {
            // Show only commands from selected zone
            options.forEach(option => {
                if (option.value === '') {
                    option.style.display = '';
                } else {
                    const zoneId = option.getAttribute('data-zone-id');
                    // This requires that commands have zone_id mapping
                    // You may need to adjust this logic based on your data structure
                    option.style.display = option.textContent.includes(selectedZone) ? '' : 'none';
                }
            });
        }
    }
});

function applyFilters() {
    const searchTerm = document.getElementById('searchWeapons').value.toLowerCase().trim();
    const type = document.getElementById('filterType').value;
    const location = document.getElementById('filterLocation').value.toLowerCase();
    const condition = document.getElementById('filterCondition').value.toLowerCase();
    const selectedZone = document.getElementById('filterZone')?.value.toLowerCase().trim() || '';
    const selectedCommand = document.getElementById('filterCommand')?.value.toLowerCase().trim() || '';
    
    const rows = document.querySelectorAll('#weaponsTable tbody tr');
    filteredRows = [];
    
    rows.forEach(row => {
        let show = true;
        
        // Search term filter
        if (searchTerm !== '') {
            const text = row.textContent.toLowerCase();
            show = show && text.includes(searchTerm);
        }
        
        // Weapon type filter
        if (type !== '' && show) {
            show = row.dataset.type === type;
        }
        
        // Condition filter
        if (condition !== '' && show) {
            show = row.dataset.condition === condition;
        }
        
        // Location filter with zone and command support
        if (location !== '' && show) {
            const rowLocation = row.dataset.location;
            
            if (location === 'zonal armoury') {
                // Show only weapons in zonal armoury
                show = rowLocation.includes('zonal armoury');
                // Further filter by zone if selected
                if (show && selectedZone !== '') {
                    const rowZone = row.dataset.zone || '';
                    show = rowZone === selectedZone;
                }
            } else if (location === 'command armoury') {
                // Show only weapons in command armoury
                show = rowLocation.includes('command armoury');
                // Further filter by command if selected
                if (show && selectedCommand !== '') {
                    const rowCommand = row.dataset.command || '';
                    show = rowCommand === selectedCommand;
                }
            } else {
                // Exact match for other locations
                show = rowLocation === location;
            }
        }
        
        if (show) {
            filteredRows.push(row);
        }
    });
    
    currentPage = 1;
    updateDisplay();
}

function resetFilters() {
    document.getElementById('searchWeapons').value = '';
    document.getElementById('filterType').value = '';
    document.getElementById('filterLocation').value = '';
    document.getElementById('filterCondition').value = '';
    
    // Reset zone and command filters
    const zoneSelect = document.getElementById('filterZone');
    const commandSelect = document.getElementById('filterCommand');
    if (zoneSelect) zoneSelect.value = '';
    if (commandSelect) commandSelect.value = '';
    
    // Hide zone and command containers
    const zoneContainer = document.getElementById('zoneFilterContainer');
    const commandContainer = document.getElementById('commandFilterContainer');
    if (zoneContainer) zoneContainer.style.display = 'none';
    if (commandContainer) commandContainer.style.display = 'none';
    
    const rows = document.querySelectorAll('#weaponsTable tbody tr');
    filteredRows = Array.from(rows);
    
    currentPage = 1;
    updateDisplay();
}

function updateDisplay() {
    const totalRecords = filteredRows.length;
    document.getElementById('recordCount').textContent = totalRecords;
    
    document.querySelectorAll('#weaponsTable tbody tr').forEach(row => {
        row.style.display = 'none';
    });
    
    if (totalRecords === 0) {
        document.getElementById('pagination').innerHTML = '';
        return;
    }
    
    const start = (currentPage - 1) * rowsPerPage;
    const end = Math.min(start + rowsPerPage, totalRecords);
    
    for (let i = start; i < end; i++) {
        if (filteredRows[i]) {
            filteredRows[i].style.display = '';
        }
    }
    
    updatePagination(totalRecords);
}

function updatePagination(totalRecords) {
    const totalPages = Math.ceil(totalRecords / rowsPerPage);
    const pagination = document.getElementById('pagination');
    
    if (totalPages <= 1) {
        pagination.innerHTML = '';
        return;
    }
    
    let html = `
        <button class="page-link" onclick="changePage(${currentPage - 1})" ${currentPage === 1 ? 'disabled' : ''}>
            <i class="fas fa-chevron-left"></i> Previous
        </button>
        <span class="page-info">Page ${currentPage} of ${totalPages}</span>
        <button class="page-link" onclick="changePage(${currentPage + 1})" ${currentPage === totalPages ? 'disabled' : ''}>
            Next <i class="fas fa-chevron-right"></i>
        </button>
    `;
    
    pagination.innerHTML = html;
}

function changePage(page) {
    currentPage = page;
    updateDisplay();
}

document.addEventListener('DOMContentLoaded', function() {
    const rows = document.querySelectorAll('#weaponsTable tbody tr');
    filteredRows = Array.from(rows);
    document.getElementById('recordCount').textContent = filteredRows.length;
    
    // Auto-hide success/error messages after 5 seconds
    const successAlert = document.getElementById('successAlert');
    if (successAlert) {
        setTimeout(function() {
            successAlert.style.display = 'none';
        }, 5000);
    }
    
    const errorAlert = document.getElementById('errorAlert');
    if (errorAlert) {
        setTimeout(function() {
            errorAlert.style.display = 'none';
        }, 5000);
    }
});

let searchTimeout;
document.getElementById('searchWeapons').addEventListener('input', function() {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(() => {
        currentPage = 1;
        applyFilters();
    }, 300);
});

document.getElementById('filterType').addEventListener('change', function() {
    currentPage = 1;
    applyFilters();
});

document.getElementById('filterLocation').addEventListener('change', function() {
    currentPage = 1;
    applyFilters();
});

document.getElementById('filterCondition').addEventListener('change', function() {
    currentPage = 1;
    applyFilters();
});

// Add event listeners for zone and command filters if they exist
const zoneFilter = document.getElementById('filterZone');
const commandFilter = document.getElementById('filterCommand');

if (zoneFilter) {
    zoneFilter.addEventListener('change', function() {
        currentPage = 1;
        applyFilters();
    });
}

if (commandFilter) {
    commandFilter.addEventListener('change', function() {
        currentPage = 1;
        applyFilters();
    });
}
</script>

<?php require_once __DIR__ . '/../layouts/footer.php'; ?>