<?php
require_once 'config/database.php';
require_once 'config/auth.php';
require_once 'config/currency.php';
require_once 'config/rbac.php';
require_once __DIR__ . '/includes/functions.php';

if (function_exists('getAllPublishedPosts')) {
    echo "Function getAllPublishedPosts loaded successfully.";
} else {
    echo "Function getAllPublishedPosts NOT found.";
    exit;
}

$page_title = 'Home';
$post_search = $_GET['post_search'] ?? null;
$posts = getAllPublishedPosts(6, $post_search);
$categories = getCategories();
$announcements = getActiveAnnouncements();
$slideshow_images = json_decode(getSiteSetting('slideshow_images') ?: '[]', true);

// Get filter parameters for courses
$category = $_GET['category'] ?? '';
$level = $_GET['level'] ?? '';
$search = $_GET['search'] ?? '';
$sort = $_GET['sort'] ?? 'newest';

// Get featured courses for home page
$db = getDB();
$query = "SELECT DISTINCT c.id, c.title, c.slug, c.description, c.short_description, c.thumbnail, c.banner_image,
                  c.price, c.currency, c.level, c.duration_hours, c.language, c.max_students, c.prerequisites,
                  c.learning_objectives, c.tags, c.status, c.is_featured, c.is_free, c.created_at, c.updated_at,
                  c.instructor_id, c.category_id,
                  cat.name as category_name, cat.icon as category_icon, cat.color as category_color,
                  u.username as instructor_name, up.first_name, up.last_name,
                  COALESCE(stats.enrollment_count, 0) as enrollment_count,
                  stats.average_rating,
                  COALESCE(stats.review_count, 0) as review_count
           FROM courses c
           LEFT JOIN course_categories cat ON c.category_id = cat.id
           LEFT JOIN users u ON c.instructor_id = u.id
           LEFT JOIN user_profiles up ON u.id = up.user_id
           LEFT JOIN course_lessons cl ON c.id = cl.course_id
           LEFT JOIN (
               SELECT c2.id as course_id,
                      COUNT(DISTINCT ce.id) as enrollment_count,
                      AVG(cr.rating) as average_rating,
                      COUNT(DISTINCT cr.id) as review_count
               FROM courses c2
               LEFT JOIN course_enrollments ce ON c2.id = ce.course_id AND ce.status = 'completed'
               LEFT JOIN course_reviews cr ON c2.id = cr.course_id AND cr.status = 'approved'
               GROUP BY c2.id
           ) stats ON c.id = stats.course_id
           WHERE c.status = 'published' AND (cat.is_active = 1 OR cat.id IS NULL)";

$params = [];

// Add filters
if (!empty($category)) {
    $query .= " AND cat.slug = ?";
    $params[] = $category;
}

if (!empty($level)) {
    $query .= " AND c.level = ?";
    $params[] = $level;
}

if (!empty($search)) {
    $query .= " AND (c.title LIKE ? OR c.description LIKE ? OR c.tags LIKE ? OR cl.content LIKE ?)";
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

// Add sorting
switch ($sort) {
    case 'oldest':
        $query .= " ORDER BY c.created_at ASC";
        break;
    case 'popular':
        $query .= " ORDER BY enrollment_count DESC, average_rating DESC";
        break;
    case 'rating':
        $query .= " ORDER BY average_rating DESC, enrollment_count DESC";
        break;
    case 'price_low':
        $query .= " ORDER BY c.price ASC";
        break;
    case 'price_high':
        $query .= " ORDER BY c.price DESC";
        break;
    default: // newest
        $query .= " ORDER BY c.is_featured DESC, c.created_at DESC";
        break;
}

$query .= " LIMIT 12";

$stmt = $db->prepare($query);
$stmt->execute($params);
$courses = $stmt->fetchAll();

// Get enrollment status for logged-in users
$userEnrollments = [];
if (isLoggedIn()) {
    $stmt = $db->prepare("SELECT course_id, status FROM course_enrollments WHERE student_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $userEnrollments = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
}

include 'includes/header.php';
?>


<section class="hero">
    <div class="container">
        <div class="hero-content">
            <h1 class="hero-title">Welcome to Mutalex Academy</h1>
            <p class="hero-description">Your premier destination for the latest news, insightful articles,journals and academic content for various professional courses . Stay informed and inspired with our diverse content.</p>
            <?php if (!empty($announcements)): ?>
                <div id="hero-announcement" class="hero-announcement">
                    <div class="announcement-content">
                        <i class="fas fa-bullhorn"></i>
                        <span id="announcement-text"><?php echo htmlspecialchars($announcements[0]['title']); ?>: <?php echo htmlspecialchars($announcements[0]['content']); ?></span>
                        <button class="announcement-close" onclick="closeHeroAnnouncement()">&times;</button>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</section>

<?php if (!empty($slideshow_images)): ?>
<section class="slideshow">
    <div class="slideshow-container">
        <?php foreach ($slideshow_images as $index => $image): ?>
            <div class="slide <?php echo $index === 0 ? 'active' : ''; ?>" style="background-image: url('<?php echo htmlspecialchars($image['url']); ?>');">
                <?php if (!empty(trim($image['title'] ?? '')) || !empty(trim($image['description'] ?? ''))): ?>
                <div class="slide-content">
                    <h2><?php echo htmlspecialchars($image['title'] ?? ''); ?></h2>
                    <p><?php echo htmlspecialchars($image['description'] ?? ''); ?></p>
                </div>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
        <button class="prev-btn" onclick="changeSlide(-1)">&#10094;</button>
        <button class="next-btn" onclick="changeSlide(1)">&#10095;</button>
        <div class="dots">
            <?php foreach ($slideshow_images as $index => $image): ?>
                <span class="dot <?php echo $index === 0 ? 'active' : ''; ?>" onclick="currentSlide(<?php echo $index; ?>)"></span>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>

<section class="search-section">
    <div class="container">
        <div class="search-container">
            <form method="GET" action="" class="search-form">
                <input type="text" name="post_search" placeholder="Search posts..." value="<?php echo htmlspecialchars($post_search ?? ''); ?>" class="search-input">
                <button type="submit" class="search-btn">
                    <i class="fas fa-search"></i> Search
                </button>
                <?php if ($post_search): ?>
                    <a href="<?php echo BASE_URL; ?>home" class="clear-search">Clear Search</a>
                <?php endif; ?>
            </form>
        </div>
    </div>
</section>

<!-- Available Courses Section -->
<section class="available-courses-section">
    <div class="container">
        <div class="courses-header">
            <h2 class="courses-title">Available Courses</h2>
            <p class="courses-subtitle">Expand your knowledge with our expertly crafted courses</p>
            <a href="courses/catalog.php" class="view-all-courses">
                View All Courses <i class="fas fa-arrow-right"></i>
            </a>
        </div>

        <!-- Course Filters -->
        <div class="course-filters" style="margin-bottom: 2rem; background: white; padding: 1.5rem; border-radius: 12px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);">
            <form method="GET" class="filters-form" style="display: flex; flex-wrap: wrap; gap: 1rem; align-items: end;">
                <div style="flex: 1; min-width: 200px;">
                    <label for="search" style="display: block; font-weight: 600; color: #374151; margin-bottom: 0.5rem;">Search Courses</label>
                    <input type="text" id="search" name="search" placeholder="Search courses..." value="<?php echo htmlspecialchars($search); ?>" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 8px; font-size: 0.9rem;">
                </div>
                <div style="min-width: 150px;">
                    <label for="category" style="display: block; font-weight: 600; color: #374151; margin-bottom: 0.5rem;">Category</label>
                    <select id="category" name="category" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 8px; font-size: 0.9rem;">
                        <option value="">All Categories</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo htmlspecialchars($cat['slug']); ?>" <?php echo $category === $cat['slug'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($cat['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div style="min-width: 120px;">
                    <label for="level" style="display: block; font-weight: 600; color: #374151; margin-bottom: 0.5rem;">Level</label>
                    <select id="level" name="level" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 8px; font-size: 0.9rem;">
                        <option value="">All Levels</option>
                        <option value="beginner" <?php echo $level === 'beginner' ? 'selected' : ''; ?>>Beginner</option>
                        <option value="intermediate" <?php echo $level === 'intermediate' ? 'selected' : ''; ?>>Intermediate</option>
                        <option value="advanced" <?php echo $level === 'advanced' ? 'selected' : ''; ?>>Advanced</option>
                    </select>
                </div>
                <div style="min-width: 140px;">
                    <label for="sort" style="display: block; font-weight: 600; color: #374151; margin-bottom: 0.5rem;">Sort By</label>
                    <select id="sort" name="sort" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 8px; font-size: 0.9rem;">
                        <option value="newest" <?php echo $sort === 'newest' ? 'selected' : ''; ?>>Newest First</option>
                        <option value="popular" <?php echo $sort === 'popular' ? 'selected' : ''; ?>>Most Popular</option>
                        <option value="rating" <?php echo $sort === 'rating' ? 'selected' : ''; ?>>Highest Rated</option>
                        <option value="price_low" <?php echo $sort === 'price_low' ? 'selected' : ''; ?>>Price: Low to High</option>
                        <option value="price_high" <?php echo $sort === 'price_high' ? 'selected' : ''; ?>>Price: High to Low</option>
                    </select>
                </div>
                <button type="submit" style="padding: 0.75rem 1.5rem; background: #3b82f6; color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer;">Apply Filters</button>
                <?php if (!empty($category) || !empty($level) || !empty($search) || $sort !== 'newest'): ?>
                    <a href="home.php" style="padding: 0.75rem 1.5rem; background: #6b7280; color: white; text-decoration: none; border-radius: 8px; font-weight: 600;">Clear Filters</a>
                <?php endif; ?>
            </form>
        </div>

        <?php if (!empty($courses)): ?>
            <div class="courses-grid">
                <?php foreach ($courses as $index => $course): ?>
                     <div class="course-card" style="--card-index: <?php echo $index; ?>">
                        <div class="course-image-container">
                            <?php if ($course['thumbnail']): ?>
                                <img src="<?php echo htmlspecialchars($course['thumbnail']); ?>" alt="<?php echo htmlspecialchars($course['title']); ?>" class="course-image">
                            <?php else: ?>
                                <div class="course-image-placeholder" style="background: linear-gradient(135deg, <?php echo htmlspecialchars($course['category_color'] ?? '#667eea'); ?> 0%, <?php echo htmlspecialchars($course['category_color'] ?? '#764ba2'); ?> 100%);">
                                    <i class="<?php echo htmlspecialchars($course['category_icon'] ?? 'fas fa-graduation-cap'); ?>"></i>
                                </div>
                            <?php endif; ?>

                            <div class="course-badges">
                                <?php if ($course['is_featured']): ?>
                                    <span class="badge badge-featured">
                                        <i class="fas fa-star"></i> Featured
                                    </span>
                                <?php endif; ?>
                                <?php if ($course['is_free']): ?>
                                    <span class="badge badge-free">Free</span>
                                <?php endif; ?>
                            </div>

                            <div class="course-overlay">
                                <a href="courses/detail.php?id=<?php echo $course['id']; ?>" class="course-link">
                                    <i class="fas fa-eye"></i>
                                    View Course
                                </a>
                            </div>
                        </div>

                        <div class="course-content">
                            <div class="course-category">
                                <i class="<?php echo htmlspecialchars($course['category_icon']); ?>"></i>
                                <?php echo htmlspecialchars($course['category_name']); ?>
                            </div>

                            <h3 class="course-title">
                                <a href="courses/detail.php?id=<?php echo $course['id']; ?>">
                                    <?php echo htmlspecialchars($course['title']); ?>
                                </a>
                            </h3>

                            <p class="course-description">
                                <?php echo htmlspecialchars(substr($course['short_description'] ?? $course['description'], 0, 80)); ?>...
                            </p>



                            <div class="course-footer">
                                <div class="course-price">
                                    <?php if ($course['is_free']): ?>
                                        <span class="price-free">Free</span>
                                    <?php else: ?>
                                        <span class="price-amount"><?php echo formatCurrency($course['price'], $course['currency']); ?></span>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <div class="course-actions">
                                <?php if (isLoggedIn()): ?>
                                    <?php if (isset($userEnrollments[$course['id']]) && $userEnrollments[$course['id']] !== 'dropped' && $userEnrollments[$course['id']] !== 'completed'): ?>
                                        <a href="student/learn.php?id=<?php echo $course['id']; ?>" class="btn btn-success">
                                            <i class="fas fa-play me-2"></i>Continue Learning
                                        </a>
                                    <?php elseif (hasPermission('enroll_course')): ?>
                                        <button class="btn btn-primary" onclick="addToCart(<?php echo $course['id']; ?>, '<?php echo addslashes($course['title']); ?>')">
                                            <i class="fas fa-cart-plus me-2"></i>
                                            <?php echo $course['is_free'] ? 'Add to Cart (Free)' : 'Add to Cart'; ?>
                                        </button>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <a href="login.php?redirect=home.php" class="btn btn-outline-primary">
                                        <i class="fas fa-sign-in-alt me-2"></i>Login to Add to Cart
                                    </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="empty-courses">
                <div class="empty-courses-content">
                    <i class="fas fa-graduation-cap empty-icon"></i>
                    <h3>No courses available</h3>
                    <p>Courses will be available soon. Check back later!</p>
                </div>
            </div>
        <?php endif; ?>
    </div>
</section>

<style>
/* Available Courses Section */
.available-courses-section {
    padding: 4rem 0;
    background: #f8fafc;
}

.courses-header {
    text-align: center;
    margin-bottom: 3rem;
}

.courses-title {
    font-size: 2.8rem;
    font-weight: 800;
    color: #1f2937;
    margin-bottom: 1rem;
    letter-spacing: -0.02em;
    line-height: 1.2;
}

.courses-subtitle {
    color: #6b7280;
    font-size: 1.1rem;
    margin-bottom: 2rem;
    max-width: 600px;
    margin-left: auto;
    margin-right: auto;
}

.view-all-courses {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    color: #3b82f6;
    text-decoration: none;
    font-weight: 600;
    font-size: 1rem;
    transition: color 0.3s ease;
}

.view-all-courses:hover {
    color: #2563eb;
}

/* Course Grid */
.courses-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 1.5rem;
    margin-bottom: 3rem;
}

.course-card {
    background: white;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
    transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    border: 1px solid #e1e5e9;
    animation: cardFadeIn 0.6s ease-out both;
    animation-delay: calc(var(--card-index, 0) * 0.1s);
}

.course-card:hover {
    transform: translateY(-12px) scale(1.02);
    box-shadow: 0 25px 50px rgba(0, 0, 0, 0.15);
    border-color: #e5e7eb;
}

@keyframes cardFadeIn {
    from {
        opacity: 0;
        transform: translateY(30px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.course-image-container {
    position: relative;
    height: 160px;
    overflow: hidden;
}

.course-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s ease;
}

.course-card:hover .course-image {
    transform: scale(1.05);
}

.course-image-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 3rem;
    background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
}

.course-badges {
    position: absolute;
    top: 12px;
    left: 12px;
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.badge {
    padding: 0.375rem 0.75rem;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.badge-featured {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
    color: white;
}

.badge-free {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white;
}

.course-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(59, 130, 246, 0.9);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
}

.course-card:hover .course-overlay {
    opacity: 1;
}

.course-link {
    color: white;
    text-decoration: none;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.75rem 1.5rem;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 8px;
    backdrop-filter: blur(10px);
    transition: background 0.3s ease;
}

.course-link:hover {
    background: rgba(255, 255, 255, 0.3);
}

/* Course Content */
.course-content {
    padding: 1rem;
    overflow: hidden;
}

.course-category {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    background: #f3f4f6;
    color: #6b7280;
    padding: 0.25rem 0.75rem;
    border-radius: 12px;
    font-size: 0.8rem;
    font-weight: 500;
    margin-bottom: 1rem;
}

.course-title {
    font-size: 1.1rem;
    font-weight: 700;
    color: #1f2937;
    margin-bottom: 0.5rem;
    line-height: 1.2;
    letter-spacing: -0.01em;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    text-overflow: ellipsis;
}

.course-title a {
    color: inherit;
    text-decoration: none;
}

.course-title a:hover {
    color: #3b82f6;
}

.course-description {
    color: #6b7280;
    font-size: 0.85rem;
    line-height: 1.4;
    margin-bottom: 1rem;
    font-weight: 400;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    text-overflow: ellipsis;
}



/* Course Footer */
.course-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
}



.course-price .price-free {
    font-size: 1.5rem;
    font-weight: 700;
    color: #10b981;
}

.course-price .price-amount {
    font-size: 1.5rem;
    font-weight: 700;
    color: #1e40af;
}

/* Course Actions */
.course-actions {
    margin-top: 0.75rem;
}

.course-actions .btn {
    width: 100%;
    padding: 0.4rem 0.6rem;
    border-radius: 8px;
    font-size: 0.8rem;
    font-weight: 600;
    text-transform: none;
    transition: all 0.3s ease;
}

.course-actions .btn-primary {
    background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
    border: none;
}

.course-actions .btn-success {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    border: none;
}

.course-actions .btn-outline-primary {
    border: 2px solid #3b82f6;
    color: #3b82f6;
}

.course-actions .btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

/* Empty State */
.empty-courses {
    text-align: center;
    padding: 5rem 2rem;
    animation: fadeInUp 0.6s ease-out;
}

@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.empty-courses-content {
    max-width: 450px;
    margin: 0 auto;
}

.empty-icon {
    font-size: 4.5rem;
    color: #d1d5db;
    margin-bottom: 1.5rem;
    opacity: 0.7;
}

.empty-courses h3 {
    font-size: 1.6rem;
    font-weight: 700;
    color: #1f2937;
    margin-bottom: 0.75rem;
    letter-spacing: -0.01em;
}

.empty-courses p {
    color: #6b7280;
    margin-bottom: 2.5rem;
    font-size: 1.1rem;
    line-height: 1.6;
}

/* Responsive Design */
@media (max-width: 1024px) {
    .courses-grid {
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        gap: 1.75rem;
    }
}

@media (max-width: 768px) {
    .available-courses-section {
        padding: 3rem 0;
    }

    .courses-title {
        font-size: 2.3rem;
    }

    .courses-grid {
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        gap: 1.5rem;
    }

    .course-card {
        border-radius: 12px;
    }

    .course-image-container {
        height: 220px;
    }

    .course-content {
        padding: 1.5rem;
    }

    .course-footer {
        flex-direction: column;
        gap: 1rem;
        align-items: flex-start;
        margin-bottom: 1rem;
    }

    .course-stats {
        flex-wrap: wrap;
        width: 100%;
    }

    .course-actions {
        width: 100%;
    }

    .course-actions .btn {
        width: 100%;
        justify-content: center;
    }
}

@media (max-width: 480px) {
    .available-courses-section {
        padding: 2rem 0;
    }

    .courses-title {
        font-size: 2rem;
    }

    .course-image-container {
        height: 200px;
    }

    .course-title {
        font-size: 1.2rem;
    }

    .course-description {
        font-size: 0.9rem;
    }
}
</style>

<section class="categories-section">
    <div class="container">
        <h2 class="section-title">Explore Categories</h2>
        <div class="categories-grid">
            <?php foreach ($categories as $category): ?>
                <div class="category-card">
                    <div class="category-thumbnail">
                        <?php if (!empty($category['thumbnail'])): ?>
                            <img src="<?php echo htmlspecialchars($category['thumbnail']); ?>" alt="<?php echo htmlspecialchars($category['name']); ?>" class="category-image">
                        <?php else: ?>
                            <div class="category-icon">
                                <?php
                                $icons = ['news' => 'fas fa-newspaper', 'articles' => 'fas fa-file-alt', 'journals' => 'fas fa-book'];
                                echo '<i class="' . ($icons[$category['slug']] ?? 'fas fa-folder') . '"></i>';
                                ?>
                            </div>
                        <?php endif; ?>
                    </div>
                    <h3><?php echo htmlspecialchars($category['name']); ?></h3>
                    <p><?php echo htmlspecialchars($category['description']); ?></p>
                    <a href="category.php?cat=<?php echo urlencode($category['slug']); ?>" class="category-link">
                        Explore <?php echo htmlspecialchars($category['name']); ?>
                        <i class="fas fa-arrow-right"></i>
                    </a>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>

<section class="featured-posts">
    <div class="container">
        <h2 class="section-title">
            <?php echo $post_search ? 'Search Results for "' . htmlspecialchars($post_search) . '"' : 'Latest Posts'; ?>
        </h2>
        
        <?php if ($posts): ?>
            <div class="posts-grid">
                <?php foreach ($posts as $post): ?>
                    <article class="post-card">
                        <div class="post-header">
                            <span class="post-category"><?php echo htmlspecialchars($post['category_name']); ?></span>
                            <time class="post-date"><?php echo formatDate($post['created_at']); ?></time>
                        </div>
                        <h3 class="post-title">
                            <a href="post.php?slug=<?php echo urlencode($post['slug']); ?>">
                                <?php echo htmlspecialchars($post['title']); ?>
                            </a>
                        </h3>
                        <p class="post-excerpt">
                            <?php echo htmlspecialchars(truncateText(strip_tags($post['content']))); ?>
                        </p>
                        <div class="post-footer">
                            <span class="post-author">By <?php echo htmlspecialchars($post['author_name']); ?></span>
                            <a href="post.php?slug=<?php echo urlencode($post['slug']); ?>" class="read-more">
                                Read More <i class="fas fa-arrow-right"></i>
                            </a>
                        </div>
                    </article>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="no-posts">
                <i class="fas fa-newspaper"></i>
                <p>
                    <?php if ($post_search): ?>
                        No posts found matching "<?php echo htmlspecialchars($post_search); ?>". Try different keywords.
                    <?php else: ?>
                        No posts available at the moment. Check back soon!
                    <?php endif; ?>
                </p>
            </div>
        <?php endif; ?>
    </div>
</section>

<script>
<?php if (!empty($announcements)): ?>
const announcements = <?php echo json_encode($announcements); ?>;
let currentAnnouncementIndex = 0;

function showAnnouncement(index) {
    if (index < announcements.length) {
        const announcement = announcements[index];
        document.getElementById('announcement-text').textContent = announcement.title + ': ' + announcement.content;
    }
}

function closeHeroAnnouncement() {
    document.getElementById('hero-announcement').style.display = 'none';
}

// Cycle through announcements every 10 seconds
setInterval(() => {
    currentAnnouncementIndex = (currentAnnouncementIndex + 1) % announcements.length;
    showAnnouncement(currentAnnouncementIndex);
}, 10000);
<?php endif; ?>

<?php if (!empty($slideshow_images)): ?>
let slideIndex = 0;
const slides = document.getElementsByClassName("slide");
const dots = document.getElementsByClassName("dot");

function showSlides(n) {
    if (n >= slides.length) { slideIndex = 0; }
    if (n < 0) { slideIndex = slides.length - 1; }

    // Hide all slides
    for (let i = 0; i < slides.length; i++) {
        slides[i].classList.remove("active");
        slides[i].style.opacity = "0";
    }

    // Remove active class from all dots
    for (let i = 0; i < dots.length; i++) {
        dots[i].classList.remove("active");
    }

    // Show current slide
    slides[slideIndex].classList.add("active");
    slides[slideIndex].style.opacity = "1";

    // Activate corresponding dot
    if (dots[slideIndex]) {
        dots[slideIndex].classList.add("active");
    }

}

function changeSlide(n) {
    showSlides(slideIndex += n);
}

function currentSlide(n) {
    showSlides(slideIndex = n);
}

// Auto slide every 5 seconds
setInterval(() => {
    changeSlide(1);
}, 5000);

// Initialize first slide
showSlides(0);
<?php endif; ?>

function addToCart(courseId, courseTitle) {
    fetch('api/cart.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ course_id: courseId })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Show success message and redirect to cart
            alert(courseTitle + ' has been added to your cart!');
            window.location.href = 'student/dashboard.php';
        } else {
            alert('Error: ' + data.error);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred. Please try again.');
    });
}

function updateCartCount() {
    // This function could update a cart count badge in the header
    fetch('api/cart.php')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const cart = data.cart;
            // Update cart count display if it exists
            const cartBadge = document.getElementById('cartCount');
            if (cartBadge) {
                cartBadge.textContent = cart.item_count || 0;
            }
        }
    })
    .catch(error => {
        console.error('Error updating cart count:', error);
    });
}

// Update cart count on page load
document.addEventListener('DOMContentLoaded', function() {
    updateCartCount();
});
</script>

<?php include 'includes/footer.php'; ?>
