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

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

// Handle CREATE
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_roster'])) {
  $officer_id = $_POST['officer_id'];
  $duty_date = $_POST['duty_date'];
  $shift = $_POST['shift'];

  $stmt = $pdo->prepare("INSERT INTO command_center_roster (officer_id, duty_date, shift) VALUES (?, ?, ?)");
  $stmt->execute([$officer_id, $duty_date, $shift]);
  header("Location: roster_command_center.php");
  exit;
}

// Handle UPDATE
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_roster'])) {
  $id = $_POST['id'];
  $officer_id = $_POST['officer_id'];
  $duty_date = $_POST['duty_date'];
  $shift = $_POST['shift'];

  $stmt = $pdo->prepare("UPDATE command_center_roster SET officer_id = ?, duty_date = ?, shift = ? WHERE id = ?");
  $stmt->execute([$officer_id, $duty_date, $shift, $id]);
  header("Location: roster_command_center.php");
  exit;
}

// Handle DELETE
if (isset($_GET['delete'])) {
  $id = $_GET['delete'];
  $stmt = $pdo->prepare("DELETE FROM command_center_roster WHERE id = ?");
  $stmt->execute([$id]);
  header("Location: roster_command_center.php");
  exit;
}

$today = date('Y-m-d');
$officers = $pdo->query("SELECT id, username FROM users WHERE role = 'officer'")->fetchAll();
$roster = $pdo->prepare("SELECT r.*, u.username FROM command_center_roster r JOIN users u ON r.officer_id = u.id WHERE r.duty_date = ? ORDER BY r.shift");
$roster->execute([$today]);
$data = $roster->fetchAll();
?>

<!DOCTYPE html>
<html>
<head>
  <title>Command Center Roster | CFS System OS</title>
  <meta charset="UTF-8">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>

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

<div class="main-content p-4">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h4>🧭 Command Center Roster - <?= $today ?></h4>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createModal">➕ Add Duty</button>
  </div>

  <table class="table table-bordered table-hover align-middle">
    <thead class="table-dark">
      <tr>
        <th>#</th>
        <th>Officer</th>
        <th>Shift</th>
        <th>Status</th>
        <th>Time In</th>
        <th>Time Out</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($data as $i => $row): ?>
      <tr>
        <td><?= $i + 1 ?></td>
        <td><?= htmlspecialchars($row['username']) ?></td>
        <td><?= ucfirst($row['shift']) ?></td>
        <td><span class="badge bg-<?= $row['status'] === 'present' ? 'success' : ($row['status'] === 'absent' ? 'danger' : 'warning') ?>"><?= ucfirst($row['status']) ?></span></td>
        <td><?= $row['time_in'] ?? '-' ?></td>
        <td><?= $row['time_out'] ?? '-' ?></td>
        <td>
          <button class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#editModal<?= $row['id'] ?>">✏️ Edit</button>
          <a href="?delete=<?= $row['id'] ?>" onclick="return confirm('Delete this duty?')" class="btn btn-sm btn-danger">🗑️ Delete</a>
        </td>
      </tr>

      <!-- Edit Modal -->
      <div class="modal fade" id="editModal<?= $row['id'] ?>" tabindex="-1">
        <div class="modal-dialog">
          <div class="modal-content">
            <form method="post">
              <input type="hidden" name="id" value="<?= $row['id'] ?>">
              <input type="hidden" name="update_roster" value="1">
              <div class="modal-header">
                <h5 class="modal-title">Edit Duty</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
              </div>
              <div class="modal-body">
                <select name="officer_id" class="form-control mb-2" required>
                  <option value="">Select Officer</option>
                  <?php foreach ($officers as $o): ?>
                  <option value="<?= $o['id'] ?>" <?= $o['id'] == $row['officer_id'] ? 'selected' : '' ?>><?= $o['username'] ?></option>
                  <?php endforeach; ?>
                </select>
                <input type="date" name="duty_date" class="form-control mb-2" value="<?= $row['duty_date'] ?>" required>
                <select name="shift" class="form-control" required>
                  <option value="morning" <?= $row['shift'] == 'morning' ? 'selected' : '' ?>>Morning</option>
                  <option value="evening" <?= $row['shift'] == 'evening' ? 'selected' : '' ?>>Evening</option>
                  <option value="night" <?= $row['shift'] == 'night' ? 'selected' : '' ?>>Night</option>
                </select>
              </div>
              <div class="modal-footer">
                <button class="btn btn-primary">Save</button>
              </div>
            </form>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

<!-- Create Modal -->
<div class="modal fade" id="createModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <form method="post">
        <input type="hidden" name="create_roster" value="1">
        <div class="modal-header">
          <h5 class="modal-title">Add Duty</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <select name="officer_id" class="form-control mb-2" required>
            <option value="">Select Officer</option>
            <?php foreach ($officers as $o): ?>
            <option value="<?= $o['id'] ?>"><?= $o['username'] ?></option>
            <?php endforeach; ?>
          </select>
          <input type="date" name="duty_date" class="form-control mb-2" value="<?= $today ?>" required>
          <select name="shift" class="form-control" required>
            <option value="morning">Morning</option>
            <option value="evening">Evening</option>
            <option value="night">Night</option>
          </select>
        </div>
        <div class="modal-footer">
          <button class="btn btn-success">Add Duty</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
  const ctx = document.getElementById('trendChart').getContext('2d');
  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: <?= $trendLabels ?>,
      datasets: [{
        label: 'Check-ins',
        data: <?= $trendCounts ?>,
        backgroundColor: '#004080',
        borderRadius: 8
      }]
    },
    options: {
      responsive: true,
      scales: {
        y: {
          beginAtZero: true,
          ticks: { stepSize: 1 }
        }
      }
    }
  });
</script>


</body>
</html>
