<?php
// 1. Load DB + helpers before any HTML
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
requireLogin();

// 2. Handle POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name       = trim($_POST['name'] ?? '');
    $parent_id  = $_POST['parent_id'] ? (int)$_POST['parent_id'] : null;
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    $errors = [];

    if ($name === '') {
        $errors[] = 'Category name is required.';
    }
    $slug = trim($_POST['slug'] ?? '');
    if ($slug === '') {
        $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)));
    }

    $icon = null;
    if (!empty($_FILES['icon']['name'])) {
        $icon = uploadFile('icon', ['image/jpeg', 'image/png', 'image/gif', 'image/webp'], '../assets/uploads/');
        if ($icon === false) {
            $errors[] = 'Icon upload failed.';
        }
    }

    if (empty($errors)) {
        $stmt = $pdo->prepare("INSERT INTO categories (parent_id, name, slug, icon_url, sort_order)
                               VALUES (:parent_id, :name, :slug, :icon_url, :sort_order)");
        $stmt->execute([
            ':parent_id'  => $parent_id,
            ':name'       => $name,
            ':slug'       => $slug,
            ':icon_url'   => $icon,
            ':sort_order' => $sort_order,
        ]);

        setFlash('success', 'Category created successfully.');
        header('Location: categories.php');
        exit;
    }

    // If there are errors, fall through to the form (we'll include the layout below)
}
?>

<?php
// 3. Now include the layout (header, sidebar) because we didn't redirect
require_once '../includes/header.php';

// Fetch parent categories for dropdown
$parentStmt = $pdo->query("SELECT id, name FROM categories ORDER BY name");
$parents = $parentStmt->fetchAll();
?>

<h1 class="h2 mb-4">Add Category</h1>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?>
                <li><?= htmlspecialchars($err) ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="card shadow-sm">
    <div class="card-body">
        <form method="POST" enctype="multipart/form-data">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="name" class="form-label">Name *</label>
                    <input type="text" name="name" id="name" class="form-control" value="<?= htmlspecialchars($_POST['name'] ?? '') ?>" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label for="slug" class="form-label">Slug (auto‑generated if empty)</label>
                    <input type="text" name="slug" id="slug" class="form-control" value="<?= htmlspecialchars($_POST['slug'] ?? '') ?>">
                </div>
                <div class="col-md-6 mb-3">
                    <label for="parent_id" class="form-label">Parent Category</label>
                    <select name="parent_id" id="parent_id" class="form-select">
                        <option value="">— None (Top Level) —</option>
                        <?php foreach ($parents as $p): ?>
                            <option value="<?= $p['id'] ?>" <?= ($_POST['parent_id'] ?? '') == $p['id'] ? 'selected' : '' ?>><?= htmlspecialchars($p['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3 mb-3">
                    <label for="sort_order" class="form-label">Sort Order</label>
                    <input type="number" name="sort_order" id="sort_order" class="form-control" value="<?= htmlspecialchars($_POST['sort_order'] ?? '0') ?>">
                </div>
                <div class="col-md-3 mb-3">
                    <label for="icon" class="form-label">Icon (image)</label>
                    <input type="file" name="icon" id="icon" class="form-control" accept="image/*">
                </div>
            </div>
            <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Save Category</button>
            <a href="categories.php" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>