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

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

// Handle Delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_blog'])) {
    $blog_id = (int)($_POST['blog_id'] ?? 0);

    if ($blog_id <= 0) {
        $errors[] = "Invalid blog ID.";
    } else {
        $stmt = $conn->prepare("SELECT featured_image FROM blogs WHERE id = ?");
        $stmt->bind_param("i", $blog_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $image_path = $result->fetch_assoc()['featured_image'] ?? '';
        $stmt->close();

        $stmt = $conn->prepare("DELETE FROM blogs WHERE id = ?");
        $stmt->bind_param("i", $blog_id);
        if ($stmt->execute()) {
            $success = "Blog deleted successfully! Redirecting...";
            if (!empty($image_path) && file_exists($image_path)) {
                unlink($image_path);
            }
        } else {
            $errors[] = "Failed to delete blog.";
        }
        $stmt->close();
    }
}

// Fetch blogs with category
$query = "SELECT b.*, bc.name AS category_name 
          FROM blogs b 
          LEFT JOIN blog_category bc ON b.category_id = bc.id 
          ORDER BY b.created_at DESC";

$result = $conn->query($query);
$blogs = $result->fetch_all(MYSQLI_ASSOC);
?>

<!-- Content -->
<div id="content" class="content ml-64 p-6 min-h-screen relative">
    <style>
        @import url('https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css');
        @import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css');

        body { overflow-x: hidden; font-family: 'Inter', sans-serif; }
        .content { transition: margin-left 0.3s ease; }
        .top-nav { background: linear-gradient(135deg, #1E293B 0%, #334155 100%); box-shadow: 0 10px 20px rgba(0,0,0,0.1); }
        .search-input { transition: all 0.3s; }
        .search-input:focus { transform: scale(1.02); box-shadow: 0 0 0 3px rgba(251, 191, 36, 0.3); }

        /* FAB Buttons */
        .fab-container {
            position: fixed;
            bottom: 2rem;
            right: 2rem;
            z-index: 50;
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }
        .fab {
            width: 56px;
            height: 56px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
            transition: all 0.3s ease;
            font-weight: bold;
            font-size: 1.5rem;
            color: white;
        }
        .fab:hover { transform: translateY(-4px) scale(1.05); box-shadow: 0 12px 30px rgba(0, 0, 0, 0.3); }
        .fab-main { background: linear-gradient(135deg, #F59E0B, #D97706); }
        .fab-secondary { background: linear-gradient(135deg, #3B82F6, #2563EB); }

        /* Table Design */
        .table-container {
            background: white;
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
        }
        .table-container:hover { box-shadow: 0 25px 50px rgba(0, 0, 0, 0.12); }
        .table-header {
            background: linear-gradient(135deg, #1E293B 0%, #334155 100%);
            color: white;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            font-size: 0.875rem;
        }
        .table-row {
            transition: all 0.2s ease;
            border-bottom: 1px solid #f1f5f9;
        }
        .table-row:hover {
            background: linear-gradient(to right, #fffbeb 0%, #fefce8 100%);
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
        }
        .blog-img {
            width: 80px;
            height: 50px;
            object-fit: cover;
            border-radius: 8px;
            border: 2px solid #e2e8f0;
            transition: all 0.2s;
        }
        .blog-img:hover { transform: scale(1.1); border-color: #fbbf24; }

        .badge {
            @apply inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold;
            min-width: 70px;
            justify-content: center;
        }
        .badge-published {
            background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
            color: #065f46;
        }
        .badge-draft {
            background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
            color: #92400e;
        }

        .action-btn {
            @apply px-3 py-1.5 text-xs font-medium rounded-lg transition-all duration-200 flex items-center gap-1;
        }
        .btn-view { @apply bg-emerald-600 text-white hover:bg-emerald-700; }
        .btn-edit { @apply bg-amber-600 text-white hover:bg-amber-700; }
        .btn-delete { @apply bg-rose-600 text-white hover:bg-rose-700; }

        .empty-state {
            text-align: center;
            padding: 4rem 2rem;
            color: #64748b;
        }
        .empty-state i {
            font-size: 3rem;
            color: #cbd5e1;
            margin-bottom: 1rem;
        }

        @media (max-width: 768px) {
            .content { margin-left: 0; }
            .fab-container { bottom: 1rem; right: 1rem; }
            .fab { width: 48px; height: 48px; font-size: 1.25rem; }
            .table-header, .table-row td { font-size: 0.75rem; padding: 8px; }
            .blog-img { width: 60px; height: 40px; }
        }
        @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 backdrop-blur-md bg-white/10">
        <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="search-input w-full p-3 border border-gray-300 rounded-xl bg-white/20 backdrop-blur text-white placeholder-gray-300 focus:outline-none focus:ring-2 focus:ring-amber-400">
        </div>
        <div class="right-nav flex items-center gap-4">
            <i class="fas fa-bell text-xl p-2 rounded-full hover:bg-amber-500 cursor-pointer transition-all"></i>
            <i class="fas fa-envelope text-xl p-2 rounded-full hover:bg-amber-500 cursor-pointer transition-all"></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 ring-2 ring-amber-400">
                <span class="text-white font-medium">Admin</span>
            </div>
            <i id="toggle" class="fas fa-bars text-xl p-2 rounded-full hover:bg-amber-500 cursor-pointer transition-all"></i>
        </div>
    </nav>

    <!-- FAB Buttons -->
    <div class="fab-container">
        <!-- Add Blog -->
        <a href="add_blog.php" class="fab fab-main shadow-lg" title="Add New Blog">
            <i class="fas fa-plus"></i>
        </a>
        <!-- Add Category -->
        <a href="blog_category.php" class="fab fab-secondary shadow-lg" title="Add Blog Category">
            <i class="fas fa-folder-plus"></i>
        </a>
    </div>

    <!-- Blog List -->
    <div class="max-w-7xl mx-auto my-8">
        <div class="table-container">
            <div class="p-6 border-b border-gray-200 bg-gradient-to-r from-amber-50 to-yellow-50">
                <h2 class="text-3xl font-bold text-gray-800 flex items-center gap-3">
                    <i class="fas fa-blog text-amber-600"></i>
                    All Blogs
                </h2>
                <p class="text-gray-600 mt-1">Manage your blog posts with ease</p>
            </div>

            <!-- Success Message -->
            <?php if ($success): ?>
                <div class="mx-6 mt-6 p-4 bg-emerald-50 border border-emerald-200 text-emerald-700 rounded-xl flex items-center gap-2">
                    <i class="fas fa-check-circle"></i>
                    <?php echo htmlspecialchars($success); ?>
                </div>
            <?php endif; ?>

            <!-- Error Messages -->
            <?php if (!empty($errors)): ?>
                <div class="mx-6 mt-6 p-4 bg-rose-50 border border-rose-200 text-rose-700 rounded-xl">
                    <ul class="list-disc list-inside">
                        <?php foreach ($errors as $error): ?>
                            <li><?php echo htmlspecialchars($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <!-- Table -->
            <div class="overflow-x-auto">
                <table class="min-w-full">
                    <thead>
                        <tr class="table-header">
                            <th class="px-6 py-4">ID</th>
                            <th class="px-6 py-4">Image</th>
                            <th class="px-6 py-4">Title & Slug</th>
                            <th class="px-6 py-4">Category</th>
                            <th class="px-6 py-4">Status</th>
                            <th class="px-6 py-4">Created</th>
                            <th class="px-6 py-4 text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($blogs)): ?>
                            <tr>
                                <td colspan="7" class="empty-state">
                                    <i class="fas fa-blog"></i>
                                    <h3 class="text-xl font-semibold text-gray-500 mt-3">No blogs yet</h3>
                                    <p class="mt-2">Start by adding your first blog post!</p>
                                    <a href="add_blog.php" class="mt-4 inline-block bg-amber-500 text-white px-5 py-2 rounded-lg hover:bg-amber-600 transition-all">
                                        <i class="fas fa-plus mr-2"></i>Add First Blog
                                    </a>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($blogs as $blog): ?>
                                <tr class="table-row">
                                    <td class="px-6 py-4 font-mono text-sm">#<?php echo htmlspecialchars($blog['id']); ?></td>
                                    <td class="px-6 py-4">
                                        <?php if ($blog['featured_image'] && file_exists($blog['featured_image'])): ?>
                                            <img src="<?php echo htmlspecialchars($blog['featured_image']); ?>" alt="Blog" class="blog-img">
                                        <?php else: ?>
                                            <div class="bg-gray-200 border-2 border-dashed rounded-xl w-20 h-14 flex items-center justify-center text-xs text-gray-500">
                                                <i class="fas fa-image"></i>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="font-semibold text-gray-800">
                                            <?php echo htmlspecialchars(substr($blog['title'], 0, 50)) . (strlen($blog['title']) > 50 ? '...' : ''); ?>
                                        </div>
                                        <div class="text-xs text-gray-500 mt-1 flex items-center gap-1">
                                            <i class="fas fa-link"></i>
                                            /<?php echo htmlspecialchars($blog['slug']); ?>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 text-gray-700">
                                        <?php echo htmlspecialchars($blog['category_name'] ?? '<em class="text-gray-400">Uncategorized</em>'); ?>
                                    </td>
                                    <td class="px-6 py-4">
                                        <span class="badge badge-<?php echo $blog['status']; ?>">
                                            <i class="fas fa-circle text-[8px] mr-1"></i>
                                            <?php echo ucfirst($blog['status']); ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-600">
                                        <?php echo date('M j, Y', strtotime($blog['created_at'])); ?>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="flex gap-2 justify-center">
                                            <a href="view_blog.php?id=<?php echo $blog['id']; ?>" class="action-btn btn-view" title="View">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="edit_blog.php?id=<?php echo $blog['id']; ?>" class="action-btn btn-edit" title="Edit">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <form method="POST" onsubmit="return confirm('Delete this blog permanently?');" style="display:inline;">
                                                <input type="hidden" name="blog_id" value="<?php echo $blog['id']; ?>">
                                                <input type="hidden" name="delete_blog" value="1">
                                                <button type="submit" class="action-btn btn-delete" title="Delete">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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