<?php
$adminTitle = 'Categories';
require_once __DIR__ . '/includes/header.php';

// Handle save
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id    = (int)($_POST['id'] ?? 0);
    $name  = sanitize($_POST['name'] ?? '');
    $slug  = slugify($name);
    $desc  = sanitize($_POST['description'] ?? '');
    $icon  = sanitize($_POST['icon'] ?? '');
    $sort  = (int)($_POST['sort_order'] ?? 0);
    $active = isset($_POST['is_active']) ? 1 : 0;

    // Handle image
    $image = $_POST['existing_image'] ?? null;
    $uploadError = '';
    if (!empty($_FILES['image']['tmp_name'])) {
        $res = handleFileUpload($_FILES['image'], 'categories', ALLOWED_IMAGE_TYPES);
        if ($res['success']) {
            $image = $res['filename'];
        } else {
            $uploadError = ' Image upload failed: ' . $res['error'];
        }
    }

    if ($id > 0) {
        Database::execute("UPDATE categories SET name=?,slug=?,description=?,icon=?,image=?,sort_order=?,is_active=? WHERE id=?",
            [$name,$slug,$desc,$icon,$image,$sort,$active,$id]);
        $_SESSION['flash'][$uploadError ? 'warning' : 'success'] = 'Category updated.' . $uploadError;
    } else {
        // Ensure unique slug
        if (Database::fetchOne("SELECT id FROM categories WHERE slug=?", [$slug])) $slug .= '-'.time();
        Database::insert("INSERT INTO categories (name,slug,description,icon,image,sort_order,is_active) VALUES (?,?,?,?,?,?,?)",
            [$name,$slug,$desc,$icon,$image,$sort,$active]);
        $_SESSION['flash'][$uploadError ? 'warning' : 'success'] = 'Category added.' . $uploadError;
    }
    header('Location: /admin/categories.php');
    exit;
}

if (isset($_GET['delete'])) {
    Database::execute("UPDATE categories SET is_active=0 WHERE id=?", [(int)$_GET['delete']]);
    $_SESSION['flash']['success'] = 'Category deactivated.';
    header('Location: /admin/categories.php');
    exit;
}

$categories = Database::fetchAll("SELECT * FROM categories ORDER BY sort_order, name");
$editing = isset($_GET['edit']) ? Database::fetchOne("SELECT * FROM categories WHERE id=?", [(int)$_GET['edit']]) : null;
?>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
  <!-- Form -->
  <div class="card-dark p-5">
    <h3 class="font-semibold mb-4"><?= $editing ? 'Edit Category' : 'Add Category' ?></h3>
    <form method="POST" enctype="multipart/form-data" class="space-y-3">
      <input type="hidden" name="id" value="<?= $editing['id'] ?? '' ?>">
      <input type="hidden" name="existing_image" value="<?= e($editing['image'] ?? '') ?>">
      <div>
        <label class="text-xs text-gray-400 block mb-1">Name *</label>
        <input type="text" name="name" required value="<?= e($editing['name'] ?? '') ?>">
      </div>
      <div>
        <label class="text-xs text-gray-400 block mb-1">Description</label>
        <textarea name="description" rows="2"><?= e($editing['description'] ?? '') ?></textarea>
      </div>
      <div class="grid grid-cols-2 gap-2">
        <div><label class="text-xs text-gray-400 block mb-1">Icon (emoji)</label><input type="text" name="icon" value="<?= e($editing['icon'] ?? '') ?>" placeholder="⚙️"></div>
        <div><label class="text-xs text-gray-400 block mb-1">Sort Order</label><input type="number" name="sort_order" value="<?= $editing['sort_order'] ?? 0 ?>"></div>
      </div>
      <div>
        <label class="text-xs text-gray-400 block mb-1">Image</label>
        <input type="file" name="image" accept="image/*" style="width:auto">
        <?php if (!empty($editing['image'])): ?><img src="/uploads/<?= e($editing['image']) ?>" class="mt-1 h-10 object-contain"><?php endif; ?>
      </div>
      <label class="flex items-center gap-2 text-sm">
        <input type="checkbox" name="is_active" value="1" <?= ($editing['is_active'] ?? 1) ? 'checked' : '' ?> style="width:auto">
        Active
      </label>
      <div class="flex gap-2">
        <button class="btn-primary text-sm">Save</button>
        <?php if ($editing): ?><a href="/admin/categories.php" class="btn-outline text-sm">Cancel</a><?php endif; ?>
      </div>
    </form>
  </div>

  <!-- List -->
  <div class="lg:col-span-2 card-dark overflow-hidden">
    <div class="p-4 border-b border-navy-500 flex justify-between items-center">
      <h3 class="font-semibold text-sm">Categories (<?= count($categories) ?>)</h3>
    </div>
    <table class="data-table">
      <thead><tr><th>Name</th><th>Slug</th><th>Sort</th><th>Status</th><th></th></tr></thead>
      <tbody>
      <?php foreach ($categories as $cat): ?>
      <tr>
        <td class="text-sm font-medium"><?= $cat['icon'] ?? '' ?> <?= e($cat['name']) ?></td>
        <td class="text-xs font-mono text-gray-400"><?= e($cat['slug']) ?></td>
        <td class="text-xs"><?= $cat['sort_order'] ?></td>
        <td><?= statusBadge($cat['is_active'] ? 'in_stock' : 'out_of_stock') ?></td>
        <td class="flex gap-2">
          <a href="?edit=<?= $cat['id'] ?>" class="text-xs text-orange-500 hover:underline">Edit</a>
          <a href="?delete=<?= $cat['id'] ?>" class="text-xs text-red-400 hover:underline" onclick="return confirm('Deactivate?')">Del</a>
        </td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
