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

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

// Fetch incident data with joins
$query = $pdo->query("
  SELECT ir.*, u.username, s.site_name 
  FROM incident_reports ir 
  LEFT JOIN users u ON ir.user_id = u.id 
  LEFT JOIN sites s ON ir.site_id = s.id 
  ORDER BY ir.created_at DESC
");

$data = $query->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Incident Reports | Admin Dashboard</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
  <style>
    body { font-size: 0.9rem; }
    .content-wrapper { background-color: #f4f6f9; }
  </style>
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

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

  <div class="content-wrapper">
    <section class="content-header">
      <div class="container-fluid">
        <h4 class="mb-0">📋 Security Incident Reports</h4>
      </div>
    </section>

    <section class="content">
      <div class="container-fluid">
        <div class="mb-3 d-flex justify-content-between align-items-center">
          <input type="text" id="searchBox" class="form-control form-control-sm" placeholder="🔍 Search incidents..." style="width: 300px;">
          <div>
            <button onclick="window.print()" class="btn btn-sm btn-outline-primary"><i class="fas fa-print"></i> Print</button>
            <button onclick="exportTableToExcel('userTable')" class="btn btn-sm btn-outline-success"><i class="fas fa-file-excel"></i> Export Excel</button>
          </div>
        </div>

        <table id="userTable" class="table table-bordered table-striped text-sm">
          <thead class="table-dark">
            <tr>
              <th>#</th>
              <th>Subject</th>
              <th>User</th>
              <th>Role</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>
          <?php if (!empty($data) && is_array($data)): foreach ($data as $i => $r): ?>
            <?php
              $statusText = $r['status'];
              switch ($statusText) {
                case 'approved':
                  $status = "<span class='badge bg-success'>Approved</span>";
                  break;
                case 'rejected':
                  $status = "<span class='badge bg-danger'>Rejected</span>";
                  break;
                default:
                  $status = "<span class='badge bg-warning text-dark'>Pending</span>";
              }

              $photos = json_decode($r['photo'], true) ?: [];
              $videos = json_decode($r['video'], true) ?: [];
            ?>
            <tr>
              <td><?= $i + 1 ?></td>
              <td><?= htmlspecialchars($r['subject']) ?></td>
              <td><?= htmlspecialchars($r['username']) ?></td>
              <td><?= htmlspecialchars($r['submitted_by_role']) ?></td>
              <td><?= htmlspecialchars($r['site_name'] ?? '-') ?></td>
              <td><?= nl2br(htmlspecialchars($r['description'])) ?></td>
              <td>
                <?php foreach ($photos as $photo): ?>
                  <img src="../uploads/incidents/<?= htmlspecialchars($photo) ?>" width="60" class="me-1 mb-1">
                <?php endforeach; ?>
                <?= empty($photos) ? '—' : '' ?>
              </td>
              <td>
                <?php foreach ($videos as $video): ?>
                  <video src="../uploads/incidents/<?= htmlspecialchars($video) ?>" width="100" controls class="mb-1"></video>
                <?php endforeach; ?>
                <?= empty($videos) ? '—' : '' ?>
              </td>
              <td><?= $status ?></td>
              <td><?= date('Y-m-d H:i', strtotime($r['created_at'])) ?></td>
              <td>
                <a href="incident_view.php?id=<?= $r['id'] ?>" class="btn btn-sm btn-info"><i class="fas fa-eye"></i></a>
                <a href="incident_edit.php?id=<?= $r['id'] ?>" class="btn btn-sm btn-warning"><i class="fas fa-edit"></i></a>
                <a href="incident_delete.php?id=<?= $r['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete this incident?');"><i class="fas fa-trash-alt"></i></a>
              </td>
            </tr>
          <?php endforeach; else: ?>
            <tr><td colspan="11" class="text-center text-muted">No incident reports found.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </section>
  </div>

  <?php include '../includes/footer.php'; ?>
</div>

<script src="https://code.jquery.com/jquery-3.6.4.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.jsdelivr.net/npm/admin-lte@3.2/dist/js/adminlte.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script>
  $(document).ready(function () {
    $('#userTable').DataTable();
  });

  function exportTableToExcel(tableID, filename = '') {
    let downloadLink;
    const dataType = 'application/vnd.ms-excel';
    const tableSelect = document.getElementById(tableID);
    const tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
    filename = filename ? filename + '.xls' : 'incident_reports.xls';
    downloadLink = document.createElement("a");
    document.body.appendChild(downloadLink);
    if (navigator.msSaveOrOpenBlob) {
      const blob = new Blob(['\ufeff', tableHTML], { type: dataType });
      navigator.msSaveOrOpenBlob(blob, filename);
    } else {
      downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
      downloadLink.download = filename;
      downloadLink.click();
    }
  }
</script>
</body>
</html>
