<?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'];
$username = $_SESSION['username'] ?? 'Officer';
$site_id = $_POST['site_id'] ?? $_SESSION['site_id'] ?? null;

$sites = $pdo->query("SELECT id, site_name FROM sites ORDER BY site_name")->fetchAll();

// After inserting the incident report
$incident_id = $pdo->lastInsertId();

// Define the notification message
$message = "New incident reported at Site ID: $site_id by Officer ID: $officer_id.";

// Fetch all controller user IDs
$stmt = $pdo->query("SELECT id FROM users WHERE role = 'controller'");
$controllers = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Insert a notification for each controller
$insert_stmt = $pdo->prepare("INSERT INTO notifications (user_id, message) VALUES (?, ?)");
foreach ($controllers as $controller) {
    $insert_stmt->execute([$controller['id'], $message]);
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Submit Incident Report</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
  <style>
    body { background-color: #f5f9fc; font-family: 'Segoe UI', sans-serif; }
    .container { max-width: 700px; }
  </style>
</head>
<body>

<div class="container py-4">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h4 class="text-danger mb-4">🚨 Submit Incident Report</h4>
    <a href="dashboard.php" class="btn btn-outline-secondary btn-sm">← Back to Dashboard</a>
  </div>

  <form method="POST" action="submit_incident.php" enctype="multipart/form-data">
    <div class="mb-3">
      <label class="form-label">Title</label>
      <input type="text" name="title" class="form-control" required>
    </div>

    <div class="mb-3">
      <label class="form-label">Site</label>
      <select name="site_id" class="form-select" required>
        <option value="">-- Select Site --</option>
        <?php foreach ($sites as $site): ?>
          <option value="<?= $site['id'] ?>"><?= htmlspecialchars($site['site_name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div class="mb-3">
      <label class="form-label">Description</label>
      <textarea name="description" class="form-control" rows="4" required></textarea>
    </div>

    <div class="mb-3">
      <label class="form-label">Photo (optional)</label>
      <input type="file" name="photo" class="form-control" accept="image/*">
    </div>

    <div class="mb-3">
      <label class="form-label">Video (optional)</label>
      <input type="file" name="video" class="form-control" accept="video/*">
    </div>

    <button class="btn btn-danger w-100">Submit Incident</button>
  </form>
</div>

</body>
</html>
