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

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

// Build filter query
$where = "WHERE u.role = 'controller'";
$params = [];

if (!empty($_GET['from']) && !empty($_GET['to'])) {
  $where .= " AND ca.date BETWEEN ? AND ?";
  $params[] = $_GET['from'];
  $params[] = $_GET['to'];
}

// Fetch attendance data
$stmt = $pdo->prepare("
  SELECT ca.*, u.username 
  FROM controller_attendance ca 
  JOIN users u ON ca.controller_id = u.id
  $where
  ORDER BY ca.date DESC
");
$stmt->execute($params);
$records = $stmt->fetchAll();

// Shift logic
function getShift($timeIn) {
  if (!$timeIn) return '-';
  $hour = (int)date('H', strtotime($timeIn));
  return ($hour >= 8 && $hour < 20) ? 'A Shift (08 AM - 08 PM)' : 'B Shift (08 PM - 08 AM)';
}
?>

<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="icon" href="../assets/images/logo.png" type="image/png">
<head>
  <title>Controller Attendance Records</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <link rel="stylesheet" href="../assets/css/controller_dashboard.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.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>

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

<div class="main-content" id="mainContent">
  <div class="container mt-4">
  

      <div class="container-fluid">
        <div class="wrapper">
          <div class="row">
            <div class="d-flex justify-content-between align-items-center mb-4">
              <h4 class="text-primary">🕒 Controller Attendance Records</h4>
            </div>
              <hr>
            
            <!-- Filter Form -->
            <form method="get" class="row g-2 mb-3">
              <div class="col-md-3">
                <label>From Date</label>
                <input type="date" name="from" class="form-control" value="<?= $_GET['from'] ?? '' ?>">
              </div>
              <div class="col-md-3">
                <label>To Date</label>
                <input type="date" name="to" class="form-control" value="<?= $_GET['to'] ?? '' ?>">
              </div>
              <div class="col-md-2 d-grid align-self-end">
                <button class="btn btn-primary">Filter</button>
              </div>
              <div class="col-md-2 d-grid align-self-end">
                <a href="view_controller_attendance.php" class="btn btn-secondary">Reset</a>
              </div>
            </form>

            <!-- Attendance Table -->
            <div class="table-responsive">
              <table id="attendanceTable" class="table table-bordered table-striped small">
                <thead class="table-dark">
                  <tr>
                    
                    <th>Controller</th>
                    <th>Date</th>
                    <th>Time In</th>
                    <th>Time Out</th>
                    <th>Shift</th>
                    <?php if ($_SESSION['role'] === 'admin'): ?>
                      <th>Action</th>
                    <?php endif; ?>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($records as $i => $r): ?>
                  <tr>
                    
                    <td><?= htmlspecialchars($r['username']) ?></td>
                    <td><?= date('d M Y', strtotime($r['date'])) ?></td>
                    <td><?= $r['time_in'] ? date('H:i', strtotime($r['time_in'])) : '<span class="text-muted">-</span>' ?></td>
                    <td><?= $r['time_out'] ? date('H:i', strtotime($r['time_out'])) : '<span class="text-muted">-</span>' ?></td>
                    <td><?= getShift($r['time_in']) ?></td>
                    <?php if ($_SESSION['role'] === 'admin'): ?>
                      <td>
                        <button class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#editModal<?= $r['id'] ?>">✏️</button>
                      </td>
                    <?php endif; ?>
                  </tr>
                  <?php endforeach; ?>
                  <?php if (empty($records)): ?>
                  <tr><td colspan="<?= $_SESSION['role'] === 'admin' ? '7' : '6' ?>" class="text-center text-muted">No attendance records found.</td></tr>
                  <?php endif; ?>
                </tbody>
              </table>
            </div>

            <!-- Admin Edit Modals -->
            <?php if ($_SESSION['role'] === 'admin'): ?>
              <?php foreach ($records as $r): ?>
                <div class="modal fade" id="editModal<?= $r['id'] ?>" tabindex="-1">
                  <div class="modal-dialog">
                    <form method="post" action="update_controller_attendance.php" class="modal-content">
                      <input type="hidden" name="id" value="<?= $r['id'] ?>">
                      <div class="modal-header">
                        <h5 class="modal-title">Edit Attendance - <?= htmlspecialchars($r['username']) ?></h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                      </div>
                      <div class="modal-body">
                        <label>Date</label>
                        <input type="date" name="date" class="form-control mb-2" value="<?= $r['date'] ?>" required>

                        <label>Time In</label>
                        <input type="datetime-local" name="time_in" class="form-control mb-2" value="<?= $r['time_in'] ?>">

                        <label>Time Out</label>
                        <input type="datetime-local" name="time_out" class="form-control mb-2" value="<?= $r['time_out'] ?>">
                      </div>
                      <div class="modal-footer">
                        <button class="btn btn-success btn-sm">Save Changes</button>
                      </div>
                    </form>
                  </div>
                </div>
              <?php endforeach; ?>
            <?php endif; ?>

          </div>
        </div>
      </div>
  </div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.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 src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
  $(document).ready(function () {
    $('#attendanceTable').DataTable({
      dom: 'Bfrtip',
      buttons: ['excelHtml5', 'print'],
      order: [[1, 'desc']]
    });
  });
  </script>
</body>
</html>
