<?php
require_once __DIR__ . '/config/config.php';
require_permission('outlets.manage');

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

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

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

$departments = $pdo->query("SELECT * FROM departments ORDER BY name")->fetchAll();
$outlets = $pdo->query("SELECT o.*, d.name dept_name FROM outlets o LEFT JOIN departments d ON d.id=o.department_id ORDER BY o.name")->fetchAll();

$pageTitle = 'Outlets';
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-6">Outlets</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' ?> Outlet</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="Outlet name (e.g. Main Bar)" value="<?= e($edit['name'] ?? '') ?>"
        class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
      <select name="department_id" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
        <option value="">-- Department (optional) --</option>
        <?php foreach ($departments as $d): ?>
          <option value="<?= $d['id'] ?>" <?= ($edit['department_id'] ?? null)==$d['id']?'selected':'' ?>><?= e($d['name']) ?></option>
        <?php endforeach; ?>
      </select>
      <input name="location" placeholder="Location" value="<?= e($edit['location'] ?? '') ?>"
        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="outlets.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-left px-5 py-2">Department</th>
        <th class="text-left px-5 py-2">Location</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 ($outlets as $o): ?>
        <tr class="border-t border-slate-100">
          <td class="px-5 py-2.5"><?= e($o['name']) ?></td>
          <td class="px-5 py-2.5"><?= e($o['dept_name'] ?? '—') ?></td>
          <td class="px-5 py-2.5"><?= e($o['location']) ?></td>
          <td class="px-5 py-2.5">
            <span class="px-2 py-0.5 rounded-full text-xs <?= $o['is_active'] ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-200 text-slate-500' ?>">
              <?= $o['is_active'] ? 'Active' : 'Inactive' ?>
            </span>
          </td>
          <td class="px-5 py-2.5 text-right space-x-3">
            <a href="?edit=<?= $o['id'] ?>" class="text-blue-600 hover:underline">Edit</a>
            <a href="?toggle=<?= $o['id'] ?>" class="text-slate-500 hover:underline"><?= $o['is_active'] ? 'Deactivate' : 'Activate' ?></a>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table></div>
  </div>
</div>
<?php include __DIR__ . '/includes/footer.php'; ?>
