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

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

$today = date('Y-m-d');

// Fetch attendance with officer name and site (if available)
$stmt = $pdo->query("
  SELECT a.*, u.username, s.site_name
  FROM attendance a
  JOIN users u ON a.officer_id = u.id
  LEFT JOIN sites s ON u.site_id = s.id
  WHERE a.date = CURDATE()
  ORDER BY a.time_in DESC
");
$records = $stmt->fetchAll();

$controller_id = $_SESSION['user_id'];
$username = $_SESSION['username'] ?? 'Controller';
$today = date('Y-m-d');

// ✅ Controller Attendance Today
$stmt = $pdo->prepare("SELECT * FROM controller_attendance WHERE controller_id = ? AND date = ?");
$stmt->execute([$controller_id, $today]);
$myAttendance = $stmt->fetch();

// ✅ Weekly Attendance Summary (Last 7 Days)
$weekStmt = $pdo->prepare("
  SELECT date, time_in, time_out 
  FROM controller_attendance 
  WHERE controller_id = ? 
  AND date >= CURDATE() - INTERVAL 7 DAY 
  ORDER BY date DESC
");
$weekStmt->execute([$controller_id]);
$weekData = $weekStmt->fetchAll();

// ✅ Monthly Attendance Count (last 30 days)
$monthStmt = $pdo->prepare("
  SELECT COUNT(*) 
  FROM controller_attendance 
  WHERE controller_id = ? 
  AND date >= CURDATE() - INTERVAL 30 DAY
");
$monthStmt->execute([$controller_id]);
$monthlyTotal = $monthStmt->fetchColumn();

// ✅ Officer Alerts (Attendance > 12 hrs)
$alertStmt = $pdo->prepare("
  SELECT a.*, u.username 
  FROM attendance a 
  JOIN users u ON a.officer_id = u.id 
  WHERE a.date = ?  
    AND a.time_in IS NOT NULL 
    AND a.time_out IS NOT NULL
");
$alertStmt->execute([$today]);
$officerAlerts = $alertStmt->fetchAll();
?>


<!DOCTYPE html>
<html>
<head>
  <title>Controller Dashboard</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.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="../assets/css/controller_dashboard.css">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  
  <!-- jQuery (required for AJAX) -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

  <style>
      body {
        background-color: #f2f4f8;
        font-size: 14px;
      }

      h4 {
        font-weight: 600;
        color: #004080;
      }

      .card-box {
        background: #fff;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 0 10px rgba(0,0,0,0.04);
        margin-bottom: 20px;
      }

      .section-title {
        font-size: 15px;
        font-weight: 600;
        margin-bottom: 12px;
        color: #2c3e50;
      }

      .btn {
        font-size: 13px;
      }

      table.table-sm th, table.table-sm td {
        vertical-align: middle;
      }

      .table th {
        background-color: #e9ecef;
      }

      .badge {
        font-size: 11px;
      }

      .alert {
        padding: 8px 12px;
        font-size: 13px;
      }
  </style>

</head>
<body>
  

<?php if (isset($_SESSION['message'])): ?>
<div class="position-fixed top-0 end-0 p-3" style="z-index: 9999;">
  <div id="liveToast" class="toast align-items-center text-bg-primary border-0 show" role="alert">
    <div class="d-flex">
      <div class="toast-body">
        <?= $_SESSION['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['message']); endif; ?>


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

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

  <h4 class="mb-4">🙎‍♂️ Welcome, <?= htmlspecialchars($username ?? 'Controller') ?></h4>
  <hr>
  <div class="row g-4">
          <!-- My Attendance -->
          <div class="col-md-6">
            <div class="card-box">
              <div class="section-title">📍 My Attendance</div>
              <form method="post" action="mark_attendance.php">
                <button class="btn btn-primary btn-sm me-2" name="action" value="in">Check-In</button>
                <button class="btn btn-secondary btn-sm" name="action" value="out">Check-Out</button>
              </form>
              <?php if ($myAttendance): ?>
                <div class="mt-3 small">
                  <p>✅ Time In: <?= $myAttendance['time_in'] ? date('H:i', strtotime($myAttendance['time_in'])) : '—' ?></p>
                  <p>✅ Time Out: <?= $myAttendance['time_out'] ? date('H:i', strtotime($myAttendance['time_out'])) : '—' ?></p>
                </div>
              <?php else: ?>
                <p class="mt-3 text-muted">You have not marked attendance yet today.</p>
              <?php endif; ?>

            </div>
          </div>

          <!-- Attendance Summary -->
          <div class="col-md-6">
            <div class="card-box">
              <div class="section-title">📅 Attendance Summary</div>
              <p><strong>Past 30 Days:</strong> <?= $monthlyTotal ?> days present</p>
              <h6 class="text-secondary mt-3">🗓️ Last 7 Days</h6>
              <ul class="list-group list-group-flush small">
                <?php foreach ($weekData as $d): ?>
                <li class="list-group-item">
                  <strong><?= date('D, d M', strtotime($d['date'])) ?>:</strong>
                  In: <?= $d['time_in'] ? date('H:i', strtotime($d['time_in'])) : '—' ?> |
                  Out: <?= $d['time_out'] ? date('H:i', strtotime($d['time_out'])) : '—' ?>
                </li>
                <?php endforeach; ?>
                <?php if (empty($weekData)): ?>
                  <li class="list-group-item text-muted">No attendance records.</li>
                <?php endif; ?>
              </ul>
            </div>
          </div>
          
          <!-- Officer Attendance today -->
          <div class="col-md-12">
            <div class="card-box">
            <div class="section-title">📅 Today's Officer Attendance</div>
            <table class="table table-bordered table-striped align-middle">
              <thead>
              <tr>
                <th>#</th>
                <th>Officer</th>
                <th>Site</th>
                <th>Time In</th>
                <th>Time Out</th>
                <th>Status</th>
              </tr>
              </thead>
              <tbody>
                <?php foreach ($records as $i => $r): ?>
                <tr>
                  <td><?= $i + 1 ?></td>
                  <td><?= htmlspecialchars($r['username']) ?></td>
                  <td><?= htmlspecialchars($r['site_name'] ?? 'Unassigned') ?></td>
                  <td><?= $r['time_in'] ? date('h:i A', strtotime($r['time_in'])) : '-' ?></td>
                  <td><?= $r['time_out'] ? date('h:i A', strtotime($r['time_out'])) : '<span class="text-danger">Not Signed Out</span>' ?></td>
                  <td>
                    <?php if ($r['time_in'] && $r['time_out']): ?>
                      <span class="badge bg-success">✔ Completed</span>
                    <?php elseif ($r['time_in']): ?>
                      <span class="badge bg-warning text-dark">⏳ Active</span>
                    <?php else: ?>
                      <span class="badge bg-secondary">-</span>
                    <?php endif; ?>
                  </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($records)): ?>
                  <tr><td colspan="6" class="text-center text-muted">No attendance recorded today.</td></tr>
                <?php endif; ?>
              </tbody>

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

          <!-- Officer Alerts -->
          <div class="col-md-12">
            <div class="card-box">
              <div class="section-title">⏱️ Officer Alerts (12+ Hours)</div>
              <table class="table table-sm table-bordered">
                <thead><tr><th>Officer</th><th>In</th><th>Out</th><th>Duration</th></tr></thead>
                <tbody>
                <?php
                  $alerted = false;
                  foreach ($officerAlerts as $r):
                    $in = new DateTime($r['time_in']);
                    $out = new DateTime($r['time_out']);
                    $diff = $in->diff($out);
                    $hours = $diff->h + ($diff->days * 24);
                    if ($hours > 12): $alerted = true;
                ?>
                  <tr class="table-danger">
                    <td><?= htmlspecialchars($r['username']) ?></td>
                    <td><?= date('H:i', strtotime($r['time_in'])) ?></td>
                    <td><?= date('H:i', strtotime($r['time_out'])) ?></td>
                    <td><?= $hours ?> hrs <?= $diff->i ?> mins</td>
                  </tr>
                <?php endif; endforeach; ?>
                <?php if (!$alerted): ?>
                  <tr><td colspan="4" class="text-center text-muted">✅ No officers exceeded 12 hours.</td></tr>
                <?php endif; ?>
                </tbody>
              </table>
            </div>
          </div>

          <!-- Modules -->
          <div class="col-md-4"><div class="card-box"><div class="section-title">🗓️ Roster</div><a href="manage_roster.php" class="btn btn-outline-primary btn-sm">Manage</a></div></div>
          <div class="col-md-4"><div class="card-box"><div class="section-title">📌 Assign Sites</div><a href="assign_sites.php" class="btn btn-outline-success btn-sm">Assign</a></div></div>
          <div class="col-md-4"><div class="card-box"><div class="section-title">📋 Occurrence Log</div><a href="occurrence_log.php" class="btn btn-outline-dark btn-sm">Log</a></div></div>
          <div class="col-md-4"><div class="card-box"><div class="section-title">🚨 Incident Feed</div><a href="incident_feed.php" class="btn btn-outline-danger btn-sm">View</a></div></div>
          <div class="col-md-4"><div class="card-box"><div class="section-title">📝 Report Incident</div><a href="submit_incident.php" class="btn btn-outline-warning btn-sm">Report</a></div></div>
          <div class="col-md-4"><div class="card-box"><div class="section-title">📂 My Reports</div><a href="view_incidents.php" class="btn btn-outline-info btn-sm">View</a></div></div>

          <!-- Incident Feed Section -->
          <div class="card mb-4">
              <div class="card-header">
                  <h5>🚨 Live Incident Feed</h5>
              </div>
              <div class="card-body">
                  <ul id="incident-feed" class="list-group">
                      <!-- Incident items will be appended here -->
                  </ul>
              </div>
          </div>
  </div>
</div>


<script>
$(document).ready(function() {
    function fetchIncidents() {
        $.ajax({
            url: 'ajax_fetch_incidents.php',
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                var feed = $('#incident-feed');
                feed.empty(); // Clear existing items

                if (data.length === 0) {
                    feed.append('<li class="list-group-item">No incidents reported.</li>');
                } else {
                    data.forEach(function(incident) {
                        var item = '<li class="list-group-item">' +
                            '<strong>' + incident.title + '</strong><br>' +
                            'Reported by ' + incident.officer_name + ' at ' + incident.site_name + '<br>' +
                            'Date: ' + incident.incident_date + ' Time: ' + incident.incident_time +
                            '</li>';
                        feed.append(item);
                    });
                }
            },
            error: function(xhr, status, error) {
                console.error('Error fetching incidents:', error);
            }
        });
    }

    // Initial fetch
    fetchIncidents(); 
    // Fetch incidents every 30 seconds
    setInterval(fetchIncidents, 30000);
});
</script>

<script>
function fetchEvents() {
  fetch('fetch_site_events.php')
    .then(response => {
      if (!response.ok) {
        throw new Error("Failed to fetch site events");
      }
      return response.text();
    })
    .then(data => {
      const feedContainer = document.getElementById('eventFeedBody');
      if (feedContainer) {
        feedContainer.innerHTML = data;
      } else {
        console.warn("eventFeedBody element not found");
      }
    })
    .catch(error => console.error("Error loading events:", error));
}

// Initial load
fetchEvents();

// Auto-refresh every 10 seconds
setInterval(fetchEvents, 10000);
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
  const toastEl = document.getElementById('liveToast');
  if (toastEl) {
    const toast = new bootstrap.Toast(toastEl, { delay: 3000 });
    toast.show();
  }
});
</script>


</body>
</html>
