<?php
session_start();
require_once '../includes/config.php';

// Ensure the user is logged in and has the 'controller' role
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'controller') {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

try {
    // Prepare and execute the query to fetch the latest 10 incidents
    $stmt = $pdo->prepare("
        SELECT ir.id, ir.title, ir.description, 
               DATE_FORMAT(ir.incident_date, '%Y-%m-%d') AS incident_date,
               DATE_FORMAT(ir.incident_time, '%H:%i:%s') AS incident_time,
               s.site_name, u.username AS officer_name
        FROM incident_report ir
        JOIN sites s ON ir.site_id = s.id
        JOIN users u ON ir.officer_id = u.id
        ORDER BY ir.reported_at DESC
        LIMIT 10
    ");
    $stmt->execute();
    $incidents = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Handle empty results
    if (empty($incidents)) {
        header('Content-Type: application/json');
        echo json_encode([]);
        exit;
    }

    // Return the incidents as JSON
    header('Content-Type: application/json');
    echo json_encode($incidents);

} catch (PDOException $e) {
    // Log the error for debugging (optional)
    error_log("Database error: " . $e->getMessage());

    // Respond with a generic error message
    http_response_code(500);
    echo json_encode(['error' => 'An error occurred while fetching incidents.']);
}
