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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    if ($name !== '') {
        try {
            $pdo->prepare("INSERT INTO waste_reasons (name) VALUES (?)")->execute([$name]);
            flash('success', 'Reason added.');
        } catch (PDOException $ex) {
            flash('error', 'That reason already exists.');
        }
    }
    redirect('waste_reasons.php');
}

if (isset($_GET['toggle'])) {
    $pdo->prepare("UPDATE waste_reasons SET is_active = 1 - is_active WHERE id=?")->execute([$_GET['toggle']]);
    redirect('waste_reasons.php');
}

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

$pageTitle = 'Waste Reasons';
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-6">Waste & Breakage Reasons</h1>
<p class="text-slate-500 text-sm mb-6 max-w-xl">This is the dropdown list people choose from when recording waste, breakage,
  or spillage. Deactivating a reason keeps it on old records but hides it from the form going forward.</p>

<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">Add Reason</h2>
    <form method="POST" class="space-y-3">
      <input name="name" required placeholder="e.g. Fridge breakdown" 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">Add</button>
    </form>
  </div>

  <div class="md:col-span-2 overflow-x-auto">
  <div class="bg-white rounded-xl shadow-sm border border-slate-200">
    <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">Reason</th><th class="text-left px-5 py-2">Status</th>
        <th class="text-right px-5 py-2">Actions</th></tr></thead>
      <tbody>
      <?php foreach ($reasons as $r): ?>
        <tr class="border-t border-slate-100">
          <td class="px-5 py-2.5"><?= e($r['name']) ?></td>
          <td class="px-5 py-2.5">
            <span class="px-2 py-0.5 rounded-full text-xs <?= $r['is_active'] ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-200 text-slate-500' ?>">
              <?= $r['is_active'] ? 'Active' : 'Inactive' ?>
            </span>
          </td>
          <td class="px-5 py-2.5 text-right">
            <a href="?toggle=<?= $r['id'] ?>" class="text-slate-500 hover:underline"><?= $r['is_active'] ? 'Deactivate' : 'Activate' ?></a>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  </div>
</div>
<?php include __DIR__ . '/includes/footer.php'; ?>
