<?php
require_once __DIR__ . '/admin_header.php';

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $slug = isset($_POST['slug']) ? trim($_POST['slug']) : '';
    
    // Convert slug to lowercase URL-friendly structure if manual entry was messy
    $slug = preg_replace('/[^a-z0-9\-]/', '', strtolower(str_replace(' ', '-', $slug)));

    if (empty($name) || empty($slug)) {
        $error = 'Both Name and Slug are mandatory fields.';
    } else {
        try {
            // Check if slug is unique
            $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM categories WHERE slug = ?");
            $stmt_check->execute([$slug]);
            if ($stmt_check->fetchColumn() > 0) {
                $error = 'A category with this slug already exists. Please choose a unique slug.';
            } else {
                $image_filename = '';

                // Handle Image File Upload
                if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
                    $file_tmp = $_FILES['image']['tmp_name'];
                    $file_name = $_FILES['image']['name'];
                    $file_size = $_FILES['image']['size'];
                    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                    
                    $allowed_exts = ['png', 'jpg', 'jpeg', 'webp'];
                    
                    if (!in_array($file_ext, $allowed_exts)) {
                        $error = 'Invalid image type. Only PNG, JPG, JPEG, and WEBP formats are accepted.';
                    } elseif ($file_size > 5 * 1024 * 1024) { // 5MB cap
                        $error = 'Image file size is too large. Keep uploads under 5 megabytes.';
                    } else {
                        // Create unique target filename
                        $image_filename = 'cat_' . time() . '_' . uniqid() . '.' . $file_ext;
                        $upload_dir = __DIR__ . '/../assets/images/';
                        
                        if (!is_dir($upload_dir)) {
                            mkdir($upload_dir, 0755, true);
                        }

                        if (!move_uploaded_file($file_tmp, $upload_dir . $image_filename)) {
                            $error = 'Failed to save uploaded image. Check directory write permissions.';
                            $image_filename = '';
                        }
                    }
                }

                if (empty($error)) {
                    // Insert category
                    $stmt_insert = $pdo->prepare("INSERT INTO categories (name, image, slug) VALUES (?, ?, ?)");
                    $stmt_insert->execute([$name, $image_filename, $slug]);
                    
                    $success = 'Category added successfully! Redirecting back...';
                    echo "<script>setTimeout(() => { window.location.href = 'categories.php'; }, 1500);</script>";
                }
            }
        } catch (Exception $e) {
            $error = 'Database transaction failed: ' . $e->getMessage();
        }
    }
}
?>

<div class="row mb-4">
    <div class="col-12">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                <li class="breadcrumb-item"><a href="categories.php">Categories</a></li>
                <li class="breadcrumb-item active" aria-current="page">Add Category</li>
            </ol>
        </nav>
        <h2 class="text-white">Create Category</h2>
        <p class="text-muted small">Establish a new product classification with customized assets.</p>
    </div>
</div>

<div class="row justify-content-center">
    <div class="col-lg-8">
        <div class="admin-card">
            
            <?php if (!empty($error)): ?>
                <div class="alert alert-danger border-danger bg-dark text-danger rounded-3 py-2 px-3 small mb-4" role="alert">
                    <i class="fa-solid fa-circle-exclamation me-2"></i> <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>

            <?php if (!empty($success)): ?>
                <div class="alert alert-success border-success bg-dark text-success rounded-3 py-2 px-3 small mb-4" role="alert">
                    <i class="fa-solid fa-circle-check me-2"></i> <?php echo htmlspecialchars($success); ?>
                </div>
            <?php endif; ?>

            <form action="category_add.php" method="POST" enctype="multipart/form-data">
                <div class="row g-3">
                    <!-- Category Name -->
                    <div class="col-md-6">
                        <label for="name" class="form-label text-muted small text-uppercase fw-bold">Category Name</label>
                        <input type="text" class="form-control" id="name" name="name" required placeholder="e.g. Footwear" onkeyup="generateSlug(this.value)">
                    </div>

                    <!-- Category Slug -->
                    <div class="col-md-6">
                        <label for="slug" class="form-label text-muted small text-uppercase fw-bold">Slug URL Reference</label>
                        <input type="text" class="form-control" id="slug" name="slug" required placeholder="e.g. footwear">
                        <div class="form-text text-muted" style="font-size: 0.7rem;">Only alphanumeric characters and hyphens allowed.</div>
                    </div>

                    <!-- Image upload -->
                    <div class="col-12 mt-4">
                        <label for="image" class="form-label text-muted small text-uppercase fw-bold">Arched Cover Banner Image</label>
                        <input type="file" class="form-control" id="image" name="image" accept="image/*" onchange="previewFile()">
                        <div class="form-text text-muted" style="font-size: 0.7rem;">Select a premium 3:4 portrait or high-resolution cover photo. JPG, PNG, WEBP only. Max 5MB.</div>
                        
                        <!-- Image Preview block -->
                        <div id="preview-container" class="mt-3 d-none">
                            <span class="d-block text-muted small mb-2 text-uppercase fw-bold" style="font-size: 0.65rem;">Image Asset Preview:</span>
                            <img id="image-preview" src="#" alt="Preview" class="rounded" style="max-width: 150px; height: 180px; object-fit: cover; border: 1px solid var(--border-gray);">
                        </div>
                    </div>

                    <!-- Actions -->
                    <div class="col-12 mt-5 border-top border-dark pt-4 d-flex gap-3 justify-content-end">
                        <a href="categories.php" class="btn btn-outline-secondary rounded-pill px-4 py-2 text-uppercase tracking-wider fw-bold" style="font-size: 0.75rem; border-color: var(--border-gray);">
                            Cancel
                        </a>
                        <button type="submit" class="btn-luxury px-4 py-2">
                            Save Category Asset <i class="fa-solid fa-cloud-arrow-up ms-2"></i>
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Sluggify name value into input
function generateSlug(text) {
    const slug = text.toString().toLowerCase()
        .replace(/\s+/g, '-')           // Replace spaces with -
        .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
        .replace(/\-\-+/g, '-')         // Replace multiple - with single -
        .replace(/^-+/, '')             // Trim - from start
        .replace(/-+$/, '');            // Trim - from end
    document.getElementById('slug').value = slug;
}

// Live preview image before upload
function previewFile() {
    const preview = document.getElementById('image-preview');
    const container = document.getElementById('preview-container');
    const file = document.getElementById('image').files[0];
    const reader = new FileReader();

    reader.addEventListener("load", function () {
        preview.src = reader.result;
        container.classList.remove('d-none');
    }, false);

    if (file) {
        reader.readAsDataURL(file);
    }
}
</script>

<?php
require_once __DIR__ . '/admin_footer.php';
?>
