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

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

// Handle Update Request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update'])) {
    $attendance_id = $_POST['attendance_id'];
    $controller_id = $_POST['controller_id'];
    $date = $_POST['date'];
    $time_in = $_POST['time_in'];
    $time_out = $_POST['time_out'] !== '' ? $_POST['time_out'] : null;

    $stmt = $pdo->prepare("
        UPDATE controller_attendance
        SET controller_id = :controller_id,
            date = :date,
            time_in = :time_in,
            time_out = :time_out
        WHERE id = :id
    ");
    $stmt->execute([
        ':controller_id' => $controller_id,
        ':date' => $date,
        ':time_in' => $time_in,
        ':time_out' => $time_out,
        ':id' => $attendance_id
    ]);

    $_SESSION['message'] = "Attendance record updated successfully.";
    header("Location: edit_controller_attendance.php");
    exit;
}

// Fetch Controllers
$controllers = $pdo->query("SELECT id, username FROM users WHERE role = 'controller'")->fetchAll(PDO::FETCH_ASSOC);

// Fetch Attendance Records
$attendance_records = $pdo->query("
    SELECT ca.id, ca.controller_id, u.username, ca.date, ca.time_in, ca.time_out
    FROM controller_attendance ca
    JOIN users u ON ca.controller_id = u.id
    ORDER BY ca.date DESC, ca.time_in DESC
")->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta name="description" content="Controller Dashboard - CFS System OS">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Edit Controller Attendance</title>
  <link rel="stylesheet" href="../assets/css/controller_dashboard.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.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.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">
          <h4>🕒 Edit Controller Attendance</h4>
          <hr>

          <?php if (isset($_SESSION['message'])): ?>
            <div class="alert alert-success">
              <?= htmlspecialchars($_SESSION['message']) ?>
            </div>
          <?php unset($_SESSION['message']); endif; ?>

          <div class="table-responsive">
            <table id="attendanceTable" class="table table-bordered table-striped small">
              <thead class="table-dark">
                  <tr>
                      <th>Controller Name</th>
                      <th>Date</th>
                      <th>Time In</th>
                      <th>Time Out</th>
                      <th>Status</th>
                      <th>Action</th>
                  </tr>
              </thead>
                    <tbody>
                    <?php foreach ($attendance_records as $record): ?>
                        <?php
                            $formatted_time_in = $record['time_in'] ? date('H:i', strtotime($record['time_in'])) : '';
                            $formatted_time_out = $record['time_out'] ? date('H:i', strtotime($record['time_out'])) : '';
                        ?>
                        <tr>
                            <form method="post" action="">
                                <td>
                                    <select name="controller_id" class="form-select" required>
                                        <?php foreach ($controllers as $controller): ?>
                                            <option value="<?= $controller['id'] ?>" <?= $controller['id'] == $record['controller_id'] ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($controller['username']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                                <td><input type="date" name="date" class="form-control" value="<?= $record['date'] ?>" required></td>
                                <td><input type="time" name="time_in" class="form-control" value="<?= $formatted_time_in ?>" required></td>
                                <td><input type="time" name="time_out" class="form-control" value="<?= $formatted_time_out ?>"></td>
                                <td>
                                    <?php if (is_null($record['time_out'])): ?>
                                        <span class="badge bg-warning text-dark">Active</span>
                                    <?php else: ?>
                                        <span class="badge bg-success">Completed</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <input type="hidden" name="attendance_id" value="<?= $record['id'] ?>">
                                    <button type="submit" name="update" class="btn btn-primary btn-sm">Update</button>
                                </td>
                            </form>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
          </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>