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

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

// Fetch active blog categories
$categories = $conn->query("SELECT id, name FROM blog_category WHERE status = 'active' ORDER BY name ASC")->fetch_all(MYSQLI_ASSOC);

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_blog'])) {
    $title = trim($_POST['title'] ?? '');
    $slug = trim($_POST['slug'] ?? '');
    $content = $_POST['content'] ?? '';
    $category_id = (int)($_POST['category_id'] ?? 0);
    $meta_title = trim($_POST['meta_title'] ?? '');
    $meta_description = trim($_POST['meta_description'] ?? '');

    // Validation
    if (empty($title)) $errors[] = "Title is required.";
    if (empty($content)) $errors[] = "Content is required.";
    if ($category_id <= 0) $errors[] = "Please select a category.";

    // Auto-generate slug if empty
    if (empty($slug) && !empty($title)) {
        $slug = strtolower(preg_replace('/[^a-z0-9-]+/', '-', preg_replace('/\s+/', '-', $title)));
        $slug = trim($slug, '-');
    }

    // Check if slug already exists (only if provided or generated)
    if (!empty($slug)) {
        $stmt = $conn->prepare("SELECT id FROM blogs WHERE slug = ?");
        $stmt->bind_param("s", $slug);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            $errors[] = "Slug already exists. Please choose a unique one.";
        }
        $stmt->close();
    } else {
        $errors[] = "Failed to generate a valid slug. Please enter one manually.";
    }

    // Handle Featured Image
    $featured_image_path = null;
    if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] === UPLOAD_ERR_OK) {
        $image_name = $_FILES['featured_image']['name'];
        $image_tmp = $_FILES['featured_image']['tmp_name'];
        $image_ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
        $allowed_exts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

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

            $featured_image_path = $upload_dir . uniqid('blog_') . '.' . $image_ext;

            if (!move_uploaded_file($image_tmp, $featured_image_path)) {
                $errors[] = "Failed to upload image.";
            }
        }
    }

    // Save to DB if no errors
    if (empty($errors)) {
        $status = 'published'; // Always published

        $stmt = $conn->prepare("INSERT INTO blogs (title, slug, content, category_id, featured_image, status, meta_title, meta_description, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
        $stmt->bind_param("sssissis", $title, $slug, $content, $category_id, $featured_image_path, $status, $meta_title, $meta_description);

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

            echo "<script>
                setTimeout(() => window.location.href = 'blog_list.php', 2000);
            </script>";
        } else {
            $errors[] = "Database error: " . $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: 200px; height: auto; border-radius: 8px; margin-top: 10px; }
        @media (max-width: 768px) { .content { 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 blogs..." 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"></i>
            <i class="fas fa-envelope text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer"></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"></i>
        </div>
    </nav>

    <!-- Add Blog Form -->
    <div class="max-w-4xl 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">Add New Blog</h2>

            <!-- Success Message -->
            <?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 successful -->
            <?php if (!$success): ?>
            <form method="POST" enctype="multipart/form-data" class="space-y-5">
                <input type="hidden" name="add_blog" value="1">

                <!-- Title -->
                <div>
                    <label for="title" class="block text-sm font-medium text-gray-700">Blog Title <span class="text-red-500">*</span></label>
                    <input type="text" id="title" name="title" value="<?php echo isset($_POST['title']) ? htmlspecialchars($_POST['title']) : ''; ?>" class="w-full p-3 border border-gray-300 rounded-md" required>
                </div>

                <!-- Slug (Optional) -->
                <div>
                    <label for="slug" class="block text-sm font-medium text-gray-700">Slug (URL)</label>
                    <input type="text" id="slug" name="slug" value="<?php echo isset($_POST['slug']) ? htmlspecialchars($_POST['slug']) : ''; ?>" placeholder="auto-generated from title" class="w-full p-3 border border-gray-300 rounded-md">
                    <p class="text-xs text-gray-500 mt-1">Leave blank to auto-generate.</p>
                </div>

                <!-- Category -->
                <div>
                    <label for="category_id" class="block text-sm font-medium text-gray-700">Category <span class="text-red-500">*</span></label>
                    <select id="category_id" name="category_id" class="w-full p-3 border border-gray-300 rounded-md" required>
                        <option value="">Select Category</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>" <?php echo (isset($_POST['category_id']) && $_POST['category_id'] == $cat['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($cat['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Content -->
                <div>
                    <label for="content" class="block text-sm font-medium text-gray-700">Content <span class="text-red-500">*</span></label>
                    <textarea id="content" name="content" rows="10" class="w-full p-3 border border-gray-300 rounded-md" required><?php echo isset($_POST['content']) ? htmlspecialchars($_POST['content']) : ''; ?></textarea>
                </div>

                <!-- Featured Image -->
                <div>
                    <label for="featured_image" class="block text-sm font-medium text-gray-700">Featured Image</label>
                    <input type="file" id="featured_image" name="featured_image" accept="image/*" class="w-full p-3 border border-gray-300 rounded-md">
                    <p class="text-xs text-gray-500 mt-1">Recommended: 1200x630px</p>
                </div>

                <!-- Status: Always Published (Hidden) -->
                <input type="hidden" name="status" value="published">
                <div class="bg-gray-50 p-3 rounded-md">
                    <p class="text-sm font-medium text-gray-700">Status: <span class="text-green-600 font-bold">Published</span></p>
                    <p class="text-xs text-gray-500">All new blogs are published by default.</p>
                </div>

                <!-- SEO: Meta Title -->
                <div>
                    <label for="meta_title" class="block text-sm font-medium text-gray-700">Meta Title (SEO)</label>
                    <input type="text" id="meta_title" name="meta_title" value="<?php echo isset($_POST['meta_title']) ? htmlspecialchars($_POST['meta_title']) : ''; ?>" maxlength="70" class="w-full p-3 border border-gray-300 rounded-md">
                    <p class="text-xs text-gray-500 mt-1">Max 70 characters</p>
                </div>

                <!-- SEO: Meta Description -->
                <div>
                    <label for="meta_description" class="block text-sm font-medium text-gray-700">Meta Description (SEO)</label>
                    <textarea id="meta_description" name="meta_description" rows="3" maxlength="160" class="w-full p-3 border border-gray-300 rounded-md"><?php echo isset($_POST['meta_description']) ? htmlspecialchars($_POST['meta_description']) : ''; ?></textarea>
                    <p class="text-xs text-gray-500 mt-1">Max 160 characters</p>
                </div>

                <!-- Buttons -->
                <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">Add Blog</button>
                    <a href="blog_list.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; ?>

            <!-- Back Link after success -->
            <?php if ($success): ?>
                <div class="text-center mt-6">
                    <a href="blog_list.php" class="text-blue-600 hover:underline">Back to Blog List</a>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

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