<?php
header('Content-Type: application/json');
require_once '../includes/config.php';

$severityFilter = $_GET['severity'] ?? null;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$limit = 5;
$offset = ($page - 1) * $limit;

$params = [];
$where = '';
if ($severityFilter) {
    $where = "WHERE severity = ?";
    $params[] = $severityFilter;
}

// Get filtered incidents
$sql = "SELECT site, description, severity, reported_at FROM incident_reports 
        $where ORDER BY reported_at DESC LIMIT $limit OFFSET $offset";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$incidents = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Format badge
function format_badge($severity) {
    $class = [
        'critical' => 'danger',
        'warning'  => 'warning',
        'info'     => 'info',
    ][$severity] ?? 'secondary';

    return "<span class='badge bg-{$class} text-uppercase'>{$severity}</span>";
}

// Build HTML list
$html = "<ul class='list-group'>";
foreach ($incidents as $row) {
    $description = htmlspecialchars($row['description']);
    $site = htmlspecialchars($row['site']);
    $severity = htmlspecialchars($row['severity']);
    $time = date('d M Y, H:i', strtotime($row['reported_at']));
    $html .= "<li class='list-group-item d-flex justify-content-between align-items-center'>
        <div>
          <strong>{$site}</strong>: {$description}
          <br><small class='text-muted'>{$time}</small>
        </div>" . format_badge($severity) . "</li>";
}
$html .= "</ul>";

// Count for widgets
$onDuty = $pdo->query("SELECT COUNT(*) FROM attendance WHERE DATE(date) = CURDATE()")->fetchColumn();
$late = $pdo->query("SELECT COUNT(*) FROM attendance WHERE time_in > '08:00:00' AND DATE(date) = CURDATE()")->fetchColumn();
$missed = $pdo->query("SELECT COUNT(*) FROM users WHERE role = 'officer'")->fetchColumn() - $onDuty;
$open = $pdo->query("SELECT COUNT(*) FROM incident_reports WHERE status = 'open'")->fetchColumn();

echo json_encode([
    'html' => $html,
    'stats' => [
        'onDuty' => (int)$onDuty,
        'late' => (int)$late,
        'missed' => max(0, $missed),
        'open' => (int)$open
    ]
]);
