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

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

// Attendance data
$attendanceRecords = $pdo->query("
  SELECT a.date, a.time_in, a.time_out, a.gps_in, a.gps_out, u.username 
  FROM attendance a 
  JOIN users u ON a.officer_id = u.id
")->fetchAll();

// Approved leave
$leaveRecords = $pdo->query("
  SELECT lr.start_date AS from_date, lr.end_date AS to_date, lr.leave_type AS type, u.username, u.id AS officer_id
  FROM leave_requests lr
  JOIN users u ON lr.officer_id = u.id
  WHERE lr.status = 'approved' AND u.role = 'officer'
")->fetchAll();

// Chart summary
$leaveCounts = ['Annual' => 0, 'Sick' => 0, 'Medical' => 0, 'Unpaid' => 0, 'Other' => 0];
foreach ($leaveRecords as $l) {
  $type = ucfirst(strtolower(trim($l['type'])));
  if (isset($leaveCounts[$type])) {
    $leaveCounts[$type]++;
  } else {
    $leaveCounts['Other']++;
  }
}

$leaveLabels = json_encode(array_keys($leaveCounts));
$leaveValues = json_encode(array_values($leaveCounts));

// FullCalendar events
$events = [];
foreach ($attendanceRecords as $r) {
  $isNight = (date('H', strtotime($r['time_in'] ?? '08:00')) >= 20 || date('H', strtotime($r['time_in'] ?? '08:00')) < 6);
  $events[] = [
    'title' => htmlspecialchars($r['username']),
    'start' => $r['date'],
    'backgroundColor' => $isNight ? 'blue' : 'green',
    'borderColor' => $isNight ? 'blue' : 'green',
    'textColor' => 'white',
    'extendedProps' => [
      'type' => 'attendance',
      'username' => $r['username'],
      'time_in' => $r['time_in'],
      'time_out' => $r['time_out'],
      'gps_in' => $r['gps_in'],
      'gps_out' => $r['gps_out']
    ]
  ];
}

$colorMap = ['Annual' => '#007bff', 'Sick' => '#28a745', 'Medical' => '#17a2b8', 'Unpaid' => '#ffc107'];
foreach ($leaveRecords as $l) {
  $start = new DateTime($l['from_date']);
  $end = new DateTime($l['to_date']);
  $interval = new DateInterval('P1D');
  $range = new DatePeriod($start, $interval, $end->modify('+1 day'));
  $color = $colorMap[$l['type']] ?? 'orange';

  foreach ($range as $date) {
    $events[] = [
      'title' => $l['username'] . " ({$l['type']})",
      'start' => $date->format('Y-m-d'),
      'backgroundColor' => $color,
      'borderColor' => $color,
      'textColor' => 'white',
      'extendedProps' => [
        'type' => 'leave',
        'username' => $l['username'],
        'leave_type' => $l['type'],
        'officer_id' => $l['officer_id']
      ]
    ];
  }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Attendance & Leave Calendar</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">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.7/index.global.min.css">
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

  <style>
    .legend-icon { font-size: 1.1rem; margin-right: 8px; }
    .text-green { color: green; }
    .text-blue { color: blue; }
    .text-orange { color: orange; }
  </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">
        <h4>📅 Attendance & Leave Calendar</h4>
      </div>
    </section>
    <section class="content">
        <div class="container-fluid">

          <!-- Calendar -->
          <div class="card card-primary">
            <div class="card-body">
              <div id="attendanceCalendar"></div>
              <div class="mt-4">
                <h6>📘 Legend:</h6>
                <div class="d-flex flex-wrap gap-4">
                  <div class="d-flex align-items-center"><i class="fas fa-circle legend-icon text-green"></i> Day Shift</div>
                  <div class="d-flex align-items-center"><i class="fas fa-circle legend-icon text-blue"></i> Night Shift</div>
                  <div class="d-flex align-items-center"><i class="fas fa-circle legend-icon text-orange"></i> Approved Leave</div>
                </div>
              </div>
            </div>
          </div>

          <!-- Leave Table -->
          <div class="card mt-4">
            <div class="card-header d-flex justify-content-between align-items-center">
              <h5 class="card-title mb-0">📋 Approved Leave Records</h5>
              <button class="btn btn-sm btn-outline-success" onclick="exportLeaveTable()">Export CSV</button>
            </div>
            <div class="card-body table-responsive">
              <table class="table table-bordered table-striped table-sm">
                <thead class="table-primary">
                  <tr>
                    <th>Officer Name</th>
                    <th>Leave Type</th>
                    <th>From Date</th>
                    <th>To Date</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($leaveRecords as $leave): ?>
                    <tr>
                      <td><?= htmlspecialchars($leave['username']) ?></td>
                      <td><?= htmlspecialchars($leave['type']) ?></td>
                      <td><?= htmlspecialchars($leave['from_date']) ?></td>
                      <td><?= htmlspecialchars($leave['to_date']) ?></td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          </div>

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

  <!-- Modal -->
  <div class="modal fade" id="eventDetailModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Details</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body" id="eventDetails"></div>
        <div class="modal-footer"><button class="btn btn-secondary" data-bs-dismiss="modal">Close</button></div>
      </div>
    </div>
  </div>
</div>

<!-- JS -->
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.7/index.global.min.js"></script>
<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>
  document.addEventListener('DOMContentLoaded', function () {
    const calendarEl = document.getElementById('attendanceCalendar');
    const rawEvents = <?= json_encode($events) ?>;

    const calendar = new FullCalendar.Calendar(calendarEl, {
      initialView: 'dayGridMonth',
      height: 600,
      headerToolbar: {
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth,listWeek'
      },
      events: rawEvents,
      eventClick: function (info) {
        const props = info.event.extendedProps;
        let details = '';

        if (props.type === 'attendance') {
          details = `
            <strong>Officer:</strong> ${props.username}<br>
            <strong>Time In:</strong> ${props.time_in}<br>
            <strong>GPS In:</strong> ${props.gps_in}<br>
            <strong>Time Out:</strong> ${props.time_out}<br>
            <strong>GPS Out:</strong> ${props.gps_out}
          `;
        } else if (props.type === 'leave') {
          details = `
            <strong>Officer:</strong> ${props.username} (ID: ${props.officer_id})<br>
            <strong>Leave Type:</strong> ${props.leave_type}
          `;
        }

        document.getElementById('eventDetails').innerHTML = details;
        new bootstrap.Modal(document.getElementById('eventDetailModal')).show();
      }
    });

    calendar.render();

  
  });

  // Export Leave Table
  function exportLeaveTable() {
    const rows = [['Officer Name', 'Leave Type', 'From Date', 'To Date']];
    <?php foreach ($leaveRecords as $leave): ?>
      rows.push([
        "<?= addslashes($leave['username']) ?>",
        "<?= addslashes($leave['type']) ?>",
        "<?= $leave['from_date'] ?>",
        "<?= $leave['to_date'] ?>"
      ]);
    <?php endforeach; ?>

    const 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", "approved_leave_records.csv");
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
</script>
</body>
</html>
