<?php
$title = 'Weapons & Ammunition Issue';
$active = 'weapon_issue';
require_once __DIR__ . '/../layouts/header.php';
require_once __DIR__ . '/../layouts/sidebar.php';

// These variables come from the controller
$availableWeapons = isset($availableWeapons) ? $availableWeapons : [];
$availableAmmunition = isset($availableAmmunition) ? $availableAmmunition : [];
$requisitions = isset($requisitions) ? $requisitions : [];
$recentWeaponIssues = isset($recentWeaponIssues) ? $recentWeaponIssues : [];
$recentAmmoIssues = isset($recentAmmoIssues) ? $recentAmmoIssues : [];
$issuedWeapons = isset($issuedWeapons) ? $issuedWeapons : [];
$issuedAmmunition = isset($issuedAmmunition) ? $issuedAmmunition : [];
$statistics = isset($statistics) ? $statistics : [];

// Generate CSRF token manually
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrfToken = $_SESSION['csrf_token'];
?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-content">
            <h1>
                <i class="fas fa-hand-holding"></i>
                Weapons & Ammunition Issue
            </h1>
            <p>Manage weapon and ammunition issuance, tracking, and returns</p>
        </div>
        <div class="header-actions">
            <a href="<?php echo BASE_URL ?? ''; ?>/weapon_issue/create.php" class="btn btn-success">
                <i class="fas fa-plus-circle"></i> New Issue
            </a>
            <a href="<?php echo BASE_URL ?? ''; ?>/weapon_issue/history" class="btn btn-info">
                <i class="fas fa-history"></i> View Full History
            </a>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon total-weapons">
                <i class="fas fa-gun"></i>
            </div>
            <div class="stat-details">
                <h4>Total Weapons Issued</h4>
                <p class="stat-number"><?php echo number_format($statistics['total_issued_weapons'] ?? 0); ?></p>
                <small>All time issues</small>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon total-ammo">
                <i class="fas fa-bullseye"></i>
            </div>
            <div class="stat-details">
                <h4>Total Ammunition Issued</h4>
                <p class="stat-number"><?php echo number_format($statistics['total_issued_ammunition'] ?? 0); ?></p>
                <small>Rounds issued</small>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon available">
                <i class="fas fa-check-circle"></i>
            </div>
            <div class="stat-details">
                <h4>Total Available</h4>
                <p class="stat-number"><?php echo number_format(($statistics['available_weapons'] ?? 0) + ($statistics['available_ammo_types'] ?? 0)); ?></p>
                <small>Weapons + Ammo types</small>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon lost">
                <i class="fas fa-exclamation-triangle"></i>
            </div>
            <div class="stat-details">
                <h4>Lost Weapons</h4>
                <p class="stat-number"><?php echo number_format($statistics['lost_weapons'] ?? 0); ?></p>
                <small>Reported lost/stolen</small>
            </div>
        </div>
    </div>

    <!-- Tab Navigation -->
    <div class="tab-navigation">
        <button class="tab-btn active" onclick="showTab('issued-weapons', this)">
            <i class="fas fa-gun"></i> All Issued Weapons
        </button>
        <button class="tab-btn" onclick="showTab('issued-ammunition', this)">
            <i class="fas fa-bullseye"></i> All Issued Ammunition
        </button>
        <button class="tab-btn" onclick="showTab('lost-weapons', this)">
            <i class="fas fa-exclamation-triangle"></i> Lost Weapons
        </button>
    </div>

    <!-- Tab 1: All Issued Weapons -->
    <div id="tab-issued-weapons" class="tab-content active">
        <div class="data-section">
            <div class="section-title">
                <h3><i class="fas fa-gun"></i> Currently Issued Weapons</h3>
                <div class="card-actions">
                    <input type="text" id="searchWeapons" class="search-input" placeholder="Search weapons...">
                    <button class="btn-icon" onclick="exportTableToCSV('issued-weapons.csv')">
                        <i class="fas fa-download"></i>
                    </button>
                </div>
            </div>

            <div class="table-responsive">
                <?php if (empty($issuedWeapons)): ?>
                    <div class="empty-state">
                        <i class="fas fa-gun"></i>
                        <p>No weapons currently issued</p>
                    </div>
                <?php else: ?>
                <table class="asset-table" id="weaponsTable">
                    <thead>
                        <tr>
                            <th>Weapon ID</th>
                            <th>Make/Model</th>
                            <th>Serial No.</th>
                            <th>Calibre</th>
                            <th>Issued To</th>
                            <th>Rank</th>
                            <th>Unit</th>
                            <th>Issue Date</th>
                            <th>Expected Return</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($issuedWeapons as $weapon): 
                            $issueDate = isset($weapon['issue_date']) ? strtotime($weapon['issue_date']) : time();
                            $daysOut = floor((time() - $issueDate) / (60 * 60 * 24));
                            $expectedReturn = isset($weapon['expected_return_date']) ? strtotime($weapon['expected_return_date']) : 0;
                            $overdue = ($expectedReturn && $expectedReturn < time());
                            $status = $weapon['status'] ?? 'Issued';
                        ?>
                        <tr class="<?php echo $overdue ? 'overdue' : ''; ?>">
                            <td><?php echo htmlspecialchars($weapon['weapon_id'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($weapon['make_model'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($weapon['serial_no'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($weapon['calibre_name'] ?? $weapon['calibre_other'] ?? 'N/A'); ?></td>
                            <td><?php echo htmlspecialchars($weapon['officer_name'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($weapon['officer_rank'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($weapon['unit'] ?? ''); ?></td>
                            <td><?php echo !empty($weapon['issue_date']) ? date('d/m/Y', strtotime($weapon['issue_date'])) : '-'; ?></td>
                            <td>
                                <?php echo !empty($weapon['expected_return_date']) ? date('d/m/Y', strtotime($weapon['expected_return_date'])) : 'Not set'; ?>
                                <?php if ($overdue): ?>
                                    <span class="badge-danger">Overdue</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="status-badge status-<?php echo strtolower($status); ?>">
                                    <?php echo htmlspecialchars($status); ?>
                                </span>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <a href="<?php echo BASE_URL ?? ''; ?>/weapon_issue/return/<?php echo $weapon['id'] ?? ''; ?>?type=weapon" 
                                       class="btn btn-sm btn-primary" title="Return Weapon">
                                        <i class="fas fa-undo-alt"></i>
                                    </a>
                                    <a href="<?php echo BASE_URL ?? ''; ?>/weapon_issue/report-lost/<?php echo $weapon['id'] ?? ''; ?>?type=weapon" 
                                       class="btn btn-sm btn-danger" title="Report Lost">
                                        <i class="fas fa-exclamation-triangle"></i>
                                    </a>
                                    <a href="<?php echo BASE_URL ?? ''; ?>/weapon_issue/view/<?php echo $weapon['id'] ?? ''; ?>?type=weapon" 
                                       class="btn btn-sm btn-info" title="View Details">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Tab 2: All Issued Ammunition -->
    <div id="tab-issued-ammunition" class="tab-content">
        <div class="data-section">
            <div class="section-title">
                <h3><i class="fas fa-bullseye"></i> Currently Issued Ammunition</h3>
                <div class="card-actions">
                    <input type="text" id="searchAmmunition" class="search-input" placeholder="Search ammunition...">
                    <button class="btn-icon" onclick="exportTableToCSV('issued-ammunition.csv')">
                        <i class="fas fa-download"></i>
                    </button>
                </div>
            </div>

            <div class="table-responsive">
                <?php if (empty($issuedAmmunition)): ?>
                    <div class="empty-state">
                        <i class="fas fa-bullseye"></i>
                        <p>No ammunition currently issued</p>
                    </div>
                <?php else: ?>
                <table class="asset-table" id="ammunitionTable">
                    <thead>
                        <tr>
                            <th>Ammunition ID</th>
                            <th>Type</th>
                            <th>Calibre</th>
                            <th>Units Issued</th>
                            <th>Total Rounds</th>
                            <th>Issued To</th>
                            <th>Rank</th>
                            <th>Unit</th>
                            <th>Issue Date</th>
                            <th>Purpose</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($issuedAmmunition as $ammo): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($ammo['ammo_id'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($ammo['ammo_type'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($ammo['calibre'] ?? 'N/A'); ?></td>
                            <td><?php echo number_format($ammo['units_issued'] ?? 0); ?></td>
                            <td><?php echo number_format($ammo['total_rounds'] ?? 0); ?></td>
                            <td><?php echo htmlspecialchars($ammo['issued_to'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($ammo['rank'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($ammo['unit'] ?? ''); ?></td>
                            <td><?php echo !empty($ammo['issue_date']) ? date('d/m/Y', strtotime($ammo['issue_date'])) : '-'; ?></td>
                            <td><?php echo htmlspecialchars($ammo['purpose'] ?? ''); ?></td>
                            <td>
                                <span class="status-badge status-<?php echo strtolower($ammo['status'] ?? 'issued'); ?>">
                                    <?php echo htmlspecialchars($ammo['status'] ?? 'Issued'); ?>
                                </span>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <a href="<?php echo BASE_URL ?? ''; ?>/weapon_issue/return/<?php echo $ammo['id'] ?? ''; ?>?type=ammunition" 
                                       class="btn btn-sm btn-primary" title="Return Ammunition">
                                        <i class="fas fa-undo-alt"></i>
                                    </a>
                                    <a href="<?php echo BASE_URL ?? ''; ?>/weapon_issue/view/<?php echo $ammo['id'] ?? ''; ?>?type=ammunition" 
                                       class="btn btn-sm btn-info" title="View Details">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Tab 3: Lost Weapons -->
    <div id="tab-lost-weapons" class="tab-content">
        <div class="data-section">
            <div class="section-title">
                <h3><i class="fas fa-exclamation-triangle"></i> Lost/Stolen Weapons Report</h3>
                <div class="card-actions">
                    <input type="text" id="searchLost" class="search-input" placeholder="Search lost weapons...">
                </div>
            </div>

            <div class="table-responsive">
                <?php 
                $lostWeapons = array_filter($issuedWeapons ?? [], function($w) {
                    return ($w['status'] ?? '') === 'Lost' || ($w['status'] ?? '') === 'Stolen';
                });
                ?>
                <?php if (empty($lostWeapons)): ?>
                    <div class="empty-state">
                        <i class="fas fa-check-circle"></i>
                        <p>No lost or stolen weapons reported</p>
                    </div>
                <?php else: ?>
                <table class="asset-table" id="lostWeaponsTable">
                    <thead>
                        <tr>
                            <th>Weapon ID</th>
                            <th>Make/Model</th>
                            <th>Serial No.</th>
                            <th>Calibre</th>
                            <th>Last Issued To</th>
                            <th>Date Issued</th>
                            <th>Date Reported Lost</th>
                            <th>Status</th>
                            <th>Incident Report</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($lostWeapons as $weapon): ?>
                        <tr class="lost-row">
                            <td><?php echo htmlspecialchars($weapon['weapon_id'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($weapon['make_model'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($weapon['serial_no'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($weapon['calibre_name'] ?? $weapon['calibre_other'] ?? 'N/A'); ?></td>
                            <td><?php echo htmlspecialchars($weapon['officer_name'] ?? ''); ?></td>
                            <td><?php echo !empty($weapon['issue_date']) ? date('d/m/Y', strtotime($weapon['issue_date'])) : '-'; ?></td>
                            <td><?php echo !empty($weapon['lost_date']) ? date('d/m/Y', strtotime($weapon['lost_date'])) : '-'; ?></td>
                            <td>
                                <span class="status-badge status-lost">
                                    <?php echo htmlspecialchars($weapon['status'] ?? 'Lost'); ?>
                                </span>
                            </td>
                            <td>
                                <?php if (!empty($weapon['incident_report'])): ?>
                                    <button class="btn-link" onclick="viewIncidentReport('<?php echo htmlspecialchars($weapon['incident_report']); ?>')">
                                        View Report
                                    </button>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <a href="<?php echo BASE_URL ?? ''; ?>/weapon_issue/update-status/<?php echo $weapon['id'] ?? ''; ?>?type=weapon" 
                                       class="btn btn-sm btn-warning" title="Update Status">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<style>
/* Stats Grid - Enhanced */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 20px;
    margin-bottom: 25px;
}

.stat-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 15px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 15px;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    transition: transform 0.3s;
}

.stat-card:hover {
    transform: translateY(-5px);
}

.stat-card:nth-child(1) { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.stat-card:nth-child(2) { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.stat-card:nth-child(3) { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.stat-card:nth-child(4) { background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); }

.stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.8rem;
    background: rgba(255,255,255,0.2);
    color: white;
}

.stat-details h4 {
    margin: 0 0 5px 0;
    font-size: 0.9rem;
    color: rgba(255,255,255,0.9);
}

.stat-number {
    font-size: 2rem;
    font-weight: bold;
    margin: 0;
    color: white;
    line-height: 1.2;
}

.stat-details small {
    color: rgba(255,255,255,0.7);
    font-size: 0.8rem;
}

/* Tab Navigation */
.tab-navigation {
    display: flex;
    gap: 10px;
    margin-bottom: 25px;
    background: white;
    padding: 15px;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.tab-btn {
    padding: 12px 24px;
    border: none;
    border-radius: 8px;
    background: #f8f9fa;
    color: #2c3e50;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    display: flex;
    align-items: center;
    gap: 8px;
}

.tab-btn:hover {
    background: #e9ecef;
    transform: translateY(-2px);
}

.tab-btn.active {
    background: #27ae60;
    color: white;
}

.tab-content {
    display: none;
    animation: fadeIn 0.5s;
}

.tab-content.active {
    display: block;
}

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

/* Data Sections */
.data-section {
    background: white;
    border-radius: 10px;
    padding: 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: 2px solid #f0f0f0;
}

.section-title h3 {
    margin: 0;
    font-size: 1.3rem;
    color: #2c3e50;
    display: flex;
    align-items: center;
    gap: 10px;
}

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

.search-input {
    padding: 8px 15px;
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    width: 250px;
    font-size: 0.9rem;
    transition: all 0.3s;
}

.search-input:focus {
    outline: none;
    border-color: #27ae60;
    box-shadow: 0 0 0 3px rgba(39, 174, 96, 0.2);
}

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

.asset-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 0.9rem;
}

.asset-table thead {
    background: #f8f9fa;
}

.asset-table th {
    padding: 12px;
    text-align: left;
    font-weight: 600;
    color: #2c3e50;
    border-bottom: 2px solid #e2e8f0;
}

.asset-table td {
    padding: 12px;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
}

.asset-table tbody tr:hover {
    background: #f8f9fa;
}

.asset-table tr.overdue {
    background: #fff5f5;
}

.asset-table tr.lost-row {
    background: #fff3e0;
}

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

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

.status-returned {
    background: #cce5ff;
    color: #004085;
}

.status-lost, .status-stolen {
    background: #f8d7da;
    color: #721c24;
}

.badge-danger {
    display: inline-block;
    background: #dc3545;
    color: white;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 0.7rem;
    margin-left: 5px;
}

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

.btn {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 6px 12px;
    border: none;
    border-radius: 6px;
    font-size: 0.85rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    text-decoration: none;
}

.btn-sm {
    padding: 5px 10px;
    font-size: 0.8rem;
}

.btn-primary {
    background: #2c3e50;
    color: white;
}

.btn-primary:hover {
    background: #1a252f;
    transform: translateY(-2px);
}

.btn-danger {
    background: #dc3545;
    color: white;
}

.btn-danger:hover {
    background: #c82333;
    transform: translateY(-2px);
}

.btn-warning {
    background: #ffc107;
    color: #212529;
}

.btn-warning:hover {
    background: #e0a800;
    transform: translateY(-2px);
}

.btn-info {
    background: #17a2b8;
    color: white;
}

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

.btn-success {
    background: #28a745;
    color: white;
    padding: 10px 20px;
}

.btn-success:hover {
    background: #218838;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(40, 167, 69, 0.3);
}

.btn-icon {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 1.2rem;
    color: #7f8c8d;
    transition: color 0.3s;
}

.btn-icon:hover {
    color: #27ae60;
}

.btn-link {
    background: none;
    border: none;
    color: #27ae60;
    cursor: pointer;
    text-decoration: underline;
}

/* Empty State */
.empty-state {
    text-align: center;
    padding: 60px;
    color: #7f8c8d;
}

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

.empty-state p {
    font-size: 1.1rem;
    margin: 0;
}

/* Responsive */
@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }
    
    .tab-navigation {
        flex-direction: column;
    }
    
    .tab-btn {
        justify-content: center;
    }
    
    .section-title {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }
    
    .card-actions {
        width: 100%;
    }
    
    .search-input {
        width: 100%;
    }
    
    .action-buttons {
        flex-direction: column;
    }
    
    .asset-table {
        font-size: 0.8rem;
    }
    
    .asset-table th, 
    .asset-table td {
        padding: 8px;
    }
}
</style>

<script>
// Tab switching
function showTab(tabName, element) {
    // Hide all tabs
    document.querySelectorAll('.tab-content').forEach(tab => {
        tab.classList.remove('active');
    });
    
    // Remove active class from all tab buttons
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    
    // Show selected tab
    document.getElementById('tab-' + tabName).classList.add('active');
    
    // Add active class to clicked button
    if (element) {
        element.classList.add('active');
    }
}

// Search functionality
document.addEventListener('DOMContentLoaded', function() {
    // Search weapons
    const searchWeapons = document.getElementById('searchWeapons');
    if (searchWeapons) {
        searchWeapons.addEventListener('input', function(e) {
            const searchTerm = e.target.value.toLowerCase();
            const rows = document.querySelectorAll('#weaponsTable tbody tr');
            rows.forEach(row => {
                const text = row.textContent.toLowerCase();
                row.style.display = text.includes(searchTerm) ? '' : 'none';
            });
        });
    }
    
    // Search ammunition
    const searchAmmunition = document.getElementById('searchAmmunition');
    if (searchAmmunition) {
        searchAmmunition.addEventListener('input', function(e) {
            const searchTerm = e.target.value.toLowerCase();
            const rows = document.querySelectorAll('#ammunitionTable tbody tr');
            rows.forEach(row => {
                const text = row.textContent.toLowerCase();
                row.style.display = text.includes(searchTerm) ? '' : 'none';
            });
        });
    }
    
    // Search lost weapons
    const searchLost = document.getElementById('searchLost');
    if (searchLost) {
        searchLost.addEventListener('input', function(e) {
            const searchTerm = e.target.value.toLowerCase();
            const rows = document.querySelectorAll('#lostWeaponsTable tbody tr');
            rows.forEach(row => {
                const text = row.textContent.toLowerCase();
                row.style.display = text.includes(searchTerm) ? '' : 'none';
            });
        });
    }
});

// Export to CSV
function exportTableToCSV(filename) {
    const table = document.querySelector('.asset-table');
    const rows = table.querySelectorAll('tr');
    const csv = [];
    
    rows.forEach(row => {
        const cols = row.querySelectorAll('th, td');
        const rowData = Array.from(cols).map(col => {
            // Remove action buttons from export
            if (col.querySelector('.action-buttons')) {
                return '';
            }
            return '"' + col.innerText.replace(/"/g, '""') + '"';
        }).filter(cell => cell !== '');
        csv.push(rowData.join(','));
    });
    
    const blob = new Blob([csv.join('\n')], { type: 'text/csv' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.href = url;
    link.download = filename;
    link.click();
    URL.revokeObjectURL(url);
}

// View incident report
function viewIncidentReport(report) {
    alert('Incident Report:\n\n' + report);
}

// Refresh data periodically (every 30 seconds)
setInterval(function() {
    location.reload();
}, 30000);
</script>

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