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

// Base URL for uploaded files (must match product pages)
define('MEDIA_BASE_URL', 'https://admin.vocabpanda.com/admin_panel/assets/uploads/');

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

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

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

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);

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

    // Icon handling
    $icon = $cat['icon_url']; // existing value (could be full URL or just filename)

    if (!empty($_FILES['icon']['name'])) {
        $newIconName = uploadFile('icon', ['image/jpeg', 'image/png', 'image/gif', 'image/webp'], '../assets/uploads/');
        if ($newIconName === false) {
            $errors[] = 'Icon upload failed.';
        } else {
            // Delete old icon (extract filename from full URL if needed)
            if ($icon) {
                $oldFile = extractFilename($icon);
                if ($oldFile) deleteFile('../assets/uploads/' . $oldFile);
            }
            // Store full URL
            $icon = MEDIA_BASE_URL . $newIconName;
        }
    } elseif (isset($_POST['remove_icon']) && $_POST['remove_icon'] == '1') {
        // Remove icon completely
        if ($icon) {
            $oldFile = extractFilename($icon);
            if ($oldFile) deleteFile('../assets/uploads/' . $oldFile);
        }
        $icon = null;
    }

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

        setFlash('success', 'Category updated.');
        header('Location: categories.php');
        exit;
    }
    // If there are errors, fall through to the form
}

// ------------------------------------------------------------
// 3. Reusable helper to get just the filename from a path/URL
// ------------------------------------------------------------
function extractFilename($path) {
    if (filter_var($path, FILTER_VALIDATE_URL)) {
        return basename(parse_url($path, PHP_URL_PATH));
    }
    return $path; // It's already a simple filename
}
?>

<?php
// ------------------------------------------------------------
// 4. Now include the layout (only if we haven't redirected)
// ------------------------------------------------------------
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">Edit Category</h1>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <ul class="mb-0"><?php foreach ($errors as $e) echo '<li>'.htmlspecialchars($e).'</li>'; ?></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'] ?? $cat['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'] ?? $cat['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 —</option>
                        <?php foreach ($parents as $p): ?>
                            <option value="<?= $p['id'] ?>" <?= ($_POST['parent_id'] ?? $cat['parent_id']) == $p['id'] ? 'selected' : '' ?> <?= $p['id'] == $cat['id'] ? 'disabled' : '' ?>><?= htmlspecialchars($p['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <small class="text-muted">Cannot choose itself as parent.</small>
                </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'] ?? $cat['sort_order']) ?>">
                </div>
                <div class="col-md-3 mb-3">
                    <label for="icon" class="form-label">Icon (image)</label>
                    <?php if ($cat['icon_url']): ?>
                        <div class="mb-2">
                            <!-- Use full URL directly -->
                            <img src="<?= htmlspecialchars($cat['icon_url']) ?>" width="60" class="rounded">
                            <div class="form-check mt-1">
                                <input class="form-check-input" type="checkbox" name="remove_icon" value="1" id="remove_icon">
                                <label class="form-check-label" for="remove_icon">Remove icon</label>
                            </div>
                        </div>
                    <?php endif; ?>
                    <input type="file" name="icon" id="icon" 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 Category</button>
            <a href="categories.php" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
</div>

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