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

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

$incidents = $pdo->query("SELECT id, title, description, status, created_at FROM incident_reports ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>All Incidents | CFS System OS</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- AdminLTE + DataTables -->
  <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/@fortawesome/fontawesome-free@6.5.0/css/all.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://cdn.datatables.net/1.13.5/css/dataTables.bootstrap5.min.css"/>
  <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap5.min.css"/>
</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">
    <div class="content-header">
      <div class="container-fluid">
        <h4>📄 All Incident Reports</h4>
      </div>
    </div>

    <div class="content">
      <div class="container-fluid">
        <div class="card shadow-sm">
          <div class="card-body">
            <table id="incidentTable" class="table table-striped table-bordered">
              <thead class="table-light">
                <tr>
                  <th>Title</th>
                  <th>Status</th>
                  <th>Date</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody>
              <?php foreach ($incidents as $incident): ?>
                <?php
                  $status = $incident['status'];
                  if ($status === 'approved') {
                      $color = 'success';
                  } elseif ($status === 'rejected') {
                      $color = 'danger';
                  } else {
                      $color = 'secondary';
                  }
                ?>
                <tr>
                  <td><?= htmlspecialchars($incident['title']) ?></td>
                  <td><span class="badge bg-<?= $color ?>"><?= ucfirst($status) ?></span></td>
                  <td><?= date('d M Y, H:i', strtotime($incident['created_at'])) ?></td>
                  <td>
                    <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#viewModal"
                      data-id="<?= $incident['id'] ?>"
                      data-title="<?= htmlspecialchars($incident['title']) ?>"
                      data-desc="<?= htmlspecialchars($incident['description']) ?>"
                      data-status="<?= ucfirst($status) ?>"
                      data-date="<?= date('d M Y, H:i', strtotime($incident['created_at'])) ?>">
                      View
                    </button>
                  </td>
                </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>

  <footer class="main-footer text-sm text-center">
    <strong>&copy; <?= date('Y') ?> Corporate Force Security Pte Ltd</strong>. All rights reserved.
  </footer>
</div>

<!-- View Modal -->
<div class="modal fade" id="viewModal" tabindex="-1" aria-labelledby="viewModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Incident Details</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p><strong>Title:</strong> <span id="modalTitle"></span></p>
        <p><strong>Description:</strong> <span id="modalDesc"></span></p>
        <p><strong>Status:</strong> <span id="modalStatus" class="badge"></span></p>
        <p><strong>Reported On:</strong> <span id="modalDate"></span></p>
            <div class="d-flex justify-content-end gap-2">
            <button id="btnApprove" class="btn btn-success btn-sm">✅ Approve</button>
            <button id="btnReject" class="btn btn-danger btn-sm">❌ Reject</button>
            </div>
            <input type="hidden" id="incidentId" />

      </div>
    </div>
  </div>
</div>


<!-- JS Scripts -->
<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>

<!-- DataTables + Export -->
<script src="https://cdn.datatables.net/1.13.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.5/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>

<script>

document.getElementById('btnApprove').onclick = () => updateStatus('approved');
document.getElementById('btnReject').onclick = () => updateStatus('rejected');

function updateStatus(status) {
  const id = document.getElementById('incidentId').value;
  fetch('update_incident_status.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: `id=${id}&status=${status}`
  })
  .then(res => res.text())
  .then(response => {
    if (response === 'success') {
      document.querySelector('#viewModal .btn-close').click();
      showToast(`Status updated to "${status}"`, 'success');
      setTimeout(() => location.reload(), 1000);
    } else {
      showToast("Error updating status", 'danger');
    }
  });
}

function showToast(msg, type) {
  const toast = document.createElement('div');
  toast.className = `toast align-items-center text-white bg-${type} border-0 position-fixed bottom-0 end-0 m-3`;
  toast.role = 'alert';
  toast.innerHTML = `
    <div class="d-flex">
      <div class="toast-body">${msg}</div>
      <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
    </div>`;
  document.body.appendChild(toast);
  new bootstrap.Toast(toast).show();
  setTimeout(() => toast.remove(), 3000);
}


  $(document).ready(function () {
    $('#incidentTable').DataTable({
      pageLength: 10,
      order: [[2, 'desc']],
      dom: 'Bfrtip',
      buttons: [
        { extend: 'csv', className: 'btn btn-sm btn-outline-success' },
        { extend: 'pdf', className: 'btn btn-sm btn-outline-danger' },
        { extend: 'print', className: 'btn btn-sm btn-outline-secondary' }
      ]
    });
  });

  const modal = document.getElementById('viewModal');
  modal.addEventListener('show.bs.modal', function (event) {
  const button = event.relatedTarget;
  const id = button.getAttribute('data-id');
  const title = button.getAttribute('data-title');
  const desc = button.getAttribute('data-desc');
  const status = button.getAttribute('data-status');
  const date = button.getAttribute('data-date');

  document.getElementById('modalTitle').textContent = title;
  document.getElementById('modalDesc').textContent = desc;
  document.getElementById('modalStatus').textContent = status;
  document.getElementById('modalDate').textContent = date;
  document.getElementById('incidentId').value = id;

  const badge = document.getElementById('modalStatus');
  badge.className = 'badge bg-' + (status === 'Approved' ? 'success' : status === 'Rejected' ? 'danger' : 'secondary');
});

</script>
</body>
</html>
