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

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

$from = $_GET['from_date'] ?? '';
$to = $_GET['to_date'] ?? '';
$dateFilter = $_GET['date'] ?? '';

$query = "
  SELECT a.*, u.username 
  FROM attendance a 
  JOIN users u ON a.officer_id = u.id
";

$params = [];

if ($from && $to) {
  $query .= " WHERE a.date BETWEEN ? AND ?";
  $params = [$from, $to];
} elseif (!empty($dateFilter)) {
  $query .= " WHERE a.date = ?";
  $params = [$dateFilter];
} else {
  $query .= " ORDER BY a.date DESC, a.time_in DESC";
}

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$records = $stmt->fetchAll();
?>

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

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- AdminLTE + Bootstrap + DataTables -->
  <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.datatables.net/1.13.4/css/jquery.dataTables.min.css">
  <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.dataTables.min.css">
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

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

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

  <!-- Content Wrapper -->
  <div class="content-wrapper">
    <div class="content-header">
      <div class="container-fluid d-flex justify-content-between align-items-center">
        <h4 class="m-0">🕒 Attendance Records</h4>
      </div>
    </div>

    <div class="content">
      <div class="container-fluid">
          <!-- Calendar View -->
            <div class="card mt-4">
              <div class="card-header">
                <h5 class="card-title">📅 Attendance Calendar View</h5>
              </div>
              <div class="card-body">
                <div id="attendanceCalendar"></div>
              </div>
            </div>

        <!-- Filter Form -->
        <form class="row g-3 mb-3" method="get">
          <div class="col-auto">
            <label for="from_date">From</label>
            <input type="date" name="from_date" id="from_date" value="<?= htmlspecialchars($from) ?>" class="form-control">
          </div>
          <div class="col-auto">
            <label for="to_date">To</label>
            <input type="date" name="to_date" id="to_date" value="<?= htmlspecialchars($to) ?>" class="form-control">
          </div>
          <div class="col-auto align-self-end">
            <button class="btn btn-primary">Filter</button>
            <a href="view_attendance.php" class="btn btn-secondary">Clear</a>
          </div>
        </form>

        <!-- Table -->
        <div class="card">
          <div class="card-header">
            <h5 class="card-title">📋 Attendance Table</h5>
          </div>
          <div class="card-body">
            <div class="table-responsive">
              <table id="siteTable" class="table table-bordered table-striped text-sm">
                <thead class="table-dark">
                  <tr>
                    <th>#</th>
                    <th>Officer</th>
                    <th>Date</th>
                    <th>Time In</th>
                    <th>GPS In</th>
                    <th>Time Out</th>
                    <th>GPS Out</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($records as $i => $row): ?>
                  <tr>
                    <td><?= $i + 1 ?></td>
                    <td><?= htmlspecialchars($row['username']) ?></td>
                    <td><?= $row['date'] ?></td>
                    <td><?= $row['time_in'] ?? '<span class="text-muted">-</span>' ?></td>
                    <td><?= $row['gps_in'] ?? '<span class="text-muted">-</span>' ?></td>
                    <td><?= $row['time_out'] ?? '<span class="text-muted">-</span>' ?></td>
                    <td><?= $row['gps_out'] ?? '<span class="text-muted">-</span>' ?></td>
                    <td>
                      <a href="edit_attendance.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-outline-primary">✏️</a>
                      <a href="delete_attendance.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this record?')">🗑️</a>
                    </td>
                  </tr>
                  <?php endforeach; ?>
                  <?php if (empty($records)): ?>
                  <tr><td colspan="8" class="text-center text-muted">No records found.</td></tr>
                  <?php endif; ?>
                </tbody>
              </table>
            </div>
          </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>

<!-- JS Scripts -->
<script src="https://code.jquery.com/jquery-3.6.0.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>

<!-- DataTables + Export -->
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.print.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.7/index.global.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.7/index.global.min.js"></script>

<script>
  $(document).ready(function () {
    $('#siteTable').DataTable({
      dom: 'Bfrtip',
      buttons: ['csv', 'print'],
      order: [[2, 'desc']],
      pageLength: 10
    });
  });
</script>



<script>
  document.addEventListener('DOMContentLoaded', function () {
    const calendarEl = document.getElementById('attendanceCalendar');
    const calendar = new FullCalendar.Calendar(calendarEl, {
      initialView: 'dayGridMonth',
      height: 600,
      headerToolbar: {
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth,listWeek'
      },
      events: [
        <?php foreach ($records as $r): ?>
        {
          title: "<?= htmlspecialchars($r['username']) ?>",
          start: "<?= $r['date'] ?>",
          backgroundColor: 'green',
          borderColor: 'green'
        },
        <?php endforeach; ?>
      ]
    });
    calendar.render();
  });
</script>

</body>
</html>