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

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

// Handle status updates
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'], $_POST['incident_id'])) {
  $incident_id = (int)$_POST['incident_id'];
  $action = $_POST['action'];

  if ($action === 'resolved') {
    $pdo->prepare("UPDATE incident_reports SET status = 'resolved' WHERE id = ?")->execute([$incident_id]);
  } elseif ($action === 'reject') {
    $pdo->prepare("UPDATE incident_reports SET status = 'rejected' WHERE id = ?")->execute([$incident_id]);
  } elseif ($action === 'delete') {
    $pdo->prepare("DELETE FROM incident_reports WHERE id = ?")->execute([$incident_id]);
  }

  header("Location: incident_reports.php");
  exit;
}

// Fetch reports
function getIncidents($pdo, $role) {
  $stmt = $pdo->prepare("
  SELECT ir.*, u.username, s.site_name 
  FROM incident_reports ir
  JOIN users u ON ir.officer_id = u.id
  JOIN sites s ON ir.site_id = s.id
  WHERE ir.submitted_by_role = :role OR (ir.submitted_by_role IS NULL AND :role = 'officer')
  ORDER BY ir.id DESC
");
$stmt->execute(['role' => $role]);
  return $stmt->fetchAll();
}

$officerReports = getIncidents($pdo, 'officer');
$controllerReports = getIncidents($pdo, 'controller');
?>

<!DOCTYPE html>
<html>
<head>
  <title>Incident Reports</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" rel="stylesheet">
  <link href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.dataTables.min.css" rel="stylesheet">
  <link rel="stylesheet" href="../assets/css/admin_dashboard.css">
</head>
<body>

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

<div class="main-content" id="mainContent">

<div class="container mt-4">
  <h4>🚨 Incident Reports</h4>

  <ul class="nav nav-tabs" id="incidentTabs" role="tablist">
    <li class="nav-item">
      <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#officerTab">🚔 Officer Incidents</button>
    </li>
    <li class="nav-item">
      <button class="nav-link" data-bs-toggle="tab" data-bs-target="#controllerTab">📋 Controller Incidents</button>
    </li>
  </ul>

  <div class="tab-content mt-3">
    <div class="tab-pane fade show active" id="officerTab">
      <?php renderTable($officerReports, 'officer'); ?>
    </div>
    <div class="tab-pane fade" id="controllerTab">
      <?php renderTable($controllerReports, 'controller'); ?>
    </div>
  </div>
</div>

<?php
function renderTable($data, $id) {
  echo "<div class='table-responsive'>";
  echo "<table id='table_$id' class='table table-bordered table-striped'>";
  echo "<thead class='table-dark'>
    <tr>
      <th>#</th>
      <th>Title</th>
      <th>User</th>
      <th>Site</th>
      <th>Description</th>
      <th>Photo</th>
      <th>Video</th>
      <th>Status</th>
      <th>Date</th>
      <th>Action</th>
    </tr>
  </thead><tbody>";

  foreach ($data as $i => $r) {
    $statusText = $r['status'];
switch ($statusText) {
  case 'resolved':
    $status = "<span class='badge bg-success'>Resolved</span>";
    break;
  case 'rejected':
    $status = "<span class='badge bg-danger'>Rejected</span>";
    break;
  default:
    $status = "<span class='badge bg-secondary'>Pending</span>";
}

    echo "<tr>
      <td>" . ($i + 1) . "</td>
      <td>" . htmlspecialchars($r['title']) . "</td>
      <td>" . htmlspecialchars($r['username']) . "</td>
      <td>" . htmlspecialchars($r['site_name']) . "</td>
      <td>" . nl2br(htmlspecialchars($r['description'])) . "</td>
      <td>" . (!empty($r['photo']) ? "<a href='../uploads/{$r['photo']}' target='_blank'>📷</a>" : '-') . "</td>
      <td>" . (!empty($r['video']) ? "<a href='../uploads/{$r['video']}' target='_blank'>🎥</a>" : '-') . "</td>
      <td>$status</td>
      <td>" . (!empty($r['created_at']) ? date("d M Y H:i", strtotime($r['created_at'])) : '-') . "</td>
      <td>
        <form method='post' style='display:inline;'>
          <input type='hidden' name='incident_id' value='{$r['id']}'>
          <button name='action' value='resolved' class='btn btn-sm btn-success'>✅</button>
          <button name='action' value='reject' class='btn btn-sm btn-warning'>❌</button>
          <button name='action' value='delete' class='btn btn-sm btn-danger' onclick=\"return confirm('Delete this?')\">🗑</button>
        </form>
      </td>
    </tr>";
  }

  echo "</tbody></table></div>";
}
?>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.print.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>


<script>
  $(document).ready(function () {
    ['officer', 'controller'].forEach(function (id) {
      $('#table_' + id).DataTable({
        dom: 'Bfrtip',
        buttons: ['excelHtml5', 'print']
      });
    });
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
