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

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

$controller_id = $_SESSION['user_id'];
$username = $_SESSION['username'] ?? 'Controller';

$from = $_GET['from'] ?? '';
$to = $_GET['to'] ?? '';

$where = "WHERE cr.controller_id = ?";
$params = [$controller_id];

if ($from && $to) {
  $where .= " AND cr.shift_date BETWEEN ? AND ?";
  $params[] = $from;
  $params[] = $to;
}

$stmt = $pdo->prepare("
  SELECT cr.*, s.site_name 
  FROM controller_roster cr
  JOIN sites s ON cr.site_id = s.id
  $where
  ORDER BY cr.shift_date DESC
");
$stmt->execute($params);
$rosters = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html>
<head>
  <title>My Assigned Shifts</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">

<div class="container mt-4">
  <h4 class="mb-3">📅 <?= htmlspecialchars($username) ?> - Assigned Shifts</h4>

  <!-- 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="<?= htmlspecialchars($from) ?>">
    </div>
    <div class="col-md-3">
      <label>To Date</label>
      <input type="date" name="to" class="form-control" value="<?= htmlspecialchars($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_my_roster.php" class="btn btn-secondary">Reset</a>
    </div>
  </form>

  <div class="table-responsive">
    <table class="table table-bordered table-sm table-striped">
      <thead class="table-dark">
        <tr>
          <th>#</th>
          <th>Date</th>
          <th>Site</th>
          <th>Shift</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($rosters as $i => $r): ?>
        <tr>
          <td><?= $i + 1 ?></td>
          <td><?= date('d M Y', strtotime($r['shift_date'])) ?></td>
          <td><?= htmlspecialchars($r['site_name']) ?></td>
          <td><?= ucfirst($r['shift_type']) ?> Shift</td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($rosters)): ?>
        <tr><td colspan="4" class="text-center text-muted">No shifts found for this date range.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

</body>
</html>
