<?php
include_once 'inc/navigation.php';
?>

   <main>

      <!-- breadcrumb-area-start -->
      <div class="it-breadcrumb-area it-breadcrumb-bg" data-background="images/students_graduation.webp">
         <div class="container">
            <div class="row ">
               <div class="col-md-12">
                  <div class="it-breadcrumb-content z-index-3 text-center">
                     <div class="it-breadcrumb-title-box">
                        <h3 class="it-breadcrumb-title">Blog </h3>
                     </div>
                     <div class="it-breadcrumb-list-wrap">
                        <div class="it-breadcrumb-list">
                           <span><a href="/">home</a></span>
                           <span class="dvdr">//</span>
                           <span>Blog</span>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
      <!-- breadcrumb-area-end -->

      <!-- postbox area start -->
      <div class="postbox__area pt-120 pb-120">
         <div class="container">
            <?php
            $slug = $_GET['slug'] ?? '';

            if (empty($slug)) {
                die("Blog post not found.");
            }

            try {
                // Fetch blog details by slug
                $sql = "SELECT b.*, bc.category_name 
                        FROM blog b 
                        LEFT JOIN blog_categories bc ON b.category_id = bc.id 
                        WHERE b.slug = :slug AND b.publish_status = '1'";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([':slug' => $slug]);
                $blog = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if (!$blog) {
                    die("Blog post not found.");
                }
                
                // Fetch images from comma-separated list
                $images = !empty($blog['blog_image']) ? explode(',', $blog['blog_image']) : [];
                $mainImage = !empty($images[0]) ? 'blog_images/' . trim($images[0]) : 'assets/img/blog/blog-details-1.jpg';
                
                // Load blog content from text file
                $blogContent = '';
                if (!empty($blog['blog']) && file_exists('blog/' . $blog['blog'])) {
                    $blogContent = file_get_contents('blog/' . $blog['blog']);
                }
                
                // Format date
                $blogDate = !empty($blog['date']) ? strtotime($blog['date']) : time();
                $formattedDate = date('d F Y', $blogDate);
                
                // Get comment count (implement based on your comment system)
                $commentCount = 0; // Placeholder
                
                // Fetch recent blogs for sidebar
                $recentSql = "SELECT * FROM blog WHERE publish_status = '1' AND id != :id ORDER BY date DESC LIMIT 3";
                $recentStmt = $pdo->prepare($recentSql);
                $recentStmt->execute([':id' => $blog['id']]);
                $recentBlogs = $recentStmt->fetchAll(PDO::FETCH_ASSOC);
                
                // Fetch blog categories
                $categoriesSql = "SELECT * FROM blog_categories ORDER BY category_name";
                $categoriesStmt = $pdo->prepare($categoriesSql);
                $categoriesStmt->execute();
                $categories = $categoriesStmt->fetchAll(PDO::FETCH_ASSOC);
                
                // Fetch tags
                $tags = !empty($blog['tags']) ? explode(',', $blog['tags']) : [];
                
            } catch(PDOException $e) {
                die("Database error: " . $e->getMessage());
            }
            ?>

            <div class="row">
                <div class="col-xxl-8 col-xl-8 col-lg-8">
                    <div class="postbox__details-wrapper">
                        <article>
                            <!-- Main Image -->
                            <div class="postbox__thumb mb-30 w-img">
                                <img src="<?php echo htmlspecialchars($mainImage); ?>" alt="<?php echo htmlspecialchars($blog['blog_title']); ?>">
                            </div>
                            
                            <div class="postbox__details-title-box pb-40">
                                <div class="postbox__meta">
                                    <span><i class="fa-solid fa-calendar-days"></i><?php echo $formattedDate; ?></span>
                                    <span><i class="fa-regular fa-comments"></i>Comment (<?php echo $commentCount; ?>)</span>
                                </div>
                                <h4 class="postbox__title mb-20"><?php echo htmlspecialchars($blog['blog_title']); ?></h4>
                                <p><?php echo substr($blogContent, 0, 500) . '...'; ?></p>
                            </div>
                            
                            <div class="postbox__content pb-20">
                                <?php if (count($images) > 1): ?>
                                <div class="postbox__content-img mb-40 d-flex justify-content-between">
                                    <?php 
                                    // Display first two additional images side by side
                                    $additionalImages = array_slice($images, 1, 2);
                                    foreach ($additionalImages as $key => $image):
                                        $imagePath = 'blog_images/' . trim($image);
                                    ?>
                                    <img class="<?php echo $key == 0 ? 'mr-30' : ''; ?>" 
                                        src="<?php echo htmlspecialchars($imagePath); ?>" 
                                        alt="<?php echo htmlspecialchars($blog['blog_title'] . ' - Image ' . ($key + 2)); ?>">
                                    <?php endforeach; ?>
                                </div>
                                <?php endif; ?>
                                
                                <div class="postbox__text">
                                    <?php 
                                    // Display full blog content
                                    echo $blogContent;
                                    
                                    // Display remaining images after content
                                    if (count($images) > 3):
                                        $remainingImages = array_slice($images, 3);
                                        foreach ($remainingImages as $key => $image):
                                            $imagePath = 'blog_images/' . trim($image);
                                    ?>
                                    <div class="postbox__content-img mb-20 mt-20">
                                        <img src="<?php echo htmlspecialchars($imagePath); ?>" 
                                            alt="<?php echo htmlspecialchars($blog['blog_title'] . ' - Image ' . ($key + 4)); ?>">
                                    </div>
                                    <?php 
                                        endforeach;
                                    endif; 
                                    ?>
                                </div>
                            </div>
                            
                            <div class="postbox__details-share-wrapper">
                                <div class="row align-items-center">
                                    <div class="col-xl-7 col-lg-7 col-md-7">
                                        <div class="postbox__details-tag">
                                            <span>Posted in:</span>
                                            <?php if (!empty($blog['category_name'])): ?>
                                            <a href="blog-category.php?id=<?php echo $blog['category_id']; ?>">
                                                <?php echo htmlspecialchars($blog['category_name']); ?>
                                            </a>
                                            <?php endif; ?>
                                            <?php if (!empty($tags)): ?>
                                            <?php foreach ($tags as $tag): ?>
                                            <a href="blog-tag.php?tag=<?php echo urlencode(trim($tag)); ?>">
                                                <?php echo htmlspecialchars(trim($tag)); ?>
                                            </a>
                                            <?php endforeach; ?>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="col-xl-5 col-lg-5 col-md-5">
                                        <div class="postbox__details-share text-lg-end">
                                            <span>Share:</span>
                                            <?php
                                            $shareTitle = urlencode($blog['blog_title']);
                                            $shareUrl = urlencode("https://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
                                            ?>
                                            <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo $shareUrl; ?>" target="_blank">
                                                <i class="fab fa-facebook-f"></i>
                                            </a>
                                            <a href="https://twitter.com/intent/tweet?text=<?php echo $shareTitle; ?>&url=<?php echo $shareUrl; ?>" target="_blank">
                                                <i class="fab fa-twitter"></i>
                                            </a>
                                            <a href="https://www.linkedin.com/shareArticle?mini=true&url=<?php echo $shareUrl; ?>&title=<?php echo $shareTitle; ?>" target="_blank">
                                                <i class="fab fa-linkedin-in"></i>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </article>
                    </div>
                </div>
                
                <!-- Sidebar -->
                <div class="col-xxl-4 col-xl-4 col-lg-4">
                    <div class="it-sv-details-sidebar">
                        <!-- Search Form -->
                        <div class="it-sv-details-sidebar-search mb-55">
                            <form action="blog-search.php" method="GET">
                                <input type="text" name="q" placeholder="search">
                                <button type="submit">
                                    <i class="fal fa-search"></i>
                                </button>
                            </form>
                        </div>
                        
                        <!-- Categories -->
                        <div class="it-sv-details-sidebar-widget mb-55">
                            <h4 class="it-sv-details-sidebar-title mb-30">Blog Categories</h4>
                            <?php if (!empty($categories)): ?>
                            <?php foreach ($categories as $category): ?>
                            <div class="it-sv-details-sidebar-category mb-10">
                                <a href="blog.php?category=<?php echo $category['id']; ?>">
                                    <?php echo htmlspecialchars($category['category_name']); ?>
                                </a>
                                <span><i class="fa-light fa-angle-right"></i></span>
                            </div>
                            <?php endforeach; ?>
                            <?php else: ?>
                            <p>No categories found.</p>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Recent Posts -->
                        <div class="sidebar__widget mb-55">
                            <div class="sidebar__widge-title-box">
                                <h3 class="sidebar__widget-title pb-10">Recent Posts</h3>
                            </div>
                            <div class="sidebar__widget-content">
                                <div class="sidebar__post">
                                    <?php if (!empty($recentBlogs)): ?>
                                    <?php foreach ($recentBlogs as $recentBlog): 
                                        $recentImages = !empty($recentBlog['blog_image']) ? explode(',', $recentBlog['blog_image']) : [];
                                        $recentThumb = !empty($recentImages[0]) ? 'blog_images/' . trim($recentImages[0]) : 'assets/img/blog/blog-sidebar-sm-1.jpg';
                                        $recentDate = !empty($recentBlog['date']) ? date('d F Y', strtotime($recentBlog['date'])) : '';
                                    ?>
                                    <div class="rc__post mb-30 d-flex align-items-start">
                                        <div class="rc__post-thumb mr-20">
                                            <a href="blog-details.php?slug=<?php echo htmlspecialchars($recentBlog['slug']); ?>">
                                                <img src="<?php echo htmlspecialchars($recentThumb); ?>" alt="<?php echo htmlspecialchars($recentBlog['blog_title']); ?>">
                                            </a>
                                        </div>
                                        <div class="rc__post-content">
                                            <div class="rc__meta">
                                                <span><i class="fa-solid fa-calendar-days"></i><?php echo $recentDate; ?></span>
                                            </div>
                                            <h3 class="rc__post-title">
                                                <a href="blog-details.php?slug=<?php echo htmlspecialchars($recentBlog['slug']); ?>">
                                                    <?php echo htmlspecialchars(substr($recentBlog['blog_title'], 0, 60) . (strlen($recentBlog['blog_title']) > 60 ? '...' : '')); ?>
                                                </a>
                                            </h3>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                    <?php else: ?>
                                    <p>No recent posts.</p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Popular Tags -->
                        <div class="it-sv-details-sidebar-widget">
                            <h4 class="it-sv-details-sidebar-title mb-30">Popular Tags:</h4>
                            <div class="sidebar__widget-content">
                                <div class="tagcloud">
                                    <?php if (!empty($tags)): ?>
                                    <?php foreach ($tags as $tag): ?>
                                    <a href="blog.php?tag=<?php echo urlencode(trim($tag)); ?>">
                                        <?php echo htmlspecialchars(trim($tag)); ?>
                                    </a>
                                    <?php endforeach; ?>
                                    <?php else: ?>
                                    <a href="#">Education</a>
                                    <a href="#">Learning</a>
                                    <a href="#">School</a>
                                    <a href="#">Student</a>
                                    <a href="#">Music</a>
                                    <a href="#">Arts</a>
                                    <a href="#">Development</a>
                                    <a href="#">Training</a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
         </div>
      </div>
      <!-- postbox area end -->

<?php
require_once 'inc/footer.php';
?>