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

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'officer') {
    $_SESSION['toast'] = ['type' => 'danger', 'message' => 'Unauthorized access.'];
    header("Location: ../auth/login.php");
    exit;
}

$officerId = $_SESSION['user_id'];
$submitted_by_role = 'officer';

// Auto-generate report number
$report_number = 'IR' . date('YmdHis') . rand(100, 999);

// Collect POST data
$incident_date = $_POST['incident_date'] ?? '';
$incident_time = $_POST['incident_time'] ?? '';
$informant_name = $_POST['informant_name'] ?? '';
$contact_no = $_POST['contact_no'] ?? '';
$subject = $_POST['subject'] ?? '';
$recording_officer = $_POST['recording_officer'] ?? '';
$description = $_POST['description'] ?? '';
$site_id = $_POST['site_id'] ?? null;

// File upload directories
$photoDir = '../uploads/incidents/photos/';
$videoDir = '../uploads/incidents/videos/';
if (!is_dir($photoDir)) mkdir($photoDir, 0777, true);
if (!is_dir($videoDir)) mkdir($videoDir, 0777, true);

$uploadedPhotos = [];
$uploadedVideos = [];

// Upload photos
if (!empty($_FILES['photos']['name'][0])) {
    foreach ($_FILES['photos']['name'] as $key => $name) {
        $tmp = $_FILES['photos']['tmp_name'][$key];
        $filename = time() . '_' . basename($name);
        if (move_uploaded_file($tmp, $photoDir . $filename)) {
            $uploadedPhotos[] = $filename;
        }
    }
}

// Upload videos
if (!empty($_FILES['videos']['name'][0])) {
    foreach ($_FILES['videos']['name'] as $key => $name) {
        $tmp = $_FILES['videos']['tmp_name'][$key];
        $filename = time() . '_' . basename($name);
        if (move_uploaded_file($tmp, $videoDir . $filename)) {
            $uploadedVideos[] = $filename;
        }
    }
}

try {
    $stmt = $pdo->prepare("INSERT INTO incident_reports (
        officer_id, controller_id, submitted_by_role, report_number, 
        incident_date, incident_time, informant_name, contact_no, subject, 
        recording_officer, description, photo, video, site_id, reported_at, status
    ) VALUES (
        :officer_id, NULL, :submitted_by_role, :report_number, 
        :incident_date, :incident_time, :informant_name, :contact_no, :subject, 
        :recording_officer, :description, :photo, :video, :site_id, NOW(), 'pending'
    )");

    $stmt->execute([
        ':officer_id' => $officerId,
        ':submitted_by_role' => $submitted_by_role,
        ':report_number' => $report_number,
        ':incident_date' => $incident_date,
        ':incident_time' => $incident_time,
        ':informant_name' => $informant_name,
        ':contact_no' => $contact_no,
        ':subject' => $subject,
        ':recording_officer' => $recording_officer,
        ':description' => $description,
        ':photo' => json_encode($uploadedPhotos),
        ':video' => json_encode($uploadedVideos),
        ':site_id' => $site_id,
    ]);

    // Notify controllers
    $message = "New incident reported at Site ID: $site_id by Officer ID: $officerId.";
    $controllers = $pdo->query("SELECT id FROM users WHERE role = 'controller'")->fetchAll(PDO::FETCH_ASSOC);
    $notifyStmt = $pdo->prepare("INSERT INTO notifications (user_id, message) VALUES (?, ?)");
    foreach ($controllers as $controller) {
        $notifyStmt->execute([$controller['id'], $message]);
    }

    $_SESSION['toast'] = ['type' => 'success', 'message' => 'Incident submitted successfully.'];
    header("Location: view_incidents.php");
    exit;

} catch (PDOException $e) {
    $_SESSION['toast'] = ['type' => 'danger', 'message' => 'Database error: ' . $e->getMessage()];
    header("Location: report_incident.php");
    exit;
}
?>
