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

// These variables MUST come from the controller
$ammunition = isset($ammunition) ? $ammunition : [];
$statistics = isset($statistics) ? $statistics : [
    'total_types' => 0,
    'total_rounds' => 0,
    'expiring_soon' => 0,
    'active_count' => 0,
    'expired_count' => 0,
    'damaged_count' => 0
];

// Filter options should come from the controller
$ammoTypes = isset($ammoTypes) ? $ammoTypes : [];
$calibres = isset($calibres) ? $calibres : [];
?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-content">
            <h1>
                <i class="fas fa-bullseye"></i>
                Ammunition Inventory
            </h1>
            <p>Manage all ammunition stock and inventory</p>
        </div>
        <div class="header-actions">
            <?php if (Auth::can('ammunition.create')): ?>
            <a href="<?php echo BASE_URL; ?>/ammunition/create" class="btn btn-success">
                <i class="fas fa-plus-circle"></i> Add New Ammunition
            </a>
            <?php endif; ?>
            <a href="<?php echo BASE_URL; ?>/ammunition/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; ?>/ammunition/export" class="btn btn-outline">
                <i class="fas fa-download"></i> Export
            </a>
            <?php endif; ?>
        </div>
    </div>

    <!-- Statistics Cards - Two Equal Rows -->
    <!-- Row 1: Stock Overview -->
    <div class="stats-row">
        <div class="stat-card">
            <div class="stat-icon total">
                <i class="fas fa-boxes"></i>
            </div>
            <div class="stat-details">
                <h4>Total Types</h4>
                <p class="stat-number"><?php echo number_format($statistics['total_types'] ?? 0); ?></p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon rounds">
                <i class="fas fa-calculator"></i>
            </div>
            <div class="stat-details">
                <h4>Total Rounds</h4>
                <p class="stat-number"><?php echo number_format($statistics['total_rounds'] ?? 0); ?></p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon expiring">
                <i class="fas fa-clock"></i>
            </div>
            <div class="stat-details">
                <h4>Expiring Soon</h4>
                <p class="stat-number"><?php echo number_format($statistics['expiring_soon'] ?? 0); ?></p>
            </div>
        </div>
    </div>

    <!-- Row 2: Condition Status -->
    <div class="stats-row">
        <div class="stat-card condition-active">
            <div class="stat-icon active">
                <i class="fas fa-check-circle"></i>
            </div>
            <div class="stat-details">
                <h4>Active</h4>
                <p class="stat-number"><?php echo number_format($statistics['active_count'] ?? 0); ?></p>
                <small class="stat-subtitle">Serviceable items</small>
            </div>
        </div>
        <div class="stat-card condition-expired">
            <div class="stat-icon expired">
                <i class="fas fa-calendar-times"></i>
            </div>
            <div class="stat-details">
                <h4>Expired</h4>
                <p class="stat-number"><?php echo number_format($statistics['expired_count'] ?? 0); ?></p>
                <small class="stat-subtitle">Past expiry date</small>
            </div>
        </div>
        <div class="stat-card condition-damaged">
            <div class="stat-icon damaged">
                <i class="fas fa-broken"></i>
            </div>
            <div class="stat-details">
                <h4>Damaged</h4>
                <p class="stat-number"><?php echo number_format($statistics['damaged_count'] ?? 0); ?></p>
                <small class="stat-subtitle">Unserviceable</small>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="filter-section">
        <div class="filter-header" onclick="toggleFilters()">
            <h3><i class="fas fa-filter"></i> Filter Ammunition</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="searchAmmo" class="form-control" placeholder="Search by ID, type, calibre...">
                </div>
                <div class="filter-group">
                    <label>Ammunition Type</label>
                    <select id="filterType" class="form-control">
                        <option value="">All Types</option>
                        <?php if (!empty($ammoTypes)): ?>
                            <?php foreach ($ammoTypes as $type): ?>
                            <option value="<?php echo $type['id']; ?>"><?php echo htmlspecialchars($type['ammo_type'] ?? ''); ?></option>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Storage Location</label>
                    <select id="filterLocation" class="form-control">
                        <option value="">All Locations</option>
                        <option value="HQ Armoury">HQ Armoury</option>
                        <option value="Zonal Armoury">Zonal Armoury</option>
                        <option value="Command Armoury">Command Armoury</option>
                        <option value="Lost">Lost</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Condition</label>
                    <select id="filterCondition" class="form-control">
                        <option value="">All Conditions</option>
                        <option value="active">Active</option>
                        <option value="expired">Expired</option>
                        <option value="damaged">Damaged</option>
                    </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>

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

        <div class="table-responsive">
            <?php if (empty($ammunition)): ?>
                <div class="empty-state">
                    <i class="fas fa-bullseye"></i>
                    <p>No ammunition found</p>
                    <?php if (Auth::can('ammunition.create')): ?>
                    <a href="<?php echo BASE_URL; ?>/ammunition/create" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Add First Ammunition
                    </a>
                    <?php endif; ?>
                </div>
            <?php else: ?>
            <table class="asset-table" id="ammoTable">
                <thead>
                    <tr>
                        <th data-sort="text">S/N</th>
                        <th data-sort="text">Ammo ID</th>
                        <th data-sort="text">Type</th>
                        <th data-sort="text">Calibre</th>
                        <th data-sort="text">Batch Number</th>
                        <th data-sort="number">Received</th>
                        <th data-sort="number">Issued</th>
                        <th data-sort="number">Balance</th>
                        <th data-sort="text">Storage</th>
                        <th data-sort="date">Expiry</th>
                        <th data-sort="text">Condition</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($ammunition as $index => $ammo): 
                        // Calculate balance
                        $received = isset($ammo['quantity_received']) ? (int)$ammo['quantity_received'] : 0;
                        $issued = isset($ammo['quantity_issued']) ? (int)$ammo['quantity_issued'] : 0;
                        $balance = $received - $issued;
                        
                        // Calculate expiry
                        $expiryDate = !empty($ammo['expiry_date']) ? strtotime($ammo['expiry_date']) : null;
                        $today = time();
                        $daysToExpiry = $expiryDate ? round(($expiryDate - $today) / (60 * 60 * 24)) : null;
                        
                        // Determine condition status
                        $conditionStatus = strtolower($ammo['condition'] ?? 'active');
                        $isExpired = $daysToExpiry !== null && $daysToExpiry < 0;
                        
                        // Row classes for styling
                        $rowClass = '';
                        if ($balance < 100) {
                            $rowClass = 'low-stock-row';
                        } elseif ($daysToExpiry && $daysToExpiry <= 90 && $daysToExpiry > 0) {
                            $rowClass = 'expiring-row';
                        }
                    ?>
                    <tr class="<?php echo $rowClass; ?>" 
                        data-type="<?php echo $ammo['ammo_type_id'] ?? ''; ?>"
                        data-calibre="<?php echo $ammo['calibre_id'] ?? ''; ?>"
                        data-location="<?php echo strtolower($ammo['storage_location'] ?? ''); ?>"
                        data-condition="<?php echo $isExpired ? 'expired' : $conditionStatus; ?>"
                        data-balance="<?php echo $balance; ?>">
                        <td><?php echo $index + 1; ?></td>
                        <td>
                            <span class="asset-code"><?php echo htmlspecialchars($ammo['ammo_id'] ?? ''); ?></span>
                        </td>
                        <td>
                            <span class="badge badge-primary"><?php echo htmlspecialchars($ammo['ammo_type'] ?? 'Other'); ?></span>
                            <?php if (!empty($ammo['ammo_type_other'])): ?>
                                <small>(<?php echo htmlspecialchars($ammo['ammo_type_other']); ?>)</small>
                            <?php endif; ?>
                        </td>
                        <td><?php echo htmlspecialchars($ammo['calibre'] ?? 'N/A'); ?></td>
                        <td><?php echo htmlspecialchars($ammo['batch_number'] ?? '-'); ?></td>
                        <td class="text-right"><?php echo number_format($received); ?></td>
                        <td class="text-right"><?php echo number_format($issued); ?></td>
                        <td class="text-right <?php echo $balance < 100 ? 'text-danger font-weight-bold' : ''; ?>">
                            <?php echo number_format($balance); ?>
                        </td>
                        <td><?php echo htmlspecialchars($ammo['storage_location'] ?? ''); ?></td>
                        <td>
                            <?php if (!empty($ammo['expiry_date'])): ?>
                                <span class="<?php echo $daysToExpiry && $daysToExpiry <= 90 && $daysToExpiry > 0 ? 'expiry-warning' : ''; ?>">
                                    <?php echo date('d/m/Y', strtotime($ammo['expiry_date'])); ?>
                                </span>
                                <?php if ($daysToExpiry && $daysToExpiry <= 90): ?>
                                    <br><small class="days-remaining <?php echo $daysToExpiry < 0 ? 'expired' : 'warning'; ?>">
                                        <?php echo $daysToExpiry < 0 ? 'Expired' : $daysToExpiry . ' days'; ?>
                                    </small>
                                <?php endif; ?>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php 
                            $condition = $isExpired ? 'Expired' : ($ammo['condition'] ?? 'Active');
                            $conditionClass = '';
                            if ($condition == 'Active' || $condition == 'Serviceable') $conditionClass = 'status-active';
                            elseif ($condition == 'Expired') $conditionClass = 'status-expired';
                            elseif ($condition == 'Damaged' || $condition == 'Unserviceable') $conditionClass = 'status-damaged';
                            ?>
                            <span class="status-badge <?php echo $conditionClass; ?>">
                                <?php echo htmlspecialchars($condition); ?>
                            </span>
                        </td>
                        <td>
                            <div class="action-buttons">
                                <a href="<?php echo BASE_URL; ?>/ammunition/show/<?php echo $ammo['id'] ?? ''; ?>" 
                                   class="btn-icon" title="View Details">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <?php if (Auth::can('ammunition.edit')): ?>
                                <a href="<?php echo BASE_URL; ?>/ammunition/edit/<?php echo $ammo['id'] ?? ''; ?>" 
                                   class="btn-icon" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <?php endif; ?>
                                <?php if (Auth::can('ammunition.delete')): ?>
                                <a href="<?php echo BASE_URL; ?>/ammunition/delete/<?php echo $ammo['id'] ?? ''; ?>" 
                                   class="btn-icon delete" title="Delete"
                                   onclick="return confirm('Are you sure you want to delete this ammunition record?')">
                                    <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>
:root {
    --primary-color: #2c3e50;
    --primary-light: #27ae60;
    --secondary-color: #27ae60;
    --secondary-dark: #219a52;
    --success-color: #27ae60;
    --danger-color: #e53e3e;
    --warning-color: #f39c12;
    --info-color: #3498db;
    --light-bg: #f8f9fa;
    --border-color: #e2e8f0;
    --text-primary: #2c3e50;
    --text-secondary: #7f8c8d;
}

/* Statistics Rows - Two Equal Rows */
.stats-row {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
    margin-bottom: 20px;
}

.stats-row:last-child {
    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);
    transition: transform 0.3s, box-shadow 0.3s;
}

.stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 20px rgba(0,0,0,0.1);
}

.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.rounds {
    background: #e8f5e9;
    color: #388e3c;
}

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

.stat-icon.active {
    background: #e8f5e9;
    color: #2e7d32;
}

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

.stat-icon.damaged {
    background: #f3e5f5;
    color: #7b1fa2;
}

.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;
}

.stat-subtitle {
    font-size: 0.7rem;
    color: var(--text-secondary);
    margin-top: 2px;
    display: block;
}

.condition-active {
    border-left: 4px solid #2e7d32;
}

.condition-expired {
    border-left: 4px solid #c62828;
}

.condition-damaged {
    border-left: 4px solid #7b1fa2;
}

/* 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-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 {
    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;
}

/* Content Card */
.content-card {
    background: white;
    border-radius: 10px;
    padding: 25px;
    margin-bottom: 25px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.section-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid var(--border-color);
}

.section-title h2 {
    margin: 0;
    font-size: 1.4rem;
    color: var(--text-primary);
    display: flex;
    align-items: center;
    gap: 10px;
}

.card-actions {
    display: flex;
    align-items: center;
    gap: 15px;
}

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

/* Table Styles */
.table-responsive {
    overflow-x: auto;
}

.asset-table {
    width: 100%;
    border-collapse: collapse;
}

.asset-table th {
    background: var(--primary-color);
    color: white;
    padding: 12px 15px;
    text-align: left;
    font-weight: 600;
    white-space: nowrap;
}

.asset-table td {
    padding: 12px 15px;
    border-bottom: 1px solid var(--border-color);
}

.asset-table tbody tr:hover {
    background: var(--light-bg);
}

/* 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;
}

/* 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-expired {
    background: #f8d7da;
    color: #721c24;
}

.status-damaged {
    background: #e2e3e5;
    color: #383d41;
}

/* Asset Code */
.asset-code {
    font-family: 'Courier New', monospace;
    font-weight: 600;
    color: var(--primary-color);
    background: var(--light-bg);
    padding: 4px 8px;
    border-radius: 4px;
}

/* Expiry and Low Stock Indicators */
.expiry-warning {
    color: #f57c00;
    font-weight: 600;
}

.low-stock-row {
    background-color: #fff3e0;
}

.expiring-row {
    background-color: #ffebee;
}

.days-remaining {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 0.7rem;
    font-weight: 600;
}

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

.days-remaining.expired {
    background: #f8d7da;
    color: #721c24;
}

.text-right {
    text-align: right;
}

.text-danger {
    color: var(--danger-color);
}

.font-weight-bold {
    font-weight: 700;
}

/* Action Buttons */
.action-buttons {
    display: flex;
    gap: 5px;
}

.btn-icon {
    width: 32px;
    height: 32px;
    border-radius: 6px;
    border: none;
    background: var(--light-bg);
    color: var(--text-primary);
    display: inline-flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;
    text-decoration: none;
}

.btn-icon:hover {
    background: var(--success-color);
    color: white;
    transform: translateY(-2px);
}

.btn-icon.delete:hover {
    background: var(--danger-color);
}

/* 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;
}

/* Buttons */
.btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 10px 20px;
    border: none;
    border-radius: 6px;
    font-size: 1rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    text-decoration: none;
}

.btn-success {
    background: var(--success-color);
    color: white;
}

.btn-success:hover {
    background: var(--secondary-dark);
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(39, 174, 96, 0.3);
}

.btn-info {
    background: var(--info-color);
    color: white;
}

.btn-info:hover {
    background: #2980b9;
    transform: translateY(-2px);
}

.btn-outline {
    background: transparent;
    color: var(--text-secondary);
    border: 1px solid var(--border-color);
}

.btn-outline:hover {
    background: var(--light-bg);
    color: var(--text-primary);
    border-color: var(--success-color);
}

.btn-primary {
    background: var(--primary-color);
    color: white;
}

.btn-primary:hover {
    background: #1a252f;
}

/* 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;
    background: white;
}

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

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

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

/* Responsive */
@media (max-width: 768px) {
    .stats-row {
        grid-template-columns: 1fr;
        gap: 15px;
    }
    
    .filter-grid {
        grid-template-columns: 1fr;
    }
    
    .filter-actions {
        flex-direction: column;
    }
    
    .section-title {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }
    
    .card-actions {
        width: 100%;
    }
}

@media (max-width: 1024px) and (min-width: 769px) {
    .stats-row {
        gap: 15px;
    }
    
    .stat-card {
        padding: 15px;
    }
    
    .stat-number {
        font-size: 1.5rem;
    }
}
</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';
    }
}

function applyFilters() {
    const searchTerm = document.getElementById('searchAmmo').value.toLowerCase().trim();
    const type = document.getElementById('filterType').value;
    const location = document.getElementById('filterLocation').value.toLowerCase();
    const condition = document.getElementById('filterCondition').value.toLowerCase();
    
    const rows = document.querySelectorAll('#ammoTable tbody tr');
    filteredRows = [];
    
    rows.forEach(row => {
        let show = true;
        
        // Search filter
        if (searchTerm !== '') {
            const text = row.textContent.toLowerCase();
            show = show && text.includes(searchTerm);
        }
        
        // Type filter
        if (type !== '' && show) {
            show = row.dataset.type === type;
        }
        
        // Location filter
        if (location !== '' && show) {
            show = row.dataset.location === location;
        }
        
        // Condition filter
        if (condition !== '' && show) {
            show = row.dataset.condition === condition;
        }
        
        if (show) {
            filteredRows.push(row);
        }
    });
    
    currentPage = 1;
    updateDisplay();
}

function resetFilters() {
    document.getElementById('searchAmmo').value = '';
    document.getElementById('filterType').value = '';
    document.getElementById('filterLocation').value = '';
    document.getElementById('filterCondition').value = '';
    
    const rows = document.querySelectorAll('#ammoTable tbody tr');
    filteredRows = Array.from(rows);
    
    currentPage = 1;
    updateDisplay();
}

function updateDisplay() {
    const totalRecords = filteredRows.length;
    document.getElementById('recordCount').textContent = totalRecords;
    
    // Hide all rows first
    document.querySelectorAll('#ammoTable tbody tr').forEach(row => {
        row.style.display = 'none';
    });
    
    if (totalRecords === 0) {
        document.getElementById('pagination').innerHTML = '';
        return;
    }
    
    // Show only current page rows
    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();
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    const rows = document.querySelectorAll('#ammoTable tbody tr');
    filteredRows = Array.from(rows);
    document.getElementById('recordCount').textContent = filteredRows.length;
    updateDisplay();
});

// Search with debounce
let searchTimeout;
document.getElementById('searchAmmo').addEventListener('input', function() {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(() => {
        currentPage = 1;
        applyFilters();
    }, 300);
});

// Filter change events
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();
});
</script>