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

// Base URL for uploaded logos (same as for products/categories)
define('MEDIA_BASE_URL', 'https://admin.vocabpanda.com/admin_panel/assets/uploads/');

// Get brand ID and fetch the brand
$id = $_GET['id'] ?? null;
if (!$id) {
    header('Location: brands.php');
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM brands WHERE id = :id");
$stmt->execute([':id' => $id]);
$brand = $stmt->fetch();
if (!$brand) {
    setFlash('danger', 'Brand not found.');
    header('Location: brands.php');
    exit;
}

// ------------------------------------------------------------
// 2. Handle POST – redirect on success
// ------------------------------------------------------------
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    if ($name === '') {
        $errors[] = 'Brand name required.';
    }

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

    // Logo handling
    $logo = $brand['logo_url']; // existing value (could be full URL or just filename)

    if (!empty($_FILES['logo']['name'])) {
        $newLogoName = uploadFile('logo', ['image/jpeg', 'image/png', 'image/gif', 'image/webp'], '../assets/uploads/');
        if ($newLogoName === false) {
            $errors[] = 'Logo upload failed.';
        } else {
            // Remove old logo file (extract filename from full URL if needed)
            if ($logo) {
                $oldFile = extractFilename($logo);
                if ($oldFile) {
                    deleteFile('../assets/uploads/' . $oldFile);
                }
            }
            // Store new logo as full URL
            $logo = MEDIA_BASE_URL . $newLogoName;
        }
    } elseif (isset($_POST['remove_logo']) && $_POST['remove_logo'] == '1') {
        // Remove the logo entirely
        if ($logo) {
            $oldFile = extractFilename($logo);
            if ($oldFile) {
                deleteFile('../assets/uploads/' . $oldFile);
            }
        }
        $logo = null;
    }

    if (empty($errors)) {
        $stmt = $pdo->prepare("UPDATE brands SET name = :name, slug = :slug, logo_url = :logo WHERE id = :id");
        $stmt->execute([
            ':name' => $name,
            ':slug' => $slug,
            ':logo' => $logo,
            ':id'   => $id,
        ]);

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

    // If there are errors, we'll fall through to display the form (after the layout)
}

// ------------------------------------------------------------
// 3. Helper function to extract just the filename
// ------------------------------------------------------------
function extractFilename($path)
{
    if (filter_var($path, FILTER_VALIDATE_URL)) {
        return basename(parse_url($path, PHP_URL_PATH));
    }
    return $path; // Already a simple filename
}
?>

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

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

<?php if ($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'] ?? $brand['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'] ?? $brand['slug']) ?>">
                </div>
                <div class="col-md-6 mb-3">
                    <label for="logo" class="form-label">Logo</label>
                    <?php if ($brand['logo_url']): ?>
                        <div class="mb-2">
                            <!-- Use full URL directly (no ../assets/uploads/ prefix) -->
                            <img src="<?= htmlspecialchars($brand['logo_url']) ?>" width="60" class="rounded">
                            <div class="form-check mt-1">
                                <input class="form-check-input" type="checkbox" name="remove_logo" value="1" id="remove_logo">
                                <label class="form-check-label" for="remove_logo">Remove logo</label>
                            </div>
                        </div>
                    <?php endif; ?>
                    <input type="file" name="logo" id="logo" class="form-control" accept="image/*">
                    <small class="text-muted">Leave empty to keep current</small>
                </div>
            </div>
            <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Update Brand</button>
            <a href="brands.php" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
</div>

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