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

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

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

$trend = $pdo->query("SELECT DATE(date) as day, COUNT(*) as count FROM attendance GROUP BY day ORDER BY day DESC LIMIT 7")->fetchAll();
$trendLabels = json_encode(array_column(array_reverse($trend), 'day'));
$trendCounts = json_encode(array_column(array_reverse($trend), 'count'));
?>

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

  <!-- AdminLTE -->
  <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" />
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

  <style>
    .content-wrapper {
      background-color: #f4f6f9;
    }
     .modal-title {
      font-weight: 600;
    }
  </style>
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

  <!-- Navbar -->
  <?php include '../includes/topbar.php'; ?>
  <!-- Main Sidebar -->
  <?php include '../includes/sidebar.php'; ?>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header -->
    <div class="content-header">
      
      <div class="container-fluid">
        <h4 class="mb-2">👋 Welcome, <?= htmlspecialchars($_SESSION['username'] ?? 'Admin') ?></h4>
        <div class="d-flex justify-content-end">
          <button class="btn btn-sm btn-outline-primary me-2" onclick="exportChart()">📤 Export Chart</button>
          <button class="btn btn-sm btn-outline-success" onclick="exportKPI()">📄 Export KPIs</button>
        </div>
      </div>
    </div>

    <!-- Main content -->
    <div class="content">
      <div class="container-fluid">

        <div class="row">
          <div class="col-lg-3 col-6">
            <div class="small-box bg-primary">
              <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><?= $totalSites ?></h3>
                <p>Sites</p>
              </div>
              <div class="icon"><i class="fas fa-building"></i></div>
            </div>
          </div>

          <div class="col-lg-3 col-6">
            <div class="small-box bg-danger">
              <div class="inner">
                <h3><?= $totalIncidents ?></h3>
                <p>Incidents</p>
              </div>
              <div class="icon"><i class="fas fa-exclamation-triangle"></i></div>
            </div>
          </div>

          <div class="col-lg-3 col-6">
            <div class="small-box bg-warning">
              <div class="inner">
                <h3><?= $totalToday ?></h3>
                <p>Today Attendance</p>
              </div>
              <div class="icon"><i class="fas fa-calendar-check"></i></div>
            </div>
          </div>
        </div>

        <!-- Attendance Chart -->
        <div class="card mt-4">
          <div class="card-header">
            <h5 class="card-title">📊 Attendance Trend (Last 7 Days)</h5>
          </div>
          <div class="card-body">
            <canvas id="trendChart" height="100"></canvas>
          </div>
        </div>

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

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

<!-- Toast Notification -->
<div class="position-fixed bottom-0 end-0 p-3" style="z-index: 1055">
  <div id="dashboardToast" class="toast bg-success text-white" role="alert" data-bs-delay="3000">
    <div class="toast-header bg-success text-white">
      <strong class="me-auto">Dashboard</strong>
      <small>just now</small>
      <button type="button" class="btn-close btn-close-white ms-2" data-bs-dismiss="toast"></button>
    </div>
    <div class="toast-body">
      ✅ Dashboard loaded successfully!
    </div>
  </div>
</div>

<!-- JS Scripts -->
<script>
  const ctx = document.getElementById('trendChart').getContext('2d');
  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: <?= $trendLabels ?>,
      datasets: [{
        label: 'Check-ins',
        data: <?= $trendCounts ?>,
        backgroundColor: '#007bff',
        borderRadius: 8
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        y: {
          beginAtZero: true,
          ticks: { stepSize: 1 }
        }
      }
    }
  });

  function exportChart() {
    const canvas = document.getElementById('trendChart');
    const link = document.createElement('a');
    link.href = canvas.toDataURL('image/png');
    link.download = 'attendance_trend.png';
    link.click();
  }

  function exportKPI() {
    const rows = [
      ['KPI', 'Count'],
      ['Total Officers', <?= $totalOfficers ?>],
      ['Sites', <?= $totalSites ?>],
      ['Incidents', <?= $totalIncidents ?>],
      ['Attendance Today', <?= $totalToday ?>]
    ];

    let csvContent = "data:text/csv;charset=utf-8," + 
      rows.map(e => e.join(",")).join("\n");

    const encodedUri = encodeURI(csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "kpi_summary.csv");
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  window.onload = () => {
    const toast = new bootstrap.Toast(document.getElementById('dashboardToast'));
    toast.show();
  };
</script>

<!-- AdminLTE JS -->
<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>
</body>
</html>
