<?php
require_once __DIR__ . '/../functions.php';
requireAdmin();
$page_title = 'Categories';
$db = db();

$editId = isset($_GET['edit']) ? (int)$_GET['edit'] : 0;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $slug = trim($_POST['slug'] ?? slugify($name));
    $description = trim($_POST['description'] ?? '');
    $parentId = !empty($_POST['parent_id']) ? (int)$_POST['parent_id'] : null;
    $sortOrder = (int)($_POST['sort_order'] ?? 0);
    $taxRate = (float)($_POST['tax_rate'] ?? 0);

    if ($editId) {
        $db->prepare("UPDATE categories SET name=?, slug=?, description=?, parent_id=?, sort_order=?, tax_rate=? WHERE id=?")
            ->execute([$name, $slug, $description, $parentId, $sortOrder, $taxRate, $editId]);
        flash('success', 'Category updated!');
    } else {
        $db->prepare("INSERT INTO categories (name, slug, description, parent_id, sort_order, tax_rate) VALUES (?, ?, ?, ?, ?, ?)")
            ->execute([$name, $slug, $description, $parentId, $sortOrder, $taxRate]);
        flash('success', 'Category created!');
    }
    header('Location: categories.php');
    exit;
}

if (isset($_GET['delete'])) {
    $db->prepare("DELETE FROM categories WHERE id = ?")->execute([(int)$_GET['delete']]);
    flash('success', 'Category deleted!');
    header('Location: categories.php');
    exit;
}

$categories = $db->query("SELECT c.*, (SELECT COUNT(*) FROM products WHERE category_id = c.id) as product_count FROM categories c ORDER BY c.sort_order")->fetchAll();
$parentCategories = $db->query("SELECT * FROM categories WHERE parent_id IS NULL ORDER BY sort_order")->fetchAll();

$editCategory = null;
if ($editId) {
    $stmt = $db->prepare("SELECT * FROM categories WHERE id = ?");
    $stmt->execute([$editId]);
    $editCategory = $stmt->fetch();
    if (!$editCategory) { header('Location: categories.php'); exit; }
}

require_once __DIR__ . '/../includes/admin-header.php';
?>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <div class="lg:col-span-2">
        <div class="bg-white rounded-xl border border-gray-200 overflow-hidden">
            <table class="w-full text-sm">
                <thead><tr class="text-left bg-gray-50 text-gray-500"><th class="px-4 py-3 font-medium">Name</th><th class="px-4 py-3 font-medium">Products</th><th class="px-4 py-3 font-medium">Tax Rate</th><th class="px-4 py-3 font-medium">Order</th><th class="px-4 py-3 font-medium"></th></tr></thead>
                <tbody>
                    <?php foreach ($categories as $c): ?>
                    <tr class="border-t">
                        <td class="px-4 py-3 font-medium text-gray-800"><?= h($c['name']) ?><?= $c['parent_id'] ? ' <span class="text-xs text-gray-400">(sub)</span>' : '' ?></td>
                        <td class="px-4 py-3"><?= $c['product_count'] ?></td>
                        <td class="px-4 py-3"><?= $c['tax_rate'] > 0 ? $c['tax_rate'] . '%' : '<span class="text-gray-400">Default</span>' ?></td>
                        <td class="px-4 py-3"><?= $c['sort_order'] ?></td>
                        <td class="px-4 py-3 flex gap-2">
                            <a href="categories.php?edit=<?= $c['id'] ?>" class="text-primary-600 hover:underline text-sm">Edit</a>
                            <a href="categories.php?delete=<?= $c['id'] ?>" class="text-red-500 hover:underline text-sm" onclick="return confirm('Delete this category?')">Delete</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <div>
        <form method="POST" class="bg-white rounded-xl border border-gray-200 p-6">
            <h3 class="font-semibold text-gray-800 mb-4"><?= $editCategory ? 'Edit Category' : 'Add Category' ?></h3>
            <?php if ($editCategory): ?>
            <p class="text-sm text-gray-500 mb-4">Editing: <strong><?= h($editCategory['name']) ?></strong></p>
            <?php endif; ?>
            <div class="space-y-4">
                <input type="hidden" name="id" value="<?= $editCategory ? $editCategory['id'] : '' ?>">
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Name</label><input type="text" name="name" value="<?= h($editCategory['name'] ?? '') ?>" required class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary-500"></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Slug</label><input type="text" name="slug" value="<?= h($editCategory['slug'] ?? '') ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary-500" placeholder="Auto-generated"></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Parent Category</label>
                    <select name="parent_id" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary-500">
                        <option value="">None (Top Level)</option>
                        <?php foreach ($parentCategories as $pc): ?>
                        <option value="<?= $pc['id'] ?>" <?= $editCategory && $editCategory['parent_id'] == $pc['id'] ? 'selected' : '' ?>><?= h($pc['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Description</label><textarea name="description" rows="2" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary-500"><?= h($editCategory['description'] ?? '') ?></textarea></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Tax Rate (%)</label>
                    <input type="number" name="tax_rate" value="<?= h($editCategory['tax_rate'] ?? '0') ?>" step="0.01" min="0" max="100" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary-500">
                    <p class="text-xs text-gray-400 mt-1">Set 0 to use default rate (<?= TAX_RATE ?>%)</p>
                </div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Sort Order</label><input type="number" name="sort_order" value="<?= h($editCategory['sort_order'] ?? '0') ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary-500"></div>
                <button type="submit" class="w-full bg-primary-600 text-white py-2 rounded-lg text-sm font-semibold hover:bg-primary-700"><?= $editCategory ? 'Update Category' : 'Add Category' ?></button>
                <?php if ($editCategory): ?>
                <a href="categories.php" class="block text-center text-sm text-gray-500 hover:underline mt-2">Cancel</a>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>
<?php require_once __DIR__ . '/../includes/admin-footer.php'; ?>
