<?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 – redirect on success
// ------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $errors = [];

    if ($name === '') {
        $errors[] = 'Brand name required.';
    }

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

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

    if (empty($errors)) {
        $stmt = $pdo->prepare("INSERT INTO brands (name, slug, logo_url) VALUES (:name, :slug, :logo)");
        $stmt->execute([':name' => $name, ':slug' => $slug, ':logo' => $logo]);

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

    // If there are errors, we’ll continue to display the form (after the layout)
}
?>

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

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

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
        <ul class="mb-0">
            <?php foreach ($errors as $e): ?>
                <li><?= htmlspecialchars($e) ?></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</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="logo" class="form-label">Logo (image)</label>
                    <input type="file" name="logo" id="logo" class="form-control" accept="image/*">
                </div>
            </div>
            <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Save Brand</button>
            <a href="brands.php" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
</div>

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