<?php
require_once __DIR__ . '/config/config.php';
require_role(['admin']); // superadmin always passes via require_role

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $id = $_POST['id'] ?? null;
    if ($name === '') {
        flash('error', 'Name is required.');
    } elseif ($id) {
        $pdo->prepare("UPDATE departments SET name=? WHERE id=?")->execute([$name, $id]);
        flash('success', 'Department updated.');
    } else {
        $pdo->prepare("INSERT INTO departments (name) VALUES (?)")->execute([$name]);
        flash('success', 'Department added.');
    }
    redirect('departments.php');
}

if (isset($_GET['delete'])) {
    $pdo->prepare("DELETE FROM departments WHERE id=?")->execute([$_GET['delete']]);
    flash('success', 'Department deleted.');
    redirect('departments.php');
}

$edit = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM departments WHERE id=?");
    $stmt->execute([$_GET['edit']]);
    $edit = $stmt->fetch();
}

$departments = $pdo->query("SELECT * FROM departments ORDER BY name")->fetchAll();

$pageTitle = 'Departments';
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-6">Departments</h1>

<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
  <div class="md:col-span-1 bg-white rounded-xl shadow-sm border border-slate-200 p-5 h-fit">
    <h2 class="font-semibold mb-4"><?= $edit ? 'Edit' : 'Add' ?> Department</h2>
    <form method="POST" class="space-y-3">
      <?php if ($edit): ?><input type="hidden" name="id" value="<?= $edit['id'] ?>"><?php endif; ?>
      <input name="name" required placeholder="Department name" value="<?= e($edit['name'] ?? '') ?>"
        class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
      <button class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-4 py-2 rounded-lg w-full">
        <?= $edit ? 'Update' : 'Add' ?>
      </button>
      <?php if ($edit): ?><a href="departments.php" class="block text-center text-sm text-slate-500">Cancel</a><?php endif; ?>
    </form>
  </div>

  <div class="md:col-span-2 bg-white rounded-xl shadow-sm border border-slate-200">
    <div class="overflow-x-auto"><table class="w-full text-sm">
      <thead class="bg-slate-50 text-slate-500 text-xs uppercase"><tr>
        <th class="text-left px-5 py-2">Name</th><th class="text-right px-5 py-2">Actions</th></tr></thead>
      <tbody>
      <?php foreach ($departments as $d): ?>
        <tr class="border-t border-slate-100">
          <td class="px-5 py-2.5"><?= e($d['name']) ?></td>
          <td class="px-5 py-2.5 text-right space-x-3">
            <a href="?edit=<?= $d['id'] ?>" class="text-blue-600 hover:underline">Edit</a>
            <a href="?delete=<?= $d['id'] ?>" onclick="return confirm('Delete this department?')" class="text-red-600 hover:underline">Delete</a>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table></div>
  </div>
</div>
<?php include __DIR__ . '/includes/footer.php'; ?>
