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

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

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

$leaveRecords = $pdo->query("
  SELECT l.from_date, l.to_date, l.type, u.username 
  FROM leave l 
  JOIN users u ON l.officer_id = u.id
  WHERE l.status = 'approved'
")->fetchAll();

$events = [];

// Attendance
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']
    ]
  ];
}

// Leave
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'));

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

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Attendance Calendar | 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://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.0/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.7/index.global.min.css">
  <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'; ?>

  <!-- Content Wrapper -->
  <div class="content-wrapper">
    <section class="content-header">
      <div class="container-fluid">
        <h4 class="mb-3">📅 Attendance & Leave Calendar</h4>
        <form class="row mb-3" id="leaveFilterForm">
          <div class="col-md-4">
            <label for="leaveTypeFilter" class="form-label">Filter Leave Type</label>
            <select id="leaveTypeFilter" class="form-select">
              <option value="all">All Leave Types</option>
              <option value="Annual">Annual Leave</option>
              <option value="Sick">Sick Leave</option>
              <option value="Unpaid">Unpaid Leave</option>
              <option value="Medical">Medical Leave</option>
            </select>
          </div>
        </form>
      </div>
    </section>

    <section class="content">
      <div class="container-fluid">
        <div class="card card-primary">
          <div class="card-body">
            <div id="attendanceCalendar"></div>

            <!-- Legend -->
            <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>
      </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">
          <!-- Filled by JS -->
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>

</div>

<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.7/index.global.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}<br>
            <strong>Leave Type:</strong> ${props.leave_type}
          `;
        }

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

    calendar.render();

    // Leave filter
    document.getElementById('leaveTypeFilter').addEventListener('change', function () {
      const selectedType = this.value;
      const filtered = rawEvents.filter(event => {
        if (selectedType === 'all') return true;
        if (event.extendedProps?.type === 'leave') {
          return event.extendedProps.leave_type.toLowerCase() === selectedType.toLowerCase();
        }
        return true;
      });

      calendar.removeAllEvents();
      calendar.addEventSource(filtered);
    });
  });
</script>
</body>
</html>
