<?php
session_start();
$page_title = 'Menu Categories';
$active_nav = 'categories';
include("includes/header.php");

$success = $error = "";
$action  = $_GET['action'] ?? $_POST['action'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $is_admin) {
    $name = trim($_POST['name'] ?? '');
    $sort = (int)($_POST['sort_order'] ?? 0);
    $cid  = (int)($_POST['cat_id'] ?? 0);

    if (!$name) {
        $error = "Category name is required.";
    } elseif ($action === 'create') {
        $s = $conn->prepare("INSERT INTO categories(restaurant_id,name,sort_order) VALUES(?,?,?)");
        $s->bind_param("isi", $__rid, $name, $sort); $s->execute();
        $success = "Category '{$name}' created.";
    } elseif ($action === 'edit') {
        $s = $conn->prepare("UPDATE categories SET name=?,sort_order=? WHERE id=? AND restaurant_id=?");
        $s->bind_param("siii", $name, $sort, $cid, $__rid); $s->execute();
        $success = "Category updated.";
    }
}

if ($action === 'delete' && isset($_POST['id']) && $is_admin) {
    $cid = (int)$_POST['id'];
    // Unlink items from category before delete
    $ul = $conn->prepare("UPDATE menu_items SET category_id=NULL WHERE category_id=? AND restaurant_id=?");
    $ul->bind_param("ii", $cid, $__rid); $ul->execute();
    $d = $conn->prepare("DELETE FROM categories WHERE id=? AND restaurant_id=?");
    $d->bind_param("ii", $cid, $__rid); $d->execute();
    header("Location: categories.php?msg=deleted"); exit;
}

$msg = $_GET['msg'] ?? '';
if ($msg === 'deleted') $success = "Category deleted.";

$edit_cat = null;
if ($action === 'edit' && isset($_GET['id'])) {
    $edit_id = (int)$_GET['id'];
    $s = $conn->prepare("SELECT * FROM categories WHERE id=? AND restaurant_id=?");
    $s->bind_param("ii", $edit_id, $__rid); $s->execute();
    $edit_cat = $s->get_result()->fetch_assoc();
}

$cats = $conn->prepare("SELECT c.*, (SELECT COUNT(*) FROM menu_items WHERE category_id=c.id) as item_count FROM categories c WHERE c.restaurant_id=? ORDER BY c.sort_order, c.name");
$cats->bind_param("i", $__rid); $cats->execute();
$cats = $cats->get_result();
$total_cats = $cats->num_rows;
?>

<div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px">
  <div>
    <h1 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em;margin-bottom:3px">Menu Categories</h1>
    <p style="color:var(--text-muted);font-size:.875rem"><?php echo $total_cats; ?> categories — group your menu items for easy browsing</p>
  </div>
  <div style="display:flex;gap:8px">
    <?php if ($is_admin): ?>
    <a href="menu.php" class="btn btn-secondary btn-md">View Menu</a>
    <button class="btn btn-primary btn-md" onclick="openModal('catModal')">
      <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v8M8 12h8"/></svg>
      Add Category
    </button>
    <?php endif; ?>
  </div>
</div>

<?php if ($success): ?>
<div class="alert alert-success">
  <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
  <?php echo $success; ?>
</div>
<?php endif; ?>
<?php if ($error): ?>
<div class="alert alert-error">
  <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/></svg>
  <?php echo htmlspecialchars($error); ?>
</div>
<?php endif; ?>

<div class="alert alert-info">
  <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>
  Categories help customers browse your menu. Use <strong>Sort Order</strong> to control the display order (0 = first). Deleting a category uncategorizes its items — it doesn't delete them.
</div>

<div class="card">
  <?php if ($cats->num_rows === 0): ?>
    <div style="padding:60px;text-align:center;color:var(--text-muted)">
      <svg width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="var(--border)" stroke-width="1.5" stroke-linecap="round" style="margin:0 auto 14px;display:block"><path d="M3 3h7v7H3zM14 3h7v7h-7zM14 14h7v7h-7zM3 14h7v7H3z"/></svg>
      <p style="font-weight:700;margin-bottom:6px">No categories yet</p>
      <p style="font-size:.82rem;margin-bottom:16px">Categories help customers find items faster</p>
      <?php if ($is_admin): ?>
      <button class="btn btn-primary btn-md" onclick="openModal('catModal')">Create First Category</button>
      <?php endif; ?>
    </div>
  <?php else: ?>
  <div class="table-scroll">
<table class="data-table">
    <thead>
      <tr><th>Category</th><th>Sort Order</th><th>Menu Items</th><th>Actions</th></tr>
    </thead>
    <tbody>
    <?php while ($c = $cats->fetch_assoc()): ?>
    <tr>
      <td>
        <div style="display:flex;align-items:center;gap:10px">
          <div style="width:32px;height:32px;background:var(--primary-bg);border-radius:8px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" stroke-width="2" stroke-linecap="round"><path d="M3 3h7v7H3zM14 3h7v7h-7zM14 14h7v7h-7zM3 14h7v7H3z"/></svg>
          </div>
          <span style="font-weight:700"><?php echo htmlspecialchars($c['name']); ?></span>
        </div>
      </td>
      <td>
        <span style="font-size:.78rem;font-weight:600;background:var(--bg);padding:3px 10px;border-radius:8px"><?php echo $c['sort_order']; ?></span>
      </td>
      <td>
        <span style="font-weight:700"><?php echo $c['item_count']; ?></span>
        <?php if ($c['item_count'] > 0): ?>
        <a href="menu.php?cat=<?php echo $c['id']; ?>" style="font-size:.72rem;color:var(--primary);margin-left:8px;font-weight:600">View →</a>
        <?php endif; ?>
      </td>
      <td>
        <?php if ($is_admin): ?>
        <div style="display:flex;gap:6px">
          <a href="?action=edit&id=<?php echo $c['id']; ?>" class="btn btn-secondary btn-sm">Edit</a>
          <form method="POST" style="display:inline"
                onsubmit="return confirm('Delete <?php echo addslashes($c['name']); ?>? Items will be uncategorized.')">
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="id" value="<?php echo $c['id']; ?>">
            <button class="btn btn-danger btn-sm">Delete</button>
          </form>
        </div>
        <?php else: ?>
        <span style="font-size:.75rem;color:var(--text-light)">—</span>
        <?php endif; ?>
      </td>
    </tr>
    <?php endwhile; ?>
    </tbody>
  </table>
</div>
  <?php endif; ?>
</div>

<!-- Add / Edit Modal -->
<div class="modal-backdrop" id="catModal" <?php echo ($edit_cat ? 'style="display:flex"' : ''); ?>>
  <div class="modal">
    <div class="modal-header">
      <h3><?php echo $edit_cat ? 'Edit Category' : 'Add Category'; ?></h3>
      <?php if ($edit_cat): ?>
        <a href="categories.php" class="modal-close">
          <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        </a>
      <?php else: ?>
        <button class="modal-close" onclick="closeModal('catModal')">
          <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        </button>
      <?php endif; ?>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="<?php echo $edit_cat ? 'edit' : 'create'; ?>">
      <?php if ($edit_cat): ?>
      <input type="hidden" name="cat_id" value="<?php echo $edit_cat['id']; ?>">
      <?php endif; ?>
      <div class="modal-body">
        <div class="form-group">
          <label>Category Name *</label>
          <input type="text" name="name" class="form-control" required
                 value="<?php echo htmlspecialchars($edit_cat['name'] ?? ''); ?>"
                 placeholder="e.g. Starters, Main Course, Drinks, Desserts">
        </div>
        <div class="form-group" style="margin-bottom:0">
          <label>Sort Order</label>
          <input type="number" name="sort_order" class="form-control" min="0"
                 value="<?php echo $edit_cat['sort_order'] ?? 0; ?>">
          <div style="font-size:.72rem;color:var(--text-muted);margin-top:5px">Lower numbers appear first (0 = top of list)</div>
        </div>
      </div>
      <div class="modal-footer">
        <?php if ($edit_cat): ?>
          <a href="categories.php" class="btn btn-secondary btn-md">Cancel</a>
        <?php else: ?>
          <button type="button" class="btn btn-secondary btn-md" onclick="closeModal('catModal')">Cancel</button>
        <?php endif; ?>
        <button type="submit" class="btn btn-primary btn-md"><?php echo $edit_cat ? 'Save Changes' : 'Create Category'; ?></button>
      </div>
    </form>
  </div>
</div>

<?php include("includes/footer.php"); ?>
