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

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'officer') {
  header("Location: ../auth/login.php");
  exit;
}

$officer_id = $_SESSION['user_id'];
$title = trim($_POST['title'] ?? '');
$description = trim($_POST['description'] ?? '');
$site_id = intval($_POST['site_id'] ?? 0);
$incident_date = $_POST['incident_date'] ?? date('Y-m-d');
$incident_time = $_POST['incident_time'] ?? date('H:i:s');

$photo_path = '';
$video_path = '';
$upload_dir = '../uploads/incidents/';
if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);

// Upload photo
if (!empty($_FILES['photo']['name'])) {
  $ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
  $photo_path = 'incidents/photos/' . time() . '_photo.' . $ext;
  move_uploaded_file($_FILES['photo']['tmp_name'], $upload_dir . basename($photo_path));
}

// Upload video
if (!empty($_FILES['video']['name'])) {
  $ext = pathinfo($_FILES['video']['name'], PATHINFO_EXTENSION);
  $video_path = 'incidents/videos/' . time() . '_video.' . $ext;
  move_uploaded_file($_FILES['video']['tmp_name'], $upload_dir . basename($video_path));
}

// Auto generate report number
$report_no = 'IR-' . strtoupper(uniqid());

// Insert record
$stmt = $pdo->prepare("
  INSERT INTO incident_reports (officer_id, site_id, title, description, incident_date, incident_time, photo, video, report_number, submitted_by_role, status, created_at)
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'officer', 'pending', NOW())
");
$stmt->execute([$officer_id, $site_id, $title, $description, $incident_date, $incident_time, $photo_path, $video_path, $report_no]);

// Optional: notify admin
$pdo->prepare("INSERT INTO notifications (message, type, link, created_at)
VALUES (?, 'incident', 'admin/incident_reports.php', NOW())")
->execute(["New incident report submitted: $title"]);

header("Location: report_incident.php?success=1");
exit;
