<?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'] ?? '';

$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];
} else {
  $query .= " ORDER BY a.date DESC, a.time_in DESC";
}

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

// CSRF for edit
if (empty($_SESSION['csrf_token'])) {
  $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>

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

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

<?php include '../includes/topbar.php'; ?>
<?php include '../includes/sidebar.php'; ?>

<div class="content-wrapper">
  <div class="content-header">
    <div class="container-fluid">
      <h4 class="mb-3">🕒 Attendance Records</h4>
      <form class="row g-3 mb-3" method="get">
        <div class="col-auto">
          <label>From</label>
          <input type="date" name="from_date" value="<?= htmlspecialchars($from) ?>" class="form-control">
        </div>
        <div class="col-auto">
          <label>To</label>
          <input type="date" name="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>
    </div>
  </div>

  <div class="content">
    <div class="container-fluid">
      <div class="card">
        <div class="card-header">
          <h5 class="card-title">📋 Attendance Table</h5>
        </div>
        <div class="card-body 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>
                  <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editModal<?= $row['id'] ?>">✏️</button>
                  <a href="delete_attendance.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this record?')">🗑️</a>
                </td>
              </tr>

              <!-- Edit Modal -->
              <div class="modal fade" id="editModal<?= $row['id'] ?>" tabindex="-1">
                <div class="modal-dialog modal-lg">
                  <form class="edit-attendance-form" method="POST">
                    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                    <input type="hidden" name="id" value="<?= $row['id'] ?>">
                    <div class="modal-content">
                      <div class="modal-header">
                        <h5 class="modal-title">Edit: <?= htmlspecialchars($row['username']) ?></h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                      </div>
                      <div class="modal-body row g-3">
                        <div class="col-md-6">
                          <label>Date:</label>
                          <input type="text" class="form-control" value="<?= $row['date'] ?>" readonly>
                        </div>
                        <div class="col-md-6">
                          <label>Time In:</label>
                          <input type="time" name="time_in" class="form-control" value="<?= $row['time_in'] ?>">
                        </div>
                        <div class="col-md-6">
                          <label>Time Out:</label>
                          <input type="time" name="time_out" class="form-control" value="<?= $row['time_out'] ?>">
                        </div>
                        <div class="col-md-6">
                          <label>GPS In:</label>
                          <input type="text" name="gps_in" class="form-control" value="<?= $row['gps_in'] ?>">
                        </div>
                        <div class="col-md-6">
                          <label>GPS Out:</label>
                          <input type="text" name="gps_out" class="form-control" value="<?= $row['gps_out'] ?>">
                        </div>
                      </div>
                      <div class="modal-footer">
                        <button type="submit" class="btn btn-primary">Save</button>
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                      </div>
                    </div>
                  </form>
                </div>
              </div>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

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

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

  $(document).on('submit', '.edit-attendance-form', function (e) {
    e.preventDefault();
    const form = $(this);
    const modal = form.closest('.modal');
    $.post('update_attendance_ajax.php', form.serialize(), function () {
      bootstrap.Modal.getInstance(modal[0]).hide();
      location.reload();
    }).fail(() => alert('Failed to update record.'));
  });
</script>
</body>
</html>
