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

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

// Fetch incidents
$stmt = $pdo->query("
  SELECT 
    i.id, i.report_number, i.title, i.description, i.status,
    i.created_at, i.reported_at, i.photo, i.video,
    s.site_name, i.submitted_by_role,
    u.username AS officer_name,
    c.username AS controller_name
  FROM incident_reports i
  LEFT JOIN sites s ON i.site_id = s.id
  LEFT JOIN users u ON i.officer_id = u.id
  LEFT JOIN controllers c ON i.controller_id = c.id
  ORDER BY i.created_at DESC
");
$incidents = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch GPS data
$existing = $pdo->query("SELECT title, latitude, longitude FROM gps_locations")->fetchAll(PDO::FETCH_ASSOC);
$points = $pdo->query("SELECT title, latitude, longitude, created_at FROM gps_locations ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Command Center Monitoring</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
  <style>
    #map { height: 60vh; width: 100%; margin-bottom: 20px; }
    .container { padding-top: 20px; }
    th, td { text-align: center; }
  </style>
</head>
<body>

<div class="container">
  <h3 class="mb-4">📡 Command Center Monitoring</h3>

  <!-- Incident Table -->
  <div class="card mb-4">
    <div class="card-header bg-primary text-white">📋 Incident Reports</div>
    <div class="card-body table-responsive">
      <table id="incidentTable" class="table table-bordered table-hover">
        <thead class="table-dark">
          <tr>
            <th>Report #</th><th>Title</th><th>By</th><th>Site</th><th>Status</th><th>Date</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($incidents as $i): ?>
          <tr>
            <td><?= htmlspecialchars($i['report_number']) ?></td>
            <td><?= htmlspecialchars($i['title']) ?></td>
            <td><?= $i['submitted_by_role'] === 'officer' ? $i['officer_name'] : $i['controller_name'] ?></td>
            <td><?= htmlspecialchars($i['site_name']) ?></td>
            <td><?= ucfirst($i['status']) ?></td>
            <td><?= $i['reported_at'] ?></td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

  <!-- Map + GPS Table -->
  <div class="card mb-4">
    <div class="card-header bg-success text-white">🗺️ Map & GPS Locations</div>
    <div class="card-body">
      <div id="map"></div>

      <h5 class="mt-4">📌 Saved GPS Points</h5>
      <table class="table table-bordered">
        <thead class="table-dark"><tr><th>#</th><th>Title</th><th>Lat</th><th>Lng</th><th>Timestamp</th></tr></thead>
        <tbody>
        <?php if (is_array($points)): ?>
          <?php foreach ($points as $index => $row): ?>
            <tr>
              <td><?= $index + 1 ?></td>
              <td><?= htmlspecialchars($row['title']) ?></td>
              <td><?= $row['latitude'] ?></td>
              <td><?= $row['longitude'] ?></td>
              <td><?= $row['created_at'] ?></td>
            </tr>
          <?php endforeach; ?>
        <?php else: ?>
          <tr><td colspan="5">No GPS data found.</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Google Map Script -->
<script>
  let map;
  function initMap() {
    map = new google.maps.Map(document.getElementById("map"), {
      center: { lat: 1.3521, lng: 103.8198 },
      zoom: 12,
    });

    const markers = <?= json_encode($existing) ?>;
    markers.forEach(m => {
      new google.maps.Marker({
        position: { lat: parseFloat(m.latitude), lng: parseFloat(m.longitude) },
        map,
        title: m.title
      });
    });

    map.addListener("click", function(event) {
      const lat = event.latLng.lat();
      const lng = event.latLng.lng();
      const title = prompt("Enter title for this location:");
      if (title) {
        new google.maps.Marker({
          position: { lat, lng },
          map,
          title: title
        });

        fetch("save_gps_point.php", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ title: title, latitude: lat, longitude: lng })
        })
        .then(res => res.json())
        .then(data => {
          if (data.success) {
            alert("✅ Location saved. Reloading...");
            location.reload();
          } else {
            alert("❌ Error: " + data.error);
          }
        })
        .catch(err => alert("❌ Network error: " + err));
      }
    });
  }
</script>

<!-- Replace with your actual API key -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script>
  document.addEventListener("DOMContentLoaded", () => {
    new DataTable('#incidentTable');
  });
</script>
</body>
</html>
