<?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');

try {
    // Fetch attendance with officer name and site (if available)
    $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();

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

    // Metrics
    $totalToday = $pdo->query("SELECT COUNT(*) FROM attendance WHERE date = CURDATE()")->fetchColumn();
    $totalOfficers = $pdo->query("SELECT COUNT(*) FROM users WHERE role = 'officer'")->fetchColumn();
    $alerts = $pdo->query("SELECT COUNT(*) FROM attendance WHERE TIMESTAMPDIFF(HOUR, time_in, time_out) > 12 AND date = CURDATE()")->fetchColumn();
    $myMonthCount = $pdo->prepare("SELECT COUNT(*) FROM controller_attendance WHERE controller_id = ? AND date >= CURDATE() - INTERVAL 30 DAY");
    $myMonthCount->execute([$controller_id]);
    $monthlyTotal = $myMonthCount->fetchColumn();

    // Controller Weekly Trend
    $trendStmt = $pdo->prepare("SELECT date, time_in FROM controller_attendance WHERE controller_id = ? AND date >= CURDATE() - INTERVAL 7 DAY ORDER BY date ASC");
    $trendStmt->execute([$controller_id]);
    $trend = $trendStmt->fetchAll();
    $trendLabels = json_encode(array_column($trend, 'date'));
    $trendCounts = json_encode(array_map(fn($r) => $r['time_in'] ? 1 : 0, $trend));

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

    // 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 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();

} catch (PDOException $e) {
    die("Database error: " . htmlspecialchars($e->getMessage()));
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Controller Dashboard | CFS System OS</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; }</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 d-flex justify-content-between align-items-center">
            <h4 class="mb-0">👋 Welcome, <?= htmlspecialchars($username) ?></h4>
            <div>
              <button class="btn btn-sm btn-outline-primary me-2" onclick="exportChart()">📤 Export Chart</button>
              <button class="btn btn-sm btn-outline-success" onclick="window.print()">🖨️ Print Dashboard</button>
            </div>
          </div>
        </section>

        <section class="content">
          <div class="row">
            <div class="col-lg-3 col-6">
              <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-lg-3 col-6">
              <div class="small-box bg-success">
                <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 class="col-lg-3 col-6">
              <div class="small-box bg-warning">
                <div class="inner">
                  <h3><?= $monthlyTotal ?></h3>
                  <p>My Attendance (30 Days)</p>
                </div>
                <div class="icon"><i class="fas fa-user-clock"></i></div>
              </div>
            </div>
            <div class="col-lg-3 col-6">
              <div class="small-box bg-danger">
                <div class="inner">
                  <h3><?= $alerts ?></h3>
                  <p>Overtime Alerts</p>
                </div>
                <div class="icon"><i class="fas fa-exclamation-triangle"></i></div>
              </div>
            </div>
          </div>
        </section>
<!-------------------------------------------------------------------->
       <section class="content"> 
          <div class="row">
            <!-- My Attendance -->
            <div class="col-lg-3 col-6">
              <div class="card">
                <div class="card-header">
                  <div class="section-title">📍 My Attendance</div>
                </div>
                <div class="card-body">
                      <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>
            </div>

            <div class="col-lg-3 col-6">
              <div class="card">
                <div class="card-header">
                  <div class="section-title">📅 Attendance Summary</div>
                </div>
                <div class="card-body">
                  <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>
            </div>

            <div class="col-lg-3 col-6">
              <div class="card">
                <div class="card-header">
                  <div class="section-title">📅 Today's Officer Attendance</div>
                </div>
                <div class="card-body">
                  <table class="table table-bordered table-striped align-middle small">
                              <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 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>
            </div>
          </div>
       </section>
<!--------------------------------------------------------------------> 
     <section class="content">
        <div class="row">
          <div class="col-md-12">
            <div class="card">
              <div class="card-header">
                <h5 class="card-title">Box 1</h5>
              </div>
              <div class="card-body">
                Content of Box 1
              </div>
            </div>
          </div>
    </section>
    <section class="content">
          <div class="row">
          <div class="col-md-4">
            <div class="card">
              <div class="card-header">
                <h5 class="card-title">Box 1</h5>
              </div>
              <div class="card-body">
                Content of Box 1
              </div>
            </div>
          </div>

          <div class="col-md-4">
            <div class="card">
              <div class="card-header">
                <h5 class="card-title">Box 2</h5>
              </div>
              <div class="card-body">
                Content of Box 2
              </div>
            </div>
          </div>

          <div class="col-md-4">
            <div class="card">
              <div class="card-header">
                <h5 class="card-title">Box 3</h5>
              </div>
              <div class="card-body">
                Content of Box 3
              </div>
            </div>
          </div>
        </div>
                        
    </section>
</div>
</body>
</html>
