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

$error = '';
$success = '';
$category = null;

if (!isset($_GET['id'])) {
    header("Location: categories.php");
    exit;
}

$cat_id = intval($_GET['id']);

// Fetch existing details
try {
    $stmt = $pdo->prepare("SELECT * FROM categories WHERE id = ?");
    $stmt->execute([$cat_id]);
    $category = $stmt->fetch();
    
    if (!$category) {
        header("Location: categories.php");
        exit;
    }
} catch (Exception $e) {
    $error = 'Error loading category: ' . $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $slug = isset($_POST['slug']) ? trim($_POST['slug']) : '';
    
    // Clean slug structure
    $slug = preg_replace('/[^a-z0-9\-]/', '', strtolower(str_replace(' ', '-', $slug)));

    if (empty($name) || empty($slug)) {
        $error = 'Both Name and Slug are required.';
    } else {
        try {
            // Check slug uniqueness except for current category
            $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM categories WHERE slug = ? AND id != ?");
            $stmt_check->execute([$slug, $cat_id]);
            if ($stmt_check->fetchColumn() > 0) {
                $error = 'A category with this slug already exists. Please choose a unique slug.';
            } else {
                $image_filename = $category['image']; // Default to current image

                // Handle Image File Upload if uploaded
                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) {
                        $error = 'Image file size is too large. Keep uploads under 5 megabytes.';
                    } else {
                        // Create unique target filename
                        $new_image_filename = 'cat_' . time() . '_' . uniqid() . '.' . $file_ext;
                        $upload_dir = __DIR__ . '/../assets/images/';
                        
                        if (move_uploaded_file($file_tmp, $upload_dir . $new_image_filename)) {
                            // Delete old image if it exists and is custom
                            if (!empty($category['image']) && file_exists($upload_dir . $category['image']) && strpos($category['image'], 'cat_') !== false) {
                                @unlink($upload_dir . $category['image']);
                            }
                            $image_filename = $new_image_filename;
                        } else {
                            $error = 'Failed to save new image.';
                        }
                    }
                }

                if (empty($error)) {
                    // Update category
                    $stmt_update = $pdo->prepare("UPDATE categories SET name = ?, image = ?, slug = ? WHERE id = ?");
                    $stmt_update->execute([$name, $image_filename, $slug, $cat_id]);
                    
                    $success = 'Category updated successfully! Redirecting back...';
                    // Reload local state
                    $category['name'] = $name;
                    $category['slug'] = $slug;
                    $category['image'] = $image_filename;
                    
                    echo "<script>setTimeout(() => { window.location.href = 'categories.php'; }, 1500);</script>";
                }
            }
        } catch (Exception $e) {
            $error = 'Database update 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">Edit Category</li>
            </ol>
        </nav>
        <h2 class="text-white">Refine Category Asset</h2>
        <p class="text-muted small">Update branding characteristics, names, and covers for "<?php echo htmlspecialchars($category['name'] ?? ''); ?>".</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_edit.php?id=<?php echo $cat_id; ?>" 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 value="<?php echo htmlspecialchars($category['name']); ?>" 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 value="<?php echo htmlspecialchars($category['slug']); ?>" placeholder="e.g. footwear">
                        <div class="form-text text-muted" style="font-size: 0.7rem;">Alphanumeric tokens and dashes only.</div>
                    </div>

                    <!-- Image Asset -->
                    <div class="col-12 mt-4">
                        <label for="image" class="form-label text-muted small text-uppercase fw-bold">Update Cover Photo</label>
                        <input type="file" class="form-control" id="image" name="image" accept="image/*" onchange="previewFile()">
                        <div class="form-text text-muted mb-3" style="font-size: 0.7rem;">Leave empty to retain the current image asset. PNG, JPG, WEBP. Max 5MB.</div>
                        
                        <!-- Previews Grid -->
                        <div class="row g-3">
                            <!-- Current Image -->
                            <?php if (!empty($category['image'])): ?>
                                <div class="col-6 col-sm-4">
                                    <span class="d-block text-muted small mb-2 text-uppercase fw-bold" style="font-size: 0.65rem;">Active Image Asset:</span>
                                    <img src="../assets/images/<?php echo htmlspecialchars($category['image']); ?>" alt="Current Image" class="rounded" style="max-width: 100%; height: 180px; object-fit: cover; border: 1px solid var(--border-gray);">
                                </div>
                            <?php endif; ?>

                            <!-- Live New Image Preview -->
                            <div id="preview-container" class="col-6 col-sm-4 d-none">
                                <span class="d-block text-muted small mb-2 text-uppercase fw-bold" style="font-size: 0.65rem;">Newly Selected Image:</span>
                                <img id="image-preview" src="#" alt="New Preview" class="rounded" style="max-width: 100%; height: 180px; object-fit: cover; border: 1px solid var(--accent-gold);">
                            </div>
                        </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 Changes <i class="fa-solid fa-check-double ms-2"></i>
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function generateSlug(text) {
    const slug = text.toString().toLowerCase()
        .replace(/\s+/g, '-')
        .replace(/[^\w\-]+/g, '')
        .replace(/\-\-+/g, '-')
        .replace(/^-+/, '')
        .replace(/-+$/, '');
    document.getElementById('slug').value = slug;
}

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';
?>
