<?php
include "include/db.php";
include "include/header.php";

$errors = [];
$success = '';
$category = null;

// Get category ID
$category_id = $_GET['id'] ?? 0;
$category_id = (int)$category_id;

if ($category_id <= 0) {
    die("Invalid category ID.");
}

// Fetch existing category
$stmt = $conn->prepare("SELECT * FROM blog_category WHERE id = ?");
$stmt->bind_param("i", $category_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    die("Blog category not found.");
}

$category = $result->fetch_assoc();
$stmt->close();

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_category'])) {
    $category_name = trim($_POST['category_name'] ?? '');
    $category_description = trim($_POST['category_description'] ?? '') ?: null;
    $category_status = trim($_POST['category_status'] ?? '') ?: null;

    // Validation
    if (empty($category_name)) {
        $errors[] = "Category Name is required.";
    }
    if ($category_status && !in_array($category_status, ['active', 'inactive'])) {
        $errors[] = "Status must be 'active' or 'inactive'.";
    }

    // Handle image upload (optional)
    $category_image_path = $category['image']; // Keep old image
    if (isset($_FILES['category_image']) && $_FILES['category_image']['error'] === UPLOAD_ERR_OK) {
        $image_name = $_FILES['category_image']['name'];
        $image_tmp = $_FILES['category_image']['tmp_name'];
        $image_ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
        $allowed_exts = ['jpg', 'jpeg', 'png', 'gif'];

        if (!in_array($image_ext, $allowed_exts)) {
            $errors[] = "Only JPG, JPEG, PNG, or GIF files are allowed.";
        } else {
            $upload_dir = 'uploads/';
            $new_image_path = $upload_dir . uniqid() . '.' . $image_ext;
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);

            if (move_uploaded_file($image_tmp, $new_image_path)) {
                if (!empty($category_image_path) && file_exists($category_image_path)) {
                    unlink($category_image_path);
                }
                $category_image_path = $new_image_path;
            } else {
                $errors[] = "Failed to upload image.";
            }
        }
    }

    // Update database if no errors
    if (empty($errors)) {
        $stmt = $conn->prepare("UPDATE blog_category SET name = ?, description = ?, image = ?, status = ?, updated_at = NOW() WHERE id = ?");
        $stmt->bind_param("ssssi", $category_name, $category_description, $category_image_path, $category_status, $category_id);

        if ($stmt->execute()) {
            $success = "Blog category updated successfully! Redirecting...";

            // Auto redirect after 2 seconds
            echo "<script>
                setTimeout(function() {
                    window.location.href = 'blog_category.php';
                }, 2000);
            </script>";
        } else {
            $errors[] = "Failed to update category: " . $conn->error;
        }
        $stmt->close();
    }
}
?>

<!-- Content -->
<div id="content" class="content ml-64 p-6 min-h-screen">
    <style>
        @import url('https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css');
        body { overflow-x: hidden; font-family: 'Inter', sans-serif; }
        .content { transition: margin-left 0.3s ease; }
        .form-section { transition: transform 0.2s ease, box-shadow 0.2s ease; }
        .form-section:hover { transform: translateY(-5px); box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15); }
        .top-nav { background: linear-gradient(90deg, #1F2937, #374151); }
        input, textarea, select { transition: all 0.2s ease; }
        input:focus, textarea:focus, select:focus { ring: 2px solid #F59E0B; }
        .error { color: #DC2626; }
        .success { color: #10B981; font-size: 1.25rem; font-weight: bold; text-align: center; padding: 1rem; background: #ECFDF5; border-radius: 8px; }
        .preview-img { max-width: 150px; height: auto; border-radius: 8px; margin-top: 10px; }
        @media (max-width: 768px) {
            .content { margin-left: 0; }
            .content.open { margin-left: 0; }
        }
        @media (min-width: 769px) {
            .content { margin-left: 250px; }
        }
    </style>

    <!-- Top Nav -->
    <nav class="top-nav sticky top-0 text-white p-4 flex justify-between items-center shadow-lg z-40">
        <div class="logo text-2xl font-bold">CourseLMS Admin</div>
        <div class="search flex-1 max-w-xs mx-4">
            <input type="text" placeholder="Search blog categories..." class="w-full p-2 border border-gray-300 rounded-md bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-yellow-500">
        </div>
        <div class="right-nav flex items-center gap-4">
            <i class="fas fa-bell text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer" title="Notifications"></i>
            <i class="fas fa-envelope text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer" title="Messages"></i>
            <div class="profile flex items-center gap-2">
                <img src="https://via.placeholder.com/40" alt="Profile" class="w-10 h-10 rounded-full">
                <span class="text-white">Admin</span>
            </div>
            <i id="toggle" class="fas fa-bars text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer" title="Toggle Menu"></i>
        </div>
    </nav>

    <!-- Edit Form -->
    <div class="max-w-2xl mx-auto my-6">
        <div class="form-section bg-white p-6 rounded-lg shadow-md">
            <h2 class="text-2xl font-bold text-gray-900 mb-6 text-center">Edit Blog Category</h2>

            <!-- Success Message with Auto Redirect -->
            <?php if ($success): ?>
                <div class="success mb-6">
                    <?php echo htmlspecialchars($success); ?>
                </div>
            <?php endif; ?>

            <!-- Error Messages -->
            <?php if (!empty($errors)): ?>
                <ul class="error mb-4">
                    <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>

            <!-- Only show form if NOT successfully updated -->
            <?php if (!$success): ?>
            <form method="POST" enctype="multipart/form-data" class="space-y-5">
                <input type="hidden" name="update_category" value="1">

                <div>
                    <label for="category_name" class="block text-sm font-medium text-gray-700">Category Name</label>
                    <input type="text" id="category_name" name="category_name" value="<?php echo htmlspecialchars($category['name']); ?>" class="w-full p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                </div>

                <div>
                    <label for="category_description" class="block text-sm font-medium text-gray-700">Description (Optional)</label>
                    <textarea id="category_description" name="category_description" rows="4" class="w-full p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500"><?php echo htmlspecialchars($category['description'] ?? ''); ?></textarea>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700">Current Image</label>
                    <?php if ($category['image']): ?>
                        <img src="<?php echo htmlspecialchars($category['image']); ?>" alt="Current Image" class="preview-img">
                        <p class="text-xs text-gray-500 mt-1">Leave blank to keep current image.</p>
                    <?php else: ?>
                        <p class="text-gray-500">No image uploaded.</p>
                    <?php endif; ?>
                </div>

                <div>
                    <label for="category_image" class="block text-sm font-medium text-gray-700">Update Image (Optional)</label>
                    <input type="file" id="category_image" name="category_image" accept="image/*" class="w-full p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500">
                </div>

                <div>
                    <label for="category_status" class="block text-sm font-medium text-gray-700">Status</label>
                    <select id="category_status" name="category_status" class="w-full p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500">
                        <option value="">Select status</option>
                        <option value="active" <?php echo ($category['status'] == 'active') ? 'selected' : ''; ?>>Active</option>
                        <option value="inactive" <?php echo ($category['status'] == 'inactive') ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>

                <div class="flex gap-3">
                    <button type="submit" class="flex-1 bg-yellow-500 text-white p-3 rounded-md hover:bg-yellow-600 transition-colors font-medium">Update Category</button>
                    <a href="blog_category.php" class="flex-1 bg-gray-500 text-white p-3 rounded-md hover:bg-gray-600 transition-colors text-center font-medium">Cancel</a>
                </div>
            </form>
            <?php endif; ?>

            <!-- Show "Go Back" if already updated -->
            <?php if ($success): ?>
                <div class="text-center mt-6">
                    <a href="blog_category.php" class="text-blue-600 hover:underline">← Back to Blog Categories</a>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php
include "include/footer.php";
$conn->close();
?>