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

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

$adminId = $_SESSION['user_id'];

// Insert default tasks if none exist
$checkTasks = $pdo->prepare("SELECT COUNT(*) FROM dashboard_tasks WHERE admin_id = ?");
$checkTasks->execute([$adminId]);
if ($checkTasks->fetchColumn() == 0) {
  $defaultTasks = [
    "Review new leave requests",
    "Check today's attendance",
    "Update incident log",
    "Review new deployment sites"
  ];
  $stmt = $pdo->prepare("INSERT INTO dashboard_tasks (admin_id, task) VALUES (?, ?)");
  foreach ($defaultTasks as $task) {
    $stmt->execute([$adminId, $task]);
  }
}

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

// Chart Data
$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 & Bootstrap -->
  <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>
    body { font-size: 0.9rem; }
    .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($_SESSION['username'] ?? 'Admin') ?></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="exportKPI()">📄 Export KPIs</button>
        </div>
      </div>
    </section>

    <section class="content">
      <div class="container-fluid">

        <!-- KPI Cards -->
        <div class="row">
          <?php
          $kpis = [
            ['Total Officers', $totalOfficers, 'primary', 'fa-user-shield'],
            ['Sites', $totalSites, 'success', 'fa-building'],
            ['Incidents', $totalIncidents, 'danger', 'fa-exclamation-triangle'],
            ['Today Attendance', $totalToday, 'warning', 'fa-calendar-check']
          ];
          foreach ($kpis as [$label, $count, $color, $icon]) {
            echo "<div class='col-lg-3 col-6'>
              <div class='small-box bg-$color'>
                <div class='inner'><h3>$count</h3><p>$label</p></div>
                <div class='icon'><i class='fas $icon'></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>

        <!-- Summaries (AJAX-loaded) -->
        <div class="row mt-4">
          <!-- Leaves -->
          <div class="col-md-6">
            <div class="card">
              <div class="card-header bg-info text-white">
                <h5 class="card-title"><i class="fas fa-calendar-alt me-2"></i>Recent Leave Requests</h5>
              </div>
              <div class="card-body p-2" id="leave-summary">
                <div class="text-center py-3 text-muted">Loading...</div>
              </div>
            </div>
          </div>

          <!-- Sites -->
          <div class="col-md-6">
            <div class="card">
              <div class="card-header bg-primary text-white">
                <h5 class="card-title"><i class="fas fa-map-marker-alt me-2"></i>Recently Added Sites</h5>
              </div>
              <div class="card-body p-2" id="site-summary">
                <div class="text-center py-3 text-muted">Loading...</div>
              </div>
            </div>
          </div>
        </div>

        <!-- Admin Tasks -->
        <div class="row mt-4">
          <div class="col-md-12">
            <div class="card">
              <div class="card-header bg-secondary text-white">
                <h5 class="card-title"><i class="fas fa-clipboard-check me-2"></i>Admin Tasks</h5>
              </div>
              <div class="card-body">
                <ul class="list-group" id="taskList">
                  <?php
                  $tasks = $pdo->prepare("SELECT id, task, completed FROM dashboard_tasks WHERE admin_id = ?");
                  $tasks->execute([$adminId]);
                  foreach ($tasks as $t):
                  ?>
                    <li class="list-group-item">
                      <input type="checkbox" class="form-check-input me-2 task-check" data-id="<?= $t['id'] ?>" <?= $t['completed'] ? 'checked' : '' ?>>
                      <?= htmlspecialchars($t['task']) ?>
                    </li>
                  <?php endforeach; ?>
                </ul>
              </div>
            </div>
          </div>
        </div>

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

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

<!-- Toast (from leave action redirect) -->
<?php if (isset($_GET['msg'])): ?>
  <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 1055;">
    <div id="actionToast" class="toast bg-<?= $_GET['msg'] === 'approved' ? 'success' : 'danger' ?> text-white" role="alert" data-bs-delay="3000">
      <div class="d-flex">
        <div class="toast-body">✅ Leave <?= htmlspecialchars($_GET['msg']) ?> successfully!</div>
        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
      </div>
    </div>
  </div>
  <script>window.onload = () => { new bootstrap.Toast(document.getElementById('actionToast')).show(); };</script>
<?php endif; ?>

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

<script>
  const ctx = document.getElementById('trendChart').getContext('2d');
  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: <?= $trendLabels ?>,
      datasets: [{
        label: 'Check-ins',
        data: <?= $trendCounts ?>,
        backgroundColor: '#0d6efd',
        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 csv = [
      ['KPI', 'Count'],
      ['Total Officers', <?= $totalOfficers ?>],
      ['Sites', <?= $totalSites ?>],
      ['Incidents', <?= $totalIncidents ?>],
      ['Today Attendance', <?= $totalToday ?>]
    ];
    const content = "data:text/csv;charset=utf-8," + csv.map(e => e.join(",")).join("\n");
    const link = document.createElement("a");
    link.href = encodeURI(content);
    link.download = "kpi_summary.csv";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  // Auto-refresh summary sections
  function loadSummary(type, container) {
    $.get('dashboard_data.php?type=' + type, function (html) {
      document.getElementById(container).innerHTML = '<ul class="list-group">' + html + '</ul>';
    });
  }

  loadSummary('leaves', 'leave-summary');
  loadSummary('sites', 'site-summary');
  setInterval(() => {
    loadSummary('leaves', 'leave-summary');
    loadSummary('sites', 'site-summary');
  }, 30000);

  // Update task checklist
  $(document).on('change', '.task-check', function () {
    const taskId = $(this).data('id');
    const checked = $(this).is(':checked') ? 1 : 0;
    $.post('update_task_status.php', {
      id: taskId,
      completed: checked
    }, function (res) {
      if (!res.success) alert('Failed to update task.');
    }, 'json');
  });
</script>
</body>
</html>
