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

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

$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();
?>

<!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">

  <!-- AdminLTE & Bootstrap -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
   <style>
    #map {
      height: 90vh;
      width: 100%;
    }
  </style>
</head>
<body>

<?php include '../includes/topbar.php'; ?>
<?php include '../includes/sidebar.php'; ?>

<div class="content-wrapper p-4">

  <div class="container-fluid">

    <div class="content-header">
      <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3">
          <h4 class="mb-0">📡 Command Center Monitoring</h4>
        </div>
        <div class="row">
          <div class="col-md-3"><div class="small-box bg-success"><div class="inner"><h4 id="onDuty">0</h4><p>On Duty</p></div></div></div>
          <div class="col-md-3"><div class="small-box bg-danger"><div class="inner"><h4 id="late">0</h4><p>Late Check-ins</p></div></div></div>
          <div class="col-md-3"><div class="small-box bg-warning"><div class="inner"><h4 id="missed">0</h4><p>Missed Patrols</p></div></div></div>
          <div class="col-md-3"><div class="small-box bg-info"><div class="inner"><h4 id="incidents">0</h4><p>Open Incidents</p></div></div></div>
        </div>
      </div>
    </div>

    <div class="content-header">
      <div class="content">
        <div class="card">
          <div class="card-header bg-primary text-white">
          <h5 class="card-title">📋 All Incident Reports</h5>
        </div>
          <div class="card-body table-responsive">
            <table id="incidentTable" class="table table-bordered table-striped">
              <thead class="table-dark">
                <tr>
                  <th>Report #</th>
                  <th>Title</th>
                  <th>Submitted By</th>
                  <th>Site</th>
                  <th>Status</th>
                  <th>Date</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($incidents as $index => $incident): ?>
                  <tr>
                    <td><?= $incident['report_number'] ?></td>
                    <td><?= htmlspecialchars($incident['title']) ?></td>
                    <td><?= $incident['submitted_by_role'] === 'officer' ? $incident['officer_name'] : $incident['controller_name'] ?></td>
                    <td><?= htmlspecialchars($incident['site_name']) ?></td>
                    <td><?= ucfirst($incident['status']) ?></td>
                    <td><?= $incident['reported_at'] ?></td>
                    <td>
                      <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#viewIncidentModal<?= $index ?>">View</button>
                      <?php if ($incident['status'] === 'pending'): ?>
                        <button class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#editIncidentModal<?= $index ?>">Edit</button>
                      <?php endif; ?>
                    </td>
                  </tr>

                  <!-- View Modal -->
                  <div class="modal fade" id="viewIncidentModal<?= $index ?>" tabindex="-1" aria-labelledby="viewIncidentLabel<?= $index ?>" aria-hidden="true">
                    <div class="modal-dialog modal-lg modal-dialog-scrollable">
                      <div class="modal-content">
                        <div class="modal-header bg-dark text-white">
                          <h5 class="modal-title" id="viewIncidentLabel<?= $index ?>">Incident Details</h5>
                          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                          <p><strong>Report #:</strong> <?= $incident['report_number'] ?></p>
                          <p><strong>Title:</strong> <?= htmlspecialchars($incident['title']) ?></p>
                          <p><strong>Description:</strong><br><?= nl2br(htmlspecialchars($incident['description'])) ?></p>
                          <p><strong>Submitted By:</strong> <?= $incident['submitted_by_role'] === 'officer' ? $incident['officer_name'] : $incident['controller_name'] ?></p>
                          <p><strong>Site:</strong> <?= htmlspecialchars($incident['site_name']) ?></p>
                          <p><strong>Status:</strong> <?= ucfirst($incident['status']) ?></p>
                          <p><strong>Reported At:</strong> <?= $incident['reported_at'] ?></p>

                          <?php if (!empty($incident['photo'])): ?>
                            <div class="mb-3">
                              <strong>Photo(s):</strong>
                              <div class="row">
                                <?php foreach (json_decode($incident['photo']) as $photo): ?>
                                  <div class="col-md-4 mb-2">
                                    <a href="../uploads/<?= $photo ?>" target="_blank">
                                      <img src="../uploads/<?= $photo ?>" class="img-fluid rounded border" />
                                    </a>
                                  </div>
                                <?php endforeach; ?>
                              </div>
                            </div>
                          <?php endif; ?>

                          <?php if (!empty($incident['video'])): ?>
                            <div class="mb-3">
                              <strong>Video:</strong><br>
                              <video controls class="w-100 border rounded" style="max-height: 300px;">
                                <source src="../uploads/<?= $incident['video'] ?>" type="video/mp4">
                              </video>
                            </div>
                          <?php endif; ?>
                        </div>
                        <div class="modal-footer">
                          <form method="POST" action="review_incident.php">
                            <input type="hidden" name="incident_id" value="<?= $incident['id'] ?>">
                            <button name="action" value="approve" class="btn btn-success" <?= $incident['status'] !== 'pending' ? 'disabled' : '' ?>>Approve</button>
                            <button name="action" value="reject" class="btn btn-danger" <?= $incident['status'] !== 'pending' ? 'disabled' : '' ?>>Reject</button>
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                          </form>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- Edit Modal -->
                  <div class="modal fade" id="editIncidentModal<?= $index ?>" tabindex="-1" aria-labelledby="editIncidentLabel<?= $index ?>" aria-hidden="true">
                    <div class="modal-dialog modal-lg">
                      <div class="modal-content">
                        <form method="POST" action="update_incident.php" enctype="multipart/form-data">
                          <div class="modal-header bg-warning">
                            <h5 class="modal-title">\u270f\ufe0f Edit Incident Report</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                          </div>
                          <div class="modal-body">
                            <input type="hidden" name="incident_id" value="<?= $incident['id'] ?>">

                            <div class="mb-3">
                              <label class="form-label">Title</label>
                              <input type="text" name="title" value="<?= htmlspecialchars($incident['title']) ?>" class="form-control" required>
                            </div>

                            <div class="mb-3">
                              <label class="form-label">Description</label>
                              <textarea name="description" class="form-control" rows="4"><?= htmlspecialchars($incident['description']) ?></textarea>
                            </div>

                            <div class="mb-3">
                              <label class="form-label">Status</label>
                              <select name="status" class="form-select">
                                <option value="pending" <?= $incident['status'] === 'pending' ? 'selected' : '' ?>>Pending</option>
                                <option value="approved" <?= $incident['status'] === 'approved' ? 'selected' : '' ?>>Approved</option>
                                <option value="rejected" <?= $incident['status'] === 'rejected' ? 'selected' : '' ?>>Rejected</option>
                              </select>
                            </div>

                            <?php if (!empty($incident['photo'])): ?>
                              <div class="mb-3">
                                <label class="form-label">Current Photo(s):</label>
                                <div class="row">
                                  <?php foreach (json_decode($incident['photo']) as $i => $p): ?>
                                    <div class="col-4">
                                      <div class="border p-2 rounded mb-2 text-center">
                                        <img src="../uploads/<?= $p ?>" class="img-fluid mb-1" style="max-height: 100px;">
                                        <div class="form-check">
                                          <input class="form-check-input" type="checkbox" name="delete_photos[]" value="<?= $p ?>" id="delphoto<?= $i ?>">
                                          <label class="form-check-label small" for="delphoto<?= $i ?>">Remove</label>
                                        </div>
                                      </div>
                                    </div>
                                  <?php endforeach; ?>
                                </div>
                              </div>
                            <?php endif; ?>

                            <div class="mb-3">
                              <label class="form-label">Add Photo(s)</label>
                              <input type="file" name="photos[]" class="form-control" multiple accept="image/*">
                            </div>

                            <?php if (!empty($incident['video'])): ?>
                              <div class="mb-3">
                                <label class="form-label">Current Video</label><br>
                                <video src="../uploads/<?= $incident['video'] ?>" controls class="w-100 border rounded mb-2" style="max-height: 200px;"></video>
                              </div>
                            <?php endif; ?>

                            <div class="mb-3">
                              <label class="form-label">Replace Video</label>
                              <input type="file" name="video" class="form-control" accept="video/*">
                            </div>
                          </div>
                          <div class="modal-footer">
                            <button type="submit" class="btn btn-success">Save</button>
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                          </div>
                        </form>
                      </div>
                    </div>
                  </div>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
    <div class="card mb-4">
          <h4 style="text-align:center;">🗺️ Singapore Map (with GPS Location Marker)</h4>
  <div id="map"></div>

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

      // Example: Add a static GPS marker (can be loaded dynamically from DB or JS array)
      const sampleLocations = [
        { lat: 1.3000, lng: 103.8000, title: "Checkpoint A" },
        { lat: 1.3400, lng: 103.9600, title: "Checkpoint B" }
      ];

      sampleLocations.forEach(loc => {
        new google.maps.Marker({
          position: { lat: loc.lat, lng: loc.lng },
          map,
          title: loc.title
        });
      });
    }
  </script>

  <!-- Replace YOUR_API_KEY with a valid Google Maps JavaScript API key -->
  <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
    </div>
  </div>
</div>

<?php if (isset($_SESSION['toast'])): ?>
  <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 9999">
    <div class="toast align-items-center text-bg-success show" role="alert">
      <div class="d-flex">
        <div class="toast-body"><?= $_SESSION['toast']['message'] ?></div>
        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
      </div>
    </div>
  </div>
  <?php unset($_SESSION['toast']); ?>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.4/dist/jquery.min.js"></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).ready(function () {
    $('#incidentTable').DataTable();
    document.querySelectorAll('.toast').forEach(t => new bootstrap.Toast(t).show());
  });
</script>
</body>
</html>
