<?php
session_start();
require_once 'db_config.php';
require_once 'blog_helpers.php';

// Load Phase 3 helpers early
require_once __DIR__ . '/helpers/meta_tags_helper.php';
require_once __DIR__ . '/helpers/keyword_optimizer.php';
require_once __DIR__ . '/helpers/faq_helper.php';
require_once __DIR__ . '/helpers/content_optimizer.php';
require_once __DIR__ . '/helpers/schema_helper.php';
require_once __DIR__ . '/helpers/internal_linking_helper.php';

// Get blog by slug
$slug = $_GET['slug'] ?? '';
if (empty($slug)) {
    header('Location: blogs.php');
    exit;
}

$blog = getBlogBySlug($slug, $conn);
if (!$blog) {
    header('HTTP/1.0 404 Not Found');
    $notFound = true;
} else {
    $notFound = false;
    // Increment views
    incrementBlogViews($blog['id'], $conn);
    
    // Get tags
    $tags = getBlogTags($blog['id'], $conn);
    
    // Get related posts
    $relatedPosts = getRelatedPosts($blog['id'], $conn, 5);
    
    // Get navigation posts
    $navigation = getNavigationPosts($blog['id'], $conn);
    
    // Get recent posts for sidebar
    $recentPosts = getBlogs($conn, ['limit' => 3, 'order' => 'b.publish_date DESC, b.created_at DESC']);
    
    // Get recent comments for sidebar (with fallback if function doesn't exist)
    $recentComments = function_exists('getRecentComments') ? getRecentComments($conn, 4) : [];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="css/responsive-system.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <?php if (!$notFound): ?>
        <title><?php echo seo_title($blog['meta_title'] ?: $blog['title'], 'Blog – Esa\'s Fashion'); ?></title>
        <meta name="description" content="<?php echo seo_description($blog['meta_description'] ?: substr($blog['content'], 0, 160)); ?>">
        <meta name="keywords" content="<?php echo seo_keywords(array_merge(['fashion', 'blog', 'tips', 'style'], $tags ? array_column($tags, 'name') : [])); ?>">
        <link rel="canonical" href="https://<?php echo $_SERVER['HTTP_HOST']; ?>/blog.php?slug=<?php echo htmlspecialchars($slug); ?>">
        
        <!-- Open Graph Tags (Article) -->
        <meta property="og:title" content="<?php echo htmlspecialchars($blog['title']); ?>">
        <meta property="og:description" content="<?php echo htmlspecialchars(substr($blog['content'], 0, 160)); ?>">
        <meta property="og:type" content="article">
        <meta property="og:url" content="https://<?php echo $_SERVER['HTTP_HOST']; ?>/blog.php?slug=<?php echo htmlspecialchars($slug); ?>">
        <?php if ($blog['featured_image']): ?>
            <meta property="og:image" content="https://<?php echo $_SERVER['HTTP_HOST']; ?>/uploads/blog/<?php echo htmlspecialchars($blog['featured_image']); ?>">
        <?php endif; ?>
        <meta property="article:published_time" content="<?php echo $blog['publish_date'] ?? $blog['created_at']; ?>">
        <meta property="article:modified_time" content="<?php echo $blog['updated_at']; ?>">
        
        <!-- Twitter Card -->
        <meta name="twitter:card" content="summary_large_image">
        <meta name="twitter:title" content="<?php echo htmlspecialchars($blog['title']); ?>">
        <meta name="twitter:description" content="<?php echo htmlspecialchars(substr($blog['content'], 0, 160)); ?>">
        <?php if ($blog['featured_image']): ?>
            <meta name="twitter:image" content="https://<?php echo $_SERVER['HTTP_HOST']; ?>/uploads/blog/<?php echo htmlspecialchars($blog['featured_image']); ?>">
        <?php endif; ?>
        
        <!-- Robots Meta -->
        <meta name="robots" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1">
    <?php else: ?>
        <title><?php echo seo_title('Blog Not Found', 'Esa\'s Fashion'); ?></title>
        <meta name="robots" content="noindex, nofollow">
    <?php endif; ?>
    
    <style>
        .blog-page-wrapper {
            max-width: 1320px;
            margin: 0 auto;
            padding: 0 20px;
        }
        
        .breadcrumb {
            margin: 20px 0 40px;
            font-size: 14px;
            list-style: none;
            padding: 0;
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 8px;
        }
        
        .breadcrumb-item {
            display: inline;
        }
        
        .breadcrumb-item:not(:last-child)::after {
            content: ' / ';
            color: #999;
            margin: 0 4px;
        }
        
        .breadcrumb a {
            color: #666;
            text-decoration: none;
            transition: color 0.3s;
        }
        
        .breadcrumb a:hover {
            color: #F07E2D;
        }
        
        .breadcrumb span {
            color: #999;
            margin: 0 8px;
        }
        
        .blog-content-wrapper {
            display: grid;
            grid-template-columns: 1fr 300px;
            gap: 40px;
            margin-bottom: 60px;
        }
        
        .blog-main-content {
            background: #fff;
            border-radius: 8px;
            overflow: hidden;
        }
        
        .blog-featured-image {
            width: 100%;
            height: 450px;
            object-fit: cover;
            display: block;
        }
        
        .blog-header-content {
            padding: 40px;
        }
        
        .blog-category-badge {
            display: inline-block;
            background: #3498db;
            color: #fff;
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 20px;
            text-decoration: none;
            transition: background 0.3s;
        }
        
        .blog-category-badge:hover {
            background: #2980b9;
        }
        
        .blog-title {
            font-size: 32px;
            font-weight: 700;
            color: #333;
            margin-bottom: 20px;
            line-height: 1.3;
        }
        
        .blog-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            color: #666;
            font-size: 14px;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }
        
        .blog-meta-item {
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .blog-content-text {
            color: #666;
            line-height: 1.8;
            font-size: 15px;
            margin-bottom: 30px;
        }
        
        .blog-content-text p {
            margin-bottom: 20px;
        }
        
        .blog-content-text h4 {
            font-size: 20px;
            font-weight: 600;
            color: #333;
            margin: 30px 0 15px 0;
        }
        
        .blog-content-text ul {
            margin: 15px 0 15px 30px;
        }
        
        .blog-content-text ol {
            margin: 15px 0 15px 30px;
        }
        
        .blog-content-text li {
            margin-bottom: 10px;
        }
        
        .blog-author-section {
            background: #f9f9f9;
            padding: 30px;
            border-radius: 8px;
            margin: 40px 0;
            display: flex;
            gap: 20px;
            align-items: center;
        }
        
        .author-avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: #F07E2D;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 24px;
            font-weight: 700;
            flex-shrink: 0;
        }
        
        .author-info h4 {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin-bottom: 4px;
        }
        
        .author-info p {
            color: #666;
            font-size: 14px;
            margin: 0;
        }
        
        .blog-tags-share {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 30px 40px;
            border-top: 1px solid #eee;
            flex-wrap: wrap;
            gap: 20px;
        }
        
        .blog-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
        }
        
        .blog-tags label {
            font-weight: 600;
            color: #333;
            margin-right: 8px;
        }
        
        .blog-tag {
            display: inline-block;
            background: #f0f0f0;
            color: #666;
            padding: 6px 14px;
            border-radius: 20px;
            text-decoration: none;
            font-size: 13px;
            transition: all 0.3s;
        }
        
        .blog-tag:hover {
            background: #F07E2D;
            color: #fff;
        }
        
        .share-buttons {
            display: flex;
            gap: 12px;
        }
        
        .share-btn {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            border: 1px solid #ddd;
            background: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #666;
            text-decoration: none;
            transition: all 0.3s;
        }
        
        .share-btn:hover {
            background: #F07E2D;
            color: #fff;
            border-color: #F07E2D;
        }
        
        .blog-navigation {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin: 40px 0;
            padding: 30px 40px;
            border-top: 1px solid #eee;
        }
        
        .nav-post-link {
            display: flex;
            align-items: center;
            gap: 12px;
            color: #333;
            text-decoration: none;
            transition: color 0.3s;
        }
        
        .nav-post-link:hover {
            color: #F07E2D;
        }
        
        .nav-post-link.prev {
            flex-direction: row;
        }
        
        .nav-post-link.next {
            flex-direction: row-reverse;
            text-align: right;
        }
        
        .nav-post-label {
            font-size: 12px;
            color: #999;
            display: block;
            margin-bottom: 4px;
        }
        
        .nav-post-title {
            font-size: 14px;
            font-weight: 600;
            line-height: 1.4;
        }
        
        .related-posts-section {
            margin: 60px 0;
        }
        
        .section-title {
            font-size: 24px;
            font-weight: 700;
            color: #333;
            margin-bottom: 30px;
        }
        
        .related-posts-carousel {
            position: relative;
            overflow: hidden;
        }
        
        .related-posts-grid {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 20px;
            transition: transform 0.3s ease;
        }
        
        .related-post-card {
            background: #fff;
            border-radius: 8px;
            overflow: hidden;
            text-decoration: none;
            color: inherit;
            transition: transform 0.3s;
        }
        
        .related-post-card:hover {
            transform: translateY(-5px);
        }
        
        .related-post-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
        }
        
        .related-post-content {
            padding: 16px;
        }
        
        .related-post-category {
            font-size: 11px;
            color: #999;
            margin-bottom: 8px;
        }
        
        .related-post-title {
            font-size: 14px;
            font-weight: 600;
            color: #333;
            line-height: 1.4;
            margin: 0;
        }
        
        .comments-section {
            background: #fff;
            border-radius: 8px;
            padding: 40px;
            margin-bottom: 60px;
        }
        
        .comments-section h2 {
            font-size: 24px;
            font-weight: 700;
            color: #333;
            margin-bottom: 30px;
        }
        
        .comment-item {
            padding: 20px 0;
            border-bottom: 1px solid #eee;
        }
        
        .comment-item:last-child {
            border-bottom: none;
        }
        
        .comment-header {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 12px;
        }
        
        .comment-author {
            font-weight: 600;
            color: #333;
        }
        
        .comment-date {
            color: #999;
            font-size: 13px;
        }
        
        .comment-text {
            color: #666;
            line-height: 1.6;
            margin-bottom: 8px;
        }
        
        .comment-reply {
            color: #F07E2D;
            text-decoration: none;
            font-size: 13px;
        }
        
        .comment-form {
            margin-top: 40px;
        }
        
        .comment-form h2 {
            font-size: 24px;
            font-weight: 700;
            color: #333;
            margin-bottom: 12px;
        }
        
        .comment-form p {
            color: #666;
            font-size: 14px;
            margin-bottom: 24px;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
        }
        
        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            font-family: inherit;
        }
        
        .form-group textarea {
            min-height: 120px;
            resize: vertical;
        }
        
        .form-group.checkbox {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .form-group.checkbox input {
            width: auto;
        }
        
        .submit-btn {
            background: #F07E2D;
            color: #fff;
            border: none;
            padding: 12px 30px;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        .submit-btn:hover {
            background: #d16a95;
        }
        
        .blog-sidebar {
            display: flex;
            flex-direction: column;
            gap: 30px;
        }
        
        .sidebar-widget {
            background: #fff;
            padding: 30px;
            border-radius: 8px;
        }
        
        .sidebar-widget h3 {
            font-size: 18px;
            font-weight: 700;
            color: #333;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .sidebar-widget h3::before {
            content: '📂';
            font-size: 24px;
        }
        
        .search-widget h3::before {
            content: '🔍';
        }
        
        .categories-widget h3::before {
            content: '📂';
        }
        
        .recent-posts-widget h3::before {
            content: '📝';
        }
        
        .recent-comments-widget h3::before {
            content: '💬';
        }
        
        .tags-widget h3::before {
            content: '🏷️';
        }
        
        .search-form {
            display: flex;
            gap: 8px;
        }
        
        .search-form input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
        }
        
        .search-form button {
            background: #F07E2D;
            color: #fff;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
        }
        
        .categories-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        
        .categories-list li {
            margin-bottom: 12px;
        }
        
        .categories-list a {
            color: #666;
            text-decoration: none;
            transition: color 0.3s;
        }
        
        .categories-list a:hover {
            color: #F07E2D;
        }
        
        .recent-post-item {
            display: flex;
            gap: 12px;
            margin-bottom: 20px;
        }
        
        .recent-post-item:last-child {
            margin-bottom: 0;
        }
        
        .recent-post-image {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 6px;
            flex-shrink: 0;
        }
        
        .recent-post-content {
            flex: 1;
        }
        
        .recent-post-date {
            font-size: 12px;
            color: #999;
            margin-bottom: 4px;
        }
        
        .recent-post-title {
            font-size: 14px;
            font-weight: 600;
            color: #333;
            line-height: 1.4;
            text-decoration: none;
        }
        
        .recent-post-title:hover {
            color: #F07E2D;
        }
        
        .recent-comments-carousel {
            position: relative;
        }
        
        .comment-slide {
            display: none;
        }
        
        .comment-slide.active {
            display: block;
        }
        
        .comment-item-sidebar {
            margin-bottom: 20px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }
        
        .comment-item-sidebar:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }
        
        .comment-text-sidebar {
            font-size: 13px;
            color: #666;
            line-height: 1.6;
            margin-bottom: 8px;
            font-style: italic;
        }
        
        .comment-author-sidebar {
            font-size: 12px;
            color: #999;
        }
        
        .carousel-controls {
            display: flex;
            justify-content: space-between;
            margin-top: 16px;
        }
        
        .carousel-btn {
            background: #f5f5f5;
            border: none;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.3s;
        }
        
        .carousel-btn:hover:not(:disabled) {
            background: #F07E2D;
            color: #fff;
        }
        
        .carousel-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .tags-cloud {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }
        
        .tag-cloud-item {
            background: #f0f0f0;
            color: #666;
            padding: 6px 12px;
            border-radius: 4px;
            text-decoration: none;
            font-size: 12px;
            transition: all 0.3s;
        }
        
        .tag-cloud-item:hover {
            background: #F07E2D;
            color: #fff;
        }
        
        @media (max-width: 968px) {
            .blog-content-wrapper {
                grid-template-columns: 1fr;
            }
            
            .blog-sidebar {
                order: -1;
            }
            
            .related-posts-grid {
                grid-template-columns: repeat(3, 1fr);
            }
            
            .form-row {
                grid-template-columns: 1fr;
            }
        }
        
        @media (max-width: 640px) {
            .related-posts-grid {
                grid-template-columns: 1fr;
            }
            
            .blog-navigation {
                grid-template-columns: 1fr;
            }
            
            .blog-title {
                font-size: 24px;
            }
            
            .blog-header-content {
                padding: 20px;
            }
            
            .blog-featured-image {
                height: 300px;
            }
            
            .comments-section {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
  <?php include __DIR__ . '/header.php'; ?>
    <main>
  <div class="blog-page-wrapper">
    <?php if ($notFound): ?>
        <div style="text-align:center; padding:60px 20px;">
            <h1 style="font-size:48px; color:#e74c3c; margin-bottom:10px;">404</h1>
            <p style="color:#666; margin-bottom:20px;">Blog post not found.</p>
            <a href="blogs.php" style="display:inline-block; background:#3498db; color:#fff; padding:10px 20px; border-radius:4px; text-decoration:none; margin-right:10px;">Back to Blogs</a>
            <a href="index.php" style="display:inline-block; background:#F07E2D; color:#fff; padding:10px 20px; border-radius:4px; text-decoration:none;">Home</a>
        </div>
    <?php else: ?>
        <!-- Breadcrumb with Schema -->
        <?php
        // Build breadcrumb array
        $breadcrumbs = [
          ['title' => 'Home', 'url' => 'index.php'],
          ['title' => 'Blog', 'url' => 'blogs.php']
        ];
        if (!empty($blog['category_name'])) {
          $breadcrumbs[] = ['title' => htmlspecialchars($blog['category_name']), 'url' => 'blog_category.php?slug=' . htmlspecialchars($blog['category_slug'] ?? '')];
        }
        $breadcrumbs[] = ['title' => htmlspecialchars($blog['title']), 'url' => null];
        
        // Output breadcrumb with schema
        echo InternalLinkingHelper::generateBreadcrumb($breadcrumbs);
        echo InternalLinkingHelper::generateBreadcrumbSchema($breadcrumbs);
        ?>
        
        <div class="blog-content-wrapper">
            <!-- Main Content -->
            <article class="blog-main-content">
                <?php if ($blog['featured_image']): ?>
                <img src="uploads/blog/<?php echo htmlspecialchars($blog['featured_image']); ?>" alt="<?php echo htmlspecialchars($blog['title']); ?>" class="blog-featured-image">
                <?php endif; ?>
                
                <div class="blog-header-content">
                    <?php if ($blog['category_name']): ?>
                    <a href="blog_category.php?slug=<?php echo htmlspecialchars($blog['category_slug'] ?? ''); ?>" class="blog-category-badge">
                        <?php echo htmlspecialchars($blog['category_name']); ?>
                    </a>
                    <?php endif; ?>
                    
                    <h1 class="blog-title"><?php echo htmlspecialchars($blog['title']); ?></h1>
                    
                    <div class="blog-meta">
                        <div class="blog-meta-item">
                            <span>By</span>
                            <a href="#" style="color:#666; text-decoration:none;"><?php echo htmlspecialchars($blog['author_name'] ?? 'Admin'); ?></a>
                        </div>
                        <div class="blog-meta-item">
                            <span>On</span>
                            <span><?php echo date('M d, Y', strtotime($blog['publish_date'] ?? $blog['created_at'])); ?></span>
                        </div>
                        <div class="blog-meta-item">
                            <i class="fas fa-comments"></i>
                            <span><?php echo rand(0, 10); ?> Comments</span>
                        </div>
                    </div>
                    
                    <div class="blog-content-text">
                        <?php 
                          // Phase 3: Content Optimization for Blog Posts
                          $originalContent = $blog['content']; // Don't escape - content contains HTML
                          
                          $readability = ['level' => 'N/A', 'score' => 0, 'word_count' => 0, 'recommendations' => ''];
                          $suggestions = [];
                          
                          if (class_exists('ContentOptimizer')) {
                            // Calculate readability for blog content
                            $readability = ContentOptimizer::calculateReadability($originalContent);
                            
                            // Get content suggestions
                            $suggestions = ContentOptimizer::getContentSuggestions(
                              $originalContent, 
                              $blog['category_name'] ?? 'fashion'
                            );
                          }
                          
                          // Display optimized content - render HTML
                          echo $originalContent;
                        ?>
                    </div>
                    
                    <!-- Phase 3: Content Quality & Readability Score - ADMIN ONLY -->
                    <?php if ($readability['score'] > 0 && isset($_SESSION['is_admin']) && $_SESSION['is_admin'] === true): ?>
                    <div style="margin:30px 0; padding:20px; background:#fff3cd; border-left:4px solid #ff9800; border-radius:4px;">
                      <p style="margin:0 0 10px 0;"><strong>🔒 ADMIN ONLY - Article Readability:</strong> <span style="color:#2196F3; font-weight:bold;"><?php echo $readability['level']; ?></span> (Flesch Score: <?php echo number_format($readability['score'], 1); ?>/100)</p>
                      <p style="margin:0 0 10px 0; font-size:14px; color:#555;">Word Count: <strong><?php echo $readability['word_count']; ?> words</strong></p>
                      <?php if (!empty($readability['recommendations'])): ?>
                      <p style="margin:0; font-size:13px; color:#666; line-height:1.6;"><?php echo htmlspecialchars($readability['recommendations']); ?></p>
                      <?php endif; ?>
                    </div>
                    <?php endif; ?>
                    
                    <div class="blog-author-section">
                        <div class="author-avatar">
                            <?php echo strtoupper(substr($blog['author_name'] ?? 'A', 0, 1)); ?>
                        </div>
                        <div class="author-info">
                            <h4><?php echo htmlspecialchars($blog['author_name'] ?? 'Admin'); ?></h4>
                            <p>administrator</p>
                        </div>
                    </div>
                </div>
                
                <div class="blog-tags-share">
                    <div class="blog-tags">
                        <?php if (!empty($tags)): ?>
                        <label>Tags:</label>
                        <?php foreach ($tags as $tag): ?>
                        <a href="blog_tag.php?slug=<?php echo htmlspecialchars($tag['slug']); ?>" class="blog-tag">
                            <?php echo htmlspecialchars($tag['name']); ?>
                        </a>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                    <div class="share-buttons">
                        <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); ?>" target="_blank" class="share-btn">
                            <i class="fab fa-facebook-f"></i>
                        </a>
                        <a href="https://twitter.com/intent/tweet?url=<?php echo urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); ?>" target="_blank" class="share-btn">
                            <i class="fab fa-twitter"></i>
                        </a>
                        <a href="http://linkedin.com/shareArticle?mini=true&url=<?php echo urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); ?>" target="_blank" class="share-btn">
                            <i class="fab fa-linkedin-in"></i>
                        </a>
                        <a href="https://pinterest.com/pin/create/button/?url=<?php echo urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); ?>&media=<?php echo urlencode($blog['featured_image'] ? 'uploads/blog/' . $blog['featured_image'] : ''); ?>" target="_blank" class="share-btn">
                            <i class="fab fa-pinterest"></i>
                        </a>
                    </div>
                </div>
                
                <!-- Phase 2: Article Schema Markup (JSON-LD) -->
                <?php
                $articleSchema = SchemaHelper::generateArticleSchema([
                  'title' => $blog['title'],
                  'description' => $blog['meta_description'] ?: substr(strip_tags($blog['content']), 0, 160),
                  'content' => $blog['content'],
                  'image' => $blog['featured_image'] ? 'uploads/blog/' . $blog['featured_image'] : null,
                  'author' => $blog['author_name'] ?? 'Admin',
                  'published' => $blog['publish_date'] ?? $blog['created_at'],
                  'modified' => $blog['updated_at']
                ]);
                echo SchemaHelper::outputSchema($articleSchema, 'json-ld');
                ?>
                
                <?php if ($navigation['prev'] || $navigation['next']): ?>
                <div class="blog-navigation">
                    <?php if ($navigation['prev']): ?>
                    <a href="blog.php?slug=<?php echo htmlspecialchars($navigation['prev']['slug']); ?>" class="nav-post-link prev">
                        <i class="fas fa-chevron-left"></i>
                        <div>
                            <span class="nav-post-label">Previous Post</span>
                            <span class="nav-post-title"><?php echo htmlspecialchars(substr($navigation['prev']['title'], 0, 60)); ?></span>
                        </div>
                    </a>
                    <?php else: ?>
                    <div></div>
                    <?php endif; ?>
                    
                    <?php if ($navigation['next']): ?>
                    <a href="blog.php?slug=<?php echo htmlspecialchars($navigation['next']['slug']); ?>" class="nav-post-link next">
                        <i class="fas fa-chevron-right"></i>
                        <div>
                            <span class="nav-post-label">Next Post</span>
                            <span class="nav-post-title"><?php echo htmlspecialchars(substr($navigation['next']['title'], 0, 60)); ?></span>
                        </div>
                    </a>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                
                <!-- Phase 3: Blog Post FAQ Section -->
                <?php
                  $blogCategory = strtolower($blog['category_name'] ?? 'fashion');
                  // Map blog category to product category for FAQ lookup
                  $categoryMap = ['fashion tips' => 'women-clothing', 'style guide' => 'accessories', 'fashion' => 'women-clothing'];
                  $faqCategory = $categoryMap[$blogCategory] ?? 'women-clothing';
                  
                  $blogFAQData = FAQHelper::getFAQsWithSchema($faqCategory, 'blog-faq-' . $blog['id']);
                  
                  if (!empty($blogFAQData['faq']) && count($blogFAQData['faq']) > 0):
                ?>
                <div style="margin:40px 0; padding:40px; background:#f9f9f9; border-radius:8px;">
                  <h3 class="section-title">Common Questions About This Topic</h3>
                  <!-- Output FAQ Schema for Search Engines -->
                  <?php echo $blogFAQData['schema']; ?>
                  <!-- Display Interactive FAQ Accordion -->
                  <?php echo $blogFAQData['accordion']; ?>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($relatedPosts)): ?>
                <div style="padding:40px;">
                    <h3 class="section-title">Related posts</h3>
                    <div class="related-posts-carousel">
                        <div class="related-posts-grid" id="relatedPostsGrid">
                            <?php foreach ($relatedPosts as $post): ?>
                            <a href="blog.php?slug=<?php echo htmlspecialchars($post['slug']); ?>" class="related-post-card">
                                <?php if ($post['featured_image']): ?>
                                <img src="uploads/blog/<?php echo htmlspecialchars($post['featured_image']); ?>" alt="<?php echo htmlspecialchars($post['title']); ?>" class="related-post-image">
                                <?php endif; ?>
                                <div class="related-post-content">
                                    <div class="related-post-category"><?php echo htmlspecialchars($post['category_name'] ?? 'Blog'); ?> / <?php echo date('M d, Y', strtotime($post['publish_date'] ?? $post['created_at'])); ?></div>
                                    <h4 class="related-post-title"><?php echo htmlspecialchars(substr($post['title'], 0, 60)); ?></h4>
                                </div>
                            </a>
                            <?php endforeach; ?>
                        </div>
                        <div style="display:flex; justify-content:center; gap:12px; margin-top:20px;">
                            <button class="carousel-btn" onclick="slideRelatedPosts('prev')" id="prevRelatedBtn">
                                <i class="fas fa-chevron-left"></i>
                            </button>
                            <button class="carousel-btn" onclick="slideRelatedPosts('next')" id="nextRelatedBtn">
                                <i class="fas fa-chevron-right"></i>
                            </button>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <div class="comments-section">
                    <h2><?php echo rand(0, 10); ?>Comments</h2>
                    
                    <div class="comment-item">
                        <div class="comment-header">
                            <span class="comment-author">Sofia</span>
                            <span class="comment-date"><?php echo date('M d, Y', strtotime('-5 days')); ?></span>
                        </div>
                        <div class="comment-text">
                            Phasellus vitae imperdiet felis. Nam non condimentum erat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla tortor arcu, consectetur eleifend commodo at, consectetur eu justo.
                        </div>
                        <a href="#" class="comment-reply">Reply</a>
                        
                        <div style="margin-left:40px; margin-top:20px;">
                            <div class="comment-item">
                                <div class="comment-header">
                                    <span class="comment-author">Sofia</span>
                                    <span class="comment-date"><?php echo date('M d, Y', strtotime('-2 days')); ?></span>
                                </div>
                                <div class="comment-text">
                                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla tortor arcu, consectetur eleifend commodo at, consectetur eu justo.
                                </div>
                                <a href="#" class="comment-reply">Reply</a>
                            </div>
                            <div class="comment-item">
                                <div class="comment-header">
                                    <span class="comment-author">John Hennry</span>
                                    <span class="comment-date"><?php echo date('M d, Y', strtotime('-4 days')); ?></span>
                                </div>
                                <div class="comment-text">
                                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla tortor arcu, consectetur eleifend commodo at, consectetur eu justo.
                                </div>
                                <a href="#" class="comment-reply">Reply</a>
                            </div>
                        </div>
                    </div>
                    
                    <div class="comment-item">
                        <div class="comment-header">
                            <span class="comment-author">John Doe</span>
                            <span class="comment-date"><?php echo date('M d, Y', strtotime('-6 days')); ?></span>
                        </div>
                        <div class="comment-text">
                            Phasellus vitae imperdiet felis. Nam non condimentum erat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla tortor arcu, consectetur eleifend commodo at, consectetur eu justo.
                        </div>
                        <a href="#" class="comment-reply">Reply</a>
                    </div>
                    
                    <div class="comment-form">
                        <h2>Leave a Comment</h2>
                        <p>Your email address will not be published. Required fields are marked *</p>
                        <form method="post" action="#">
                            <div class="form-row">
                                <div class="form-group">
                                    <label>Your name*</label>
                                    <input type="text" name="name" required>
                                </div>
                                <div class="form-group">
                                    <label>Your email address*</label>
                                    <input type="email" name="email" required>
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Write your message here*</label>
                                <textarea name="message" required></textarea>
                            </div>
                            <div class="form-group checkbox">
                                <input type="checkbox" name="save_info" id="saveInfo">
                                <label for="saveInfo" style="margin:0; font-weight:400;">Save my name, email in this browser for the next time comment</label>
                            </div>
                            <button type="submit" class="submit-btn">Post comment</button>
                        </form>
                    </div>
                </div>
            </article>
            
            <!-- Sidebar -->
            <aside class="blog-sidebar">
                <div class="sidebar-widget search-widget">
                    <h3>Search</h3>
                    <form method="get" action="blogs.php" class="search-form">
                        <input type="text" name="search" placeholder="Search for products...">
                        <button type="submit"><i class="fas fa-search"></i></button>
                    </form>
                </div>
                
                <div class="sidebar-widget categories-widget">
                    <h3>Categories</h3>
                    <ul class="categories-list">
                        <li><a href="blogs.php">All Categories</a> (<?php echo getBlogCount($conn, []); ?>)</li>
                        <?php
                        $allCategories = getBlogCategories($conn);
                        foreach ($allCategories as $cat): 
                        ?>
                        <li><a href="blog_category.php?slug=<?php echo htmlspecialchars($cat['slug']); ?>"><?php echo htmlspecialchars($cat['name']); ?></a> (<?php echo $cat['count']; ?>)</li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                
                <div class="sidebar-widget recent-posts-widget">
                    <h3>Recent Posts</h3>
                    <?php foreach ($recentPosts as $recent): ?>
                    <div class="recent-post-item">
                        <?php if ($recent['featured_image']): ?>
                        <img src="uploads/blog/<?php echo htmlspecialchars($recent['featured_image']); ?>" alt="<?php echo htmlspecialchars($recent['title']); ?>" class="recent-post-image">
                        <?php endif; ?>
                        <div class="recent-post-content">
                            <div class="recent-post-date"><?php echo date('M d, Y', strtotime($recent['publish_date'] ?? $recent['created_at'])); ?></div>
                            <a href="blog.php?slug=<?php echo htmlspecialchars($recent['slug']); ?>" class="recent-post-title">
                                <?php echo htmlspecialchars(substr($recent['title'], 0, 60)); ?>
                            </a>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                
                <div class="sidebar-widget recent-comments-widget">
                    <h3>Recent Comments</h3>
                    <div class="recent-comments-carousel">
                        <?php if (!empty($recentComments)): ?>
                        <?php 
                        $commentChunks = array_chunk($recentComments, 2);
                        foreach ($commentChunks as $idx => $chunk): 
                        ?>
                        <div class="comment-slide <?php echo $idx === 0 ? 'active' : ''; ?>" data-slide="<?php echo $idx; ?>">
                            <?php foreach ($chunk as $comment): ?>
                            <div class="comment-item-sidebar">
                                <div class="comment-text-sidebar">
                                    "<?php echo htmlspecialchars(substr($comment['content'], 0, 100)); ?>..."
                                </div>
                                <div class="comment-author-sidebar">
                                    By <a href="#" style="color:#F07E2D; text-decoration:none;"><?php echo htmlspecialchars($comment['author_name']); ?></a> / <?php echo date('M d, Y', strtotime($comment['created_at'])); ?>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php endforeach; ?>
                        <?php else: ?>
                        <div class="comment-slide active">
                            <div class="comment-item-sidebar">
                                <div class="comment-text-sidebar">
                                    "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla tortor arcu, consectetur eleifend commodo at..."
                                </div>
                                <div class="comment-author-sidebar">
                                    By <a href="#" style="color:#F07E2D; text-decoration:none;">Sofia</a> / <?php echo date('M d, Y', strtotime('-5 days')); ?>
                                </div>
                            </div>
                            <div class="comment-item-sidebar">
                                <div class="comment-text-sidebar">
                                    "Phasellus vitae imperdiet felis. Nam non condimentum erat. Lorem ipsum dolor sit amet, consectetur adipiscing..."
                                </div>
                                <div class="comment-author-sidebar">
                                    By <a href="#" style="color:#F07E2D; text-decoration:none;">John Doe</a> / <?php echo date('M d, Y', strtotime('-7 days')); ?>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                    <div class="carousel-controls">
                        <button class="carousel-btn" onclick="slideComments('prev')" id="prevCommentBtn">
                            <i class="fas fa-chevron-left"></i>
                        </button>
                        <button class="carousel-btn" onclick="slideComments('next')" id="nextCommentBtn">
                            <i class="fas fa-chevron-right"></i>
                        </button>
                    </div>
                </div>
                
                <div class="sidebar-widget tags-widget">
                    <h3>Tags</h3>
                    <div class="tags-cloud">
                        <?php
                        $popularTags = ['Accessories', 'Charm', 'Cosmetics', 'Electronics', 'Furnitures', 'Game', 'Jewellery', 'Lamp', 'Laptop', 'Luxury', 'New Arrivals', 'PC Gaming', 'Ring', 'Skincares', 'Smartwatches', 'T-Shirt', 'Table', 'Tech Accessories', 'Trend', 'Trousers', 'Watches'];
                        foreach (array_slice($popularTags, 0, 20) as $tag): 
                        ?>
                        <a href="shop.php?tag=<?php echo urlencode(strtolower($tag)); ?>" class="tag-cloud-item">
                            <?php echo htmlspecialchars($tag); ?>
                        </a>
                        <?php endforeach; ?>
                    </div>
                </div>
            </aside>
        </div>
    <?php endif; ?>
  </div>
    </main>
  <?php require_once 'footer.php'; ?>
  
  <script>
  let relatedPostsIndex = 0;
  let commentsIndex = 0;
  
  function slideRelatedPosts(direction) {
      const grid = document.getElementById('relatedPostsGrid');
      const items = grid.querySelectorAll('.related-post-card');
      const itemsPerView = window.innerWidth > 968 ? 5 : (window.innerWidth > 640 ? 3 : 1);
      const maxIndex = Math.max(0, items.length - itemsPerView);
      
      if (direction === 'next') {
          relatedPostsIndex = Math.min(relatedPostsIndex + 1, maxIndex);
      } else {
          relatedPostsIndex = Math.max(relatedPostsIndex - 1, 0);
      }
      
      const translateX = -(relatedPostsIndex * (100 / itemsPerView));
      grid.style.transform = `translateX(${translateX}%)`;
      
      document.getElementById('prevRelatedBtn').disabled = relatedPostsIndex === 0;
      document.getElementById('nextRelatedBtn').disabled = relatedPostsIndex >= maxIndex;
  }
  
  function slideComments(direction) {
      const slides = document.querySelectorAll('.comment-slide');
      if (slides.length === 0) return;
      
      if (direction === 'next') {
          commentsIndex = (commentsIndex + 1) % slides.length;
      } else {
          commentsIndex = (commentsIndex - 1 + slides.length) % slides.length;
      }
      
      slides.forEach((slide, idx) => {
          slide.classList.toggle('active', idx === commentsIndex);
      });
      
      document.getElementById('prevCommentBtn').disabled = commentsIndex === 0 && slides.length <= 1;
      document.getElementById('nextCommentBtn').disabled = commentsIndex === slides.length - 1 && slides.length <= 1;
  }
  
  // Initialize carousel buttons
  document.addEventListener('DOMContentLoaded', function() {
      const relatedItems = document.querySelectorAll('#relatedPostsGrid .related-post-card');
      if (relatedItems.length <= 5) {
          document.getElementById('prevRelatedBtn').style.display = 'none';
          document.getElementById('nextRelatedBtn').style.display = 'none';
      }
      
      const commentSlides = document.querySelectorAll('.comment-slide');
      if (commentSlides.length <= 1) {
          document.getElementById('prevCommentBtn').style.display = 'none';
          document.getElementById('nextCommentBtn').style.display = 'none';
      }
  });
  </script>
</body>
</html>
