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

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

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

$totalOfficers = $pdo->query("SELECT COUNT(*) FROM users WHERE role = 'officer'")->fetchColumn();
$totalSites = $pdo->query("SELECT COUNT(*) FROM sites")->fetchColumn();
$totalToday = $pdo->query("SELECT COUNT(*) FROM attendance WHERE date = CURDATE()")->fetchColumn();

$stmt = $pdo->prepare("
  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 = :today
  ORDER BY a.time_in DESC
");
$stmt->execute([':today' => $today]);
$records = $stmt->fetchAll();

$alertStmt = $pdo->prepare("
  SELECT a.*, u.username
  FROM attendance a
  JOIN users u ON a.officer_id = u.id
  WHERE DATE(a.date) = :today AND a.time_in IS NOT NULL AND a.time_out IS NOT NULL
");
$alertStmt->execute([':today' => $today]);
$officerAlerts = $alertStmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Controller 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">
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <style>
    .content-wrapper { background-color: #f4f6f9; }
    .card-box { background: #fff; border-radius: 8px; padding: 15px; box-shadow: 0 2px 6px rgba(0,0,0,0.05); }
    .section-title { font-weight: 600; margin-bottom: 10px; }
  </style>
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
  <?php include '../includes/topbar_controller.php'; ?>
  <?php include '../includes/sidebar_controller.php'; ?>

  <div class="content-wrapper">
    <section class="content-header">
      <div class="container-fluid d-flex justify-content-between align-items-center">
        <h4 class="mb-0">👮 Controller Dashboard – <?= htmlspecialchars($username) ?></h4>
        <span class="badge badge-primary p-2">Date: <?= $today ?></span>
      </div>
    </section>

    <section class="content">
      <div class="container-fluid">
        <div class="row">
          <div class="col-md-4">
            <div class="small-box bg-info">
              <div class="inner"><h3><?= $totalOfficers ?></h3><p>Total Officers</p></div>
              <div class="icon"><i class="fas fa-user-shield"></i></div>
            </div>
          </div>
          <div class="col-md-4">
            <div class="small-box bg-success">
              <div class="inner"><h3><?= $totalSites ?></h3><p>Client Sites</p></div>
              <div class="icon"><i class="fas fa-building"></i></div>
            </div>
          </div>
          <div class="col-md-4">
            <div class="small-box bg-warning">
              <div class="inner"><h3><?= $totalToday ?></h3><p>Today’s Attendance</p></div>
              <div class="icon"><i class="fas fa-calendar-check"></i></div>
            </div>
          </div>
        </div>

        <div class="card mt-3">
          <div class="card-header"><h5 class="card-title">🕵️ Officer Check-In Today</h5></div>
          <div class="card-body table-responsive">
            <table class="table table-bordered table-striped table-sm">
              <thead class="table-dark">
                <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', strtotime($r['time_in'])) : '-' ?></td>
                  <td><?= $r['time_out'] ? date('H:i', strtotime($r['time_out'])) : '-' ?></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 records found today.</td></tr>
              <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>

        <div class="card mt-4">
          <div class="card-header"><h5 class="card-title">⚠️ Overtime Alert – Officers Over 12 Hours</h5></div>
          <div class="card-body">
            <table class="table table-bordered table-sm small">
              <thead class="table-danger"><tr><th>Officer</th><th>Time In</th><th>Time 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 ?>h <?= $diff->i ?>m</td>
                </tr>
              <?php endif; endforeach; ?>
              <?php if (!$alerted): ?>
                <tr><td colspan="4" class="text-center text-muted">✅ No overtime alerts.</td></tr>
              <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>

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

  <?php include '../includes/footer.php'; ?>
<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>

</div>
</body>
</html>
