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

// These variables should come from the controller
$stats = isset($stats) ? $stats : [
    'total' => 0,
    'issued' => 0,
    'serviceable' => 0,
    'unserviceable' => 0,
    'in_repair' => 0,
    'new_this_month' => 0,
    'units_count' => 0,
    'last_audit' => 'N/A',
    'by_type' => [],
    'by_calibre' => []
];

$recentIssues = isset($recentIssues) ? $recentIssues : [];

// Prepare chart data with null checks - FIXED for Weapons by Calibre
$typeLabels = !empty($stats['by_type']) && is_array($stats['by_type']) ? array_keys($stats['by_type']) : [];
$typeCounts = !empty($stats['by_type']) && is_array($stats['by_type']) ? array_values($stats['by_type']) : [];

// FIXED: Prepare data for Weapons by Calibre (similar to Ammunition Dashboard)
$calibreData = !empty($stats['by_calibre']) && is_array($stats['by_calibre']) ? $stats['by_calibre'] : [];
$calibreLabels = [];
$calibreCounts = [];

if (!empty($calibreData)) {
    foreach ($calibreData as $calibre => $count) {
        $calibreLabels[] = $calibre;
        $calibreCounts[] = (int)$count;
    }
}
?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-content">
            <h1>
                <i class="fas fa-chart-pie"></i>
                Weapons Dashboard
            </h1>
            <p>Analytics and statistics for weapons inventory management</p>
        </div>
        <div class="header-actions">
            <a href="<?php echo BASE_URL; ?>/weapons" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to Weapons
            </a>
            <button class="btn btn-info" onclick="refreshDashboard()">
                <i class="fas fa-sync-alt"></i> Refresh
            </button>
        </div>
    </div>

    <!-- 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($stats['total']); ?></p>
                <?php if (($stats['new_this_month'] ?? 0) > 0): ?>
                <div class="stat-trend">
                    <span class="trend-up"><i class="fas fa-arrow-up"></i> +<?php echo number_format($stats['new_this_month']); ?> this month</span>
                </div>
                <?php endif; ?>
            </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($stats['issued']); ?></p>
                <div class="stat-trend">
                    <span class="trend-info"><?php echo round(($stats['issued'] / max($stats['total'], 1)) * 100); ?>% of total</span>
                </div>
            </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($stats['serviceable']); ?></p>
                <div class="stat-trend">
                    <span class="trend-up"><i class="fas fa-check"></i> Ready for use</span>
                </div>
            </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($stats['unserviceable']); ?></p>
                <div class="stat-trend">
                    <span class="trend-down"><i class="fas fa-exclamation"></i> Needs attention</span>
                </div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon repair">
                <i class="fas fa-tools"></i>
            </div>
            <div class="stat-details">
                <h4>In Repair</h4>
                <p class="stat-number"><?php echo number_format($stats['in_repair']); ?></p>
                <div class="stat-trend">
                    <span class="trend-warning"><i class="fas fa-clock"></i> Under maintenance</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Section -->
    <div class="dashboard-details">
        <div class="detail-section">
            <div class="section-header">
                <h3><i class="fas fa-chart-pie"></i> Weapons by Type</h3>
                <?php if (!empty($typeLabels)): ?>
                    <span class="badge"><?php echo count($typeLabels); ?> types</span>
                <?php endif; ?>
            </div>
            <div style="height: 300px; position: relative;">
                <canvas id="weaponTypeChart"></canvas>
            </div>
            <?php if (empty($typeLabels)): ?>
                <div class="empty-state-chart">
                    <p>No data available for chart</p>
                </div>
            <?php endif; ?>
        </div>

        <div class="detail-section">
            <div class="section-header">
                <h3><i class="fas fa-chart-bar"></i> Weapons by Calibre</h3>
                <?php if (!empty($calibreLabels)): ?>
                    <span class="badge"><?php echo count($calibreLabels); ?> calibres</span>
                <?php endif; ?>
            </div>
            <div style="height: 300px; position: relative;">
                <canvas id="weaponCalibreChart"></canvas>
            </div>
            <?php if (empty($calibreLabels)): ?>
                <div class="empty-state-chart">
                    <p>No data available for chart</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Additional Stats Row -->
    <div class="stats-row">
        <div class="stats-info-card">
            <div class="info-icon">
                <i class="fas fa-building"></i>
            </div>
            <div class="info-content">
                <h4>Units with Weapons</h4>
                <p class="info-value"><?php echo number_format($stats['units_count'] ?? 0); ?></p>
                <span class="info-label">Active units</span>
            </div>
        </div>
        <div class="stats-info-card">
            <div class="info-icon">
                <i class="fas fa-calendar-alt"></i>
            </div>
            <div class="info-content">
                <h4>Last Audit</h4>
                <p class="info-value"><?php echo $stats['last_audit'] ?? 'N/A'; ?></p>
                <span class="info-label">Last inventory check</span>
            </div>
        </div>
        <div class="stats-info-card">
            <div class="info-icon">
                <i class="fas fa-percent"></i>
            </div>
            <div class="info-content">
                <h4>Serviceability Rate</h4>
                <p class="info-value"><?php echo round(($stats['serviceable'] / max($stats['total'], 1)) * 100); ?>%</p>
                <span class="info-label">Weapons ready for use</span>
            </div>
        </div>
        <div class="stats-info-card">
            <div class="info-icon">
                <i class="fas fa-chart-line"></i>
            </div>
            <div class="info-content">
                <h4>Utilization Rate</h4>
                <p class="info-value"><?php echo round(($stats['issued'] / max($stats['total'], 1)) * 100); ?>%</p>
                <span class="info-label">Currently in use</span>
            </div>
        </div>
    </div>

    <!-- Recent Issues Section -->
    <div class="detail-section full-width">
        <div class="section-header">
            <h3><i class="fas fa-history"></i> Recent Issues & Assignments</h3>
            <?php if (!empty($recentIssues)): ?>
                <span class="badge badge-info"><?php echo count($recentIssues); ?> records</span>
            <?php endif; ?>
        </div>
        <div class="table-responsive">
            <?php if (empty($recentIssues)): ?>
                <div class="empty-state">
                    <i class="fas fa-history"></i>
                    <p>No recent issues found</p>
                </div>
            <?php else: ?>
            <table class="asset-table">
                <thead>
                    <tr>
                        <th>Weapon Details</th>
                        <th>Issue Information</th>
                        <th>Assigned Officer</th>
                        <th>Expected Return</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($recentIssues as $issue): ?>
                    <tr>
                        <td>
                            <div class="weapon-info">
                                <strong><?php echo htmlspecialchars($issue['make_model'] ?? $issue['weapon_name'] ?? 'N/A'); ?></strong>
                                <small><?php echo htmlspecialchars($issue['serial_number'] ?? 'N/A'); ?></small>
                            </div>
                        </td>
                        <td>
                            <div class="issue-info">
                                <span><i class="fas fa-calendar"></i> <?php echo date('d/m/Y', strtotime($issue['issue_date'])); ?></span>
                                <small><?php echo htmlspecialchars($issue['purpose'] ?? 'N/A'); ?></small>
                            </div>
                        </td>
                        <td>
                            <div class="officer-info">
                                <strong><?php echo htmlspecialchars($issue['officer_name'] ?? $issue['issued_to'] ?? 'N/A'); ?></strong>
                                <small><?php echo htmlspecialchars($issue['unit'] ?? 'N/A'); ?></small>
                            </div>
                        </td>
                        <td>
                            <?php if (!empty($issue['expected_return_date'])): ?>
                                <?php 
                                $returnDate = strtotime($issue['expected_return_date']);
                                $today = time();
                                $daysLeft = round(($returnDate - $today) / (60 * 60 * 24));
                                $statusClass = $daysLeft < 0 ? 'status-overdue' : ($daysLeft <= 7 ? 'status-warning' : 'status-active');
                                ?>
                                <div class="return-info">
                                    <span class="return-date <?php echo $statusClass; ?>">
                                        <?php echo date('d/m/Y', strtotime($issue['expected_return_date'])); ?>
                                    </span>
                                    <?php if ($daysLeft < 0): ?>
                                        <small class="overdue">Overdue by <?php echo abs($daysLeft); ?> days</small>
                                    <?php elseif ($daysLeft <= 7): ?>
                                        <small class="due-soon">Due in <?php echo $daysLeft; ?> days</small>
                                    <?php endif; ?>
                                </div>
                            <?php else: ?>
                                <span class="text-muted">Not specified</span>
                            <?php endif; ?>
                         </td>
                        <td>
                            <span class="status-badge status-issued">
                                <i class="fas fa-check-circle"></i> Issued
                            </span>
                         </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </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;
}

.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);
    transition: transform 0.2s, box-shadow 0.2s;
}

.stat-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px 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: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

.stat-icon.issued {
    background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%);
    color: white;
}

.stat-icon.serviceable {
    background: linear-gradient(135deg, #27ae60 0%, #219a52 100%);
    color: white;
}

.stat-icon.unserviceable {
    background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
    color: white;
}

.stat-icon.repair {
    background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
    color: white;
}

.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-trend {
    font-size: 0.75rem;
    margin-top: 5px;
}

.trend-up { color: #27ae60; }
.trend-down { color: #e74c3c; }
.trend-warning { color: #f39c12; }
.trend-info { color: #3498db; }

.dashboard-details {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    margin-bottom: 30px;
}

.detail-section {
    background: white;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.detail-section.full-width {
    grid-column: 1 / -1;
}

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

.section-header h3 {
    margin: 0;
    font-size: 1.2rem;
    color: var(--text-primary);
    display: flex;
    align-items: center;
    gap: 8px;
}

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

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

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

.stats-info-card {
    background: white;
    border-radius: 10px;
    padding: 15px;
    display: flex;
    align-items: center;
    gap: 15px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    transition: all 0.3s;
}

.stats-info-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.info-icon {
    width: 50px;
    height: 50px;
    border-radius: 10px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 1.3rem;
}

.info-content {
    flex: 1;
}

.info-content h4 {
    margin: 0 0 5px 0;
    font-size: 0.8rem;
    color: #7f8c8d;
    font-weight: 500;
}

.info-value {
    font-size: 1.5rem;
    font-weight: 700;
    margin: 0;
    color: #2c3e50;
    line-height: 1.2;
}

.info-label {
    font-size: 0.7rem;
    color: #95a5a6;
}

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

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

.btn-info:hover {
    background: #2980b9;
}

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

.btn-secondary:hover {
    background: #6c757d;
}

.weapon-info,
.issue-info,
.officer-info,
.return-info {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.weapon-info strong {
    font-size: 0.9rem;
    color: #2c3e50;
}

.weapon-info small,
.officer-info small {
    font-size: 0.7rem;
    color: #7f8c8d;
}

.issue-info span {
    font-size: 0.85rem;
    display: flex;
    align-items: center;
    gap: 5px;
}

.issue-info small {
    font-size: 0.7rem;
    color: #7f8c8d;
}

.return-date {
    font-size: 0.85rem;
    font-weight: 500;
    padding: 2px 8px;
    border-radius: 4px;
    display: inline-block;
}

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

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

.return-date.status-overdue {
    background: #f8d7da;
    color: #721c24;
}

.overdue,
.due-soon {
    font-size: 0.7rem;
}

.overdue { color: #e74c3c; }
.due-soon { color: #f39c12; }

.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 500;
}

.status-issued {
    background: #e3f2fd;
    color: #1976d2;
}

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

.empty-state-chart {
    text-align: center;
    padding: 20px;
    color: var(--text-secondary);
    font-style: italic;
}

.text-muted {
    color: #95a5a6;
}

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

@media (max-width: 1024px) {
    .dashboard-details {
        grid-template-columns: 1fr;
        gap: 20px;
    }
}

@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }
    
    .dashboard-details {
        grid-template-columns: 1fr;
    }
    
    .stats-row {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .section-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }
}

@media (max-width: 480px) {
    .stats-row {
        grid-template-columns: 1fr;
    }
}
</style>

<script>
function refreshDashboard() {
    location.reload();
}

document.addEventListener('DOMContentLoaded', function() {
    if (typeof Chart === 'undefined') {
        console.error('Chart.js not loaded');
        return;
    }
    
    // Weapons by Type Chart (Pie Chart)
    const typeCtx = document.getElementById('weaponTypeChart');
    if (typeCtx) {
        const labels = <?php echo json_encode($typeLabels); ?>;
        const data = <?php echo json_encode($typeCounts); ?>;
        
        if (labels.length > 0 && data.length > 0) {
            new Chart(typeCtx.getContext('2d'), {
                type: 'pie',
                data: {
                    labels: labels,
                    datasets: [{
                        data: data,
                        backgroundColor: [
                            '#27ae60', '#3498db', '#e74c3c', '#f39c12', 
                            '#9b59b6', '#1abc9c', '#e67e22', '#2c3e50',
                            '#95a5a6', '#34495e', '#16a085', '#27ae60',
                            '#2980b9', '#8e44ad', '#2c3e50', '#d35400'
                        ],
                        borderWidth: 1,
                        borderColor: '#ffffff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 15,
                                usePointStyle: true,
                                font: { size: 11 }
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.raw || 0;
                                    const total = context.dataset.data.reduce((acc, data) => acc + data, 0);
                                    const percentage = ((value * 100) / total).toFixed(1);
                                    return `${label}: ${value} weapon${value !== 1 ? 's' : ''} (${percentage}%)`;
                                }
                            }
                        }
                    }
                }
            });
        }
    }
    
    // Weapons by Calibre Chart (Bar Chart) - FIXED to match Ammunition Dashboard
    const calibreCtx = document.getElementById('weaponCalibreChart');
    if (calibreCtx) {
        const labels = <?php echo json_encode($calibreLabels); ?>;
        const data = <?php echo json_encode($calibreCounts); ?>;
        
        if (labels.length > 0 && data.length > 0) {
            new Chart(calibreCtx.getContext('2d'), {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Number of Weapons',
                        data: data,
                        backgroundColor: '#27ae60',
                        borderRadius: 5,
                        barPercentage: 0.7
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const value = context.raw || 0;
                                    return `Weapons: ${value}`;
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: 'Number of Weapons',
                                font: { size: 12 }
                            },
                            ticks: {
                                stepSize: 1,
                                precision: 0
                            }
                        },
                        x: {
                            title: {
                                display: true,
                                text: 'Calibre',
                                font: { size: 12 }
                            },
                            ticks: {
                                maxRotation: 45,
                                minRotation: 45
                            }
                        }
                    }
                }
            });
        } else {
            calibreCtx.style.display = 'none';
            if (calibreCtx.parentNode && !calibreCtx.parentNode.querySelector('.empty-state-chart')) {
                calibreCtx.parentNode.innerHTML += '<div class="empty-state-chart">No data available for chart</div>';
            }
        }
    }
});
</script>

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