<?php
require_once 'includes/config.php';

// Get post slug from URL
$slug = isset($_GET['slug']) ? trim($_GET['slug']) : '';

if (empty($slug)) {
    header('Location: ' . BASE_URL . 'blog');
    exit;
}

// Fetch post details from database
$query = "SELECT p.*, c.name as category_name 
          FROM posts p 
          LEFT JOIN categories c ON p.category_id = c.id 
          WHERE p.slug = ? AND p.post_type = 'blog' AND p.status = 'published' 
          LIMIT 1";
$stmt = mysqli_prepare($conn, $query);

if (!$stmt) {
    die("Database error: " . mysqli_error($conn));
}

mysqli_stmt_bind_param($stmt, "s", $slug);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$post = mysqli_fetch_assoc($result);

// Validate that post exists
if (!$post || !is_array($post) || !isset($post['title']) || empty($post['title'])) {
    header('Location: ' . BASE_URL . 'blog');
    exit;
}

// Dynamic SEO Meta Tags
$page_title = htmlspecialchars($post['title']);
$seo_title = htmlspecialchars($post['title']);
$seo_description = !empty($post['excerpt']) ? htmlspecialchars(substr(strip_tags($post['excerpt']), 0, 160)) : 'Read this article from OHPAG about ' . htmlspecialchars($post['title']);
$seo_keywords = 'OHPAG blog, oral health, ' . htmlspecialchars($post['category_name'] ?? '') . ', ' . htmlspecialchars($post['title']);
$seo_image = !empty($post['featured_image']) ? BASE_URL . htmlspecialchars($post['featured_image']) : BASE_URL . 'assets/images/background/page-title.jpg';
$seo_type = 'article';
$canonical_url = BASE_URL . 'post/' . htmlspecialchars($slug);
$seo_author = !empty($post['author']) ? htmlspecialchars($post['author']) : SITE_TITLE;

// Article structured data
$structured_data = '<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "Article",
  "headline": "' . htmlspecialchars($post['title']) . '",
  "image": "' . $seo_image . '",
  "datePublished": "' . date('c', strtotime($post['published_at'] ?? $post['created_at'])) . '",
  "dateModified": "' . date('c', strtotime($post['updated_at'] ?? $post['created_at'])) . '",
  "author": {
    "@type": "Person",
    "name": "' . $seo_author . '"
  },
  "publisher": {
    "@type": "Organization",
    "name": "' . htmlspecialchars(SITE_TITLE) . '",
    "logo": {
      "@type": "ImageObject",
      "url": "' . BASE_URL . 'assets/images/logo.webp"
    }
  },
  "description": "' . htmlspecialchars(substr(strip_tags($post['excerpt'] ?? $post['content']), 0, 200)) . '"
}
</script>';

// Update view count
$update_query = "UPDATE posts SET views = views + 1 WHERE id = ?";
$update_stmt = mysqli_prepare($conn, $update_query);
mysqli_stmt_bind_param($update_stmt, "i", $post['id']);
mysqli_stmt_execute($update_stmt);

// Fetch related posts
$related_query = "SELECT * FROM posts 
                  WHERE post_type = 'blog' 
                  AND status = 'published' 
                  AND id != ? 
                  AND (category_id = ? OR category_id IS NULL)
                  ORDER BY published_at DESC 
                  LIMIT 3";
$related_stmt = mysqli_prepare($conn, $related_query);
mysqli_stmt_bind_param($related_stmt, "ii", $post['id'], $post['category_id']);
mysqli_stmt_execute($related_stmt);
$related_result = mysqli_stmt_get_result($related_stmt);
$related_posts = [];
while ($related = mysqli_fetch_assoc($related_result)) {
    $related_posts[] = $related;
}

// Fetch recent posts for sidebar
$recent_query = "SELECT * FROM posts WHERE post_type = 'blog' AND status = 'published' ORDER BY published_at DESC LIMIT 5";
$recent_result = mysqli_query($conn, $recent_query);
$recent_posts = [];
if ($recent_result) {
    while ($recent = mysqli_fetch_assoc($recent_result)) {
        $recent_posts[] = $recent;
    }
}

$page_title = htmlspecialchars($post['title']);

// SEO Meta Tags
$seo_title = htmlspecialchars($post['title']);
$seo_description = !empty($post['excerpt']) ? htmlspecialchars(substr($post['excerpt'], 0, 160)) : htmlspecialchars(substr(strip_tags($post['content']), 0, 160));
$seo_keywords = 'OHPAG, oral health Ghana, dental news Ghana, ' . (!empty($post['category_name']) ? htmlspecialchars($post['category_name']) . ', ' : '') . htmlspecialchars($post['title']);
$seo_image = !empty($post['featured_image']) ? BASE_URL . htmlspecialchars($post['featured_image']) : BASE_URL . 'assets/images/logo.webp';
$seo_type = 'article';
$canonical_url = BASE_URL . 'post/' . htmlspecialchars($post['slug']);
$seo_author = 'OHPAG';

// Structured Data for Blog Post
$post_date = !empty($post['published_at']) ? $post['published_at'] : $post['created_at'];
$structured_data = '
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "' . htmlspecialchars($post['title']) . '",
  "description": "' . htmlspecialchars($seo_description) . '",
  "image": "' . htmlspecialchars($seo_image) . '",
  "datePublished": "' . date('c', strtotime($post_date)) . '",
  "dateModified": "' . date('c', strtotime($post['updated_at'])) . '",
  "author": {
    "@type": "Organization",
    "name": "' . htmlspecialchars(SITE_NAME) . '"
  },
  "publisher": {
    "@type": "Organization",
    "name": "' . htmlspecialchars(SITE_TITLE) . '",
    "logo": {
      "@type": "ImageObject",
      "url": "' . BASE_URL . 'assets/images/logo.webp"
    }
  },
  "mainEntityOfPage": {
    "@type": "WebPage",
    "@id": "' . BASE_URL . 'post/' . htmlspecialchars($post['slug']) . '"
  }' . (!empty($post['category_name']) ? ',
  "articleSection": "' . htmlspecialchars($post['category_name']) . '"' : '') . ',
  "wordCount": ' . str_word_count(strip_tags($post['content'])) . ',
  "inLanguage": "en-GB"
}
</script>

<!-- Article Metadata -->
<meta property="article:published_time" content="' . date('c', strtotime($post_date)) . '">
<meta property="article:modified_time" content="' . date('c', strtotime($post['updated_at'])) . '">
<meta property="article:author" content="OHPAG">
' . (!empty($post['category_name']) ? '<meta property="article:section" content="' . htmlspecialchars($post['category_name']) . '">' : '') . '
';

require_once 'includes/header.php';
?>

<!-- page-title -->
<section class="page-title">
    <div class="bg-layer" style="background-image: url(<?php echo BASE_URL; ?>assets/images/background/page-title.jpg);"></div>
    <div class="auto-container">
        <div class="content-box">
            <h1><?php echo htmlspecialchars($post['title']); ?></h1>
            <ul class="bread-crumb clearfix">
                <li><a href="<?php echo BASE_URL; ?>index">Home</a></li>
                <li><a href="<?php echo BASE_URL; ?>blog">Blog</a></li>
                <li><?php echo htmlspecialchars($post['title']); ?></li>
            </ul>
        </div>
    </div>
</section>
<!-- page-title end -->

<!-- sidebar-page-container -->
<section class="sidebar-page-container" style="padding: 100px 0 80px;">
    <div class="auto-container">
        <div class="row clearfix">
            <div class="col-lg-9 col-md-12 col-sm-12 content-side">
                <div class="blog-details-content">
                    <div class="news-block-two">
                        <div class="inner-box">
                            <?php if (!empty($post['featured_image'])): ?>
                            <div class="image-box">
                                <figure class="image"><img src="<?php echo BASE_URL . htmlspecialchars($post['featured_image']); ?>" alt="<?php echo htmlspecialchars($post['title']); ?>"></figure>
                            </div>
                            <?php endif; ?>
                            <div class="lower-content" style="padding: 30px;">
                                <div class="upper-box" style="margin-bottom: 25px; padding-bottom: 20px; border-bottom: 2px solid #f0f0f0;">
                                    <span class="post-date" style="display: inline-block; padding: 8px 20px; background: var(--primary-color); color: #fff; border-radius: 5px; font-size: 14px; font-weight: 600; margin-right: 15px;">
                                        <?php 
                                        $post_date = !empty($post['published_at']) ? strtotime($post['published_at']) : strtotime($post['created_at']);
                                        echo date('d M, Y', $post_date);
                                        ?>
                                    </span>
                                    <ul class="post-info clearfix" style="display: inline-flex; gap: 20px; list-style: none; padding: 0; margin: 0;">
                                        <li style="font-size: 14px; color: #666;"><i class="flaticon-user" style="margin-right: 8px; color: var(--primary-color);"></i>By: OHPAG</li>
                                        <?php if (!empty($post['category_name'])): ?>
                                        <li style="font-size: 14px; color: #666;"><i class="flaticon-folder" style="margin-right: 8px; color: var(--primary-color);"></i><a href="<?php echo BASE_URL; ?>blog?category=<?php echo $post['category_id']; ?>" style="color: #666; text-decoration: none;"><?php echo htmlspecialchars($post['category_name']); ?></a></li>
                                        <?php endif; ?>
                                        <li style="font-size: 14px; color: #666;"><i class="flaticon-eye" style="margin-right: 8px; color: var(--primary-color);"></i><?php echo number_format($post['views']); ?> Views</li>
                                    </ul>
                                </div>
                                <h2 style="font-size: 32px; font-weight: 700; margin-bottom: 20px; color: #222; line-height: 1.3;"><?php echo htmlspecialchars($post['title']); ?></h2>
                                <?php if (!empty($post['excerpt'])): ?>
                                <p class="lead" style="font-size: 18px; line-height: 1.6; color: #555; margin-bottom: 30px; padding: 20px; background: #f8f9fa; border-left: 4px solid var(--primary-color); border-radius: 5px;"><strong><?php echo htmlspecialchars($post['excerpt']); ?></strong></p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <div class="content-one" style="padding: 30px; line-height: 1.8; color: #444; font-size: 16px;">
                        <?php echo $post['content']; ?>
                    </div>
                    
                    <!-- Share Section -->
                    <div class="post-share-option" style="padding: 30px; background: #f8f9fa; border-radius: 8px; margin-top: 40px;">
                        <div class="row clearfix">
                            <div class="col-lg-6 col-md-6 col-sm-12 left-column">
                                <?php if (!empty($post['category_name'])): ?>
                                <div class="tags" style="display: flex; align-items: center; gap: 10px;">
                                    <span style="font-weight: 600; color: #444;">Category:</span>
                                    <a href="<?php echo BASE_URL; ?>blog?category=<?php echo $post['category_id']; ?>" style="display: inline-block; padding: 8px 20px; background: var(--primary-color); color: #fff; border-radius: 5px; text-decoration: none; font-size: 14px; font-weight: 600;"><?php echo htmlspecialchars($post['category_name']); ?></a>
                                </div>
                                <?php endif; ?>
                            </div>
                            <div class="col-lg-6 col-md-6 col-sm-12 right-column">
                                <ul class="social-links clearfix" style="display: flex; align-items: center; justify-content: flex-end; gap: 10px; list-style: none; padding: 0; margin: 0;">
                                    <li style="font-weight: 600; color: #444;"><span>Share:</span></li>
                                    <li><a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($_SERVER['REQUEST_URI']); ?>" target="_blank" style="display: flex; align-items: center; justify-content: center; width: 40px; height: 40px; background: #3b5998; color: #fff; border-radius: 50%; text-decoration: none; transition: all 0.3s;"><i class="fab fa-facebook-f"></i></a></li>
                                    <li><a href="https://twitter.com/intent/tweet?url=<?php echo urlencode($_SERVER['REQUEST_URI']); ?>&text=<?php echo urlencode($post['title']); ?>" target="_blank" style="display: flex; align-items: center; justify-content: center; width: 40px; height: 40px; background: #1da1f2; color: #fff; border-radius: 50%; text-decoration: none; transition: all 0.3s;"><i class="fab fa-twitter"></i></a></li>
                                    <li><a href="https://www.linkedin.com/shareArticle?mini=true&url=<?php echo urlencode($_SERVER['REQUEST_URI']); ?>" target="_blank" style="display: flex; align-items: center; justify-content: center; width: 40px; height: 40px; background: #0077b5; color: #fff; border-radius: 50%; text-decoration: none; transition: all 0.3s;"><i class="fab fa-linkedin-in"></i></a></li>
                                    <li><a href="https://api.whatsapp.com/send?text=<?php echo urlencode($post['title'] . ' ' . $_SERVER['REQUEST_URI']); ?>" target="_blank" style="display: flex; align-items: center; justify-content: center; width: 40px; height: 40px; background: #25d366; color: #fff; border-radius: 50%; text-decoration: none; transition: all 0.3s;"><i class="fab fa-whatsapp"></i></a></li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if (count($related_posts) > 0): ?>
                <!-- Related Posts -->
                <div class="related-post" style="margin-top: 60px; padding-top: 40px; border-top: 2px solid #f0f0f0;">
                    <div class="group-title" style="margin-bottom: 40px;">
                        <h3 style="font-size: 28px; font-weight: 700; color: #222;">Related Posts</h3>
                    </div>
                    <div class="row clearfix" style="row-gap: 30px;">
                        <?php foreach ($related_posts as $related): ?>
                        <div class="col-lg-4 col-md-6 col-sm-12 news-block" style="margin-bottom: 30px;">
                            <div class="news-block-one">
                                <div class="inner-box" style="box-shadow: 0 5px 20px rgba(0,0,0,0.1); border-radius: 8px; overflow: hidden; transition: transform 0.3s ease;" onmouseover="this.style.transform='translateY(-5px)';" onmouseout="this.style.transform='translateY(0)';">
                                    <?php if (!empty($related['featured_image'])): ?>
                                    <figure class="image-box">
                                        <a href="<?php echo BASE_URL; ?>post/<?php echo htmlspecialchars($related['slug']); ?>">
                                            <img src="<?php echo BASE_URL . htmlspecialchars($related['featured_image']); ?>" alt="<?php echo htmlspecialchars($related['title']); ?>">
                                        </a>
                                    </figure>
                                    <?php endif; ?>
                                    <div class="lower-content" style="padding: 20px;">
                                        <h4 style="margin-bottom: 10px; font-size: 18px; line-height: 1.4;"><a href="<?php echo BASE_URL; ?>post/<?php echo htmlspecialchars($related['slug']); ?>" style="color: #222; text-decoration: none;"><?php echo htmlspecialchars($related['title']); ?></a></h4>
                                        <span class="post-date" style="font-size: 14px; color: #999;">
                                            <?php 
                                            $related_date = !empty($related['published_at']) ? strtotime($related['published_at']) : strtotime($related['created_at']);
                                            echo date('M d, Y', $related_date);
                                            ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <!-- Sidebar -->
            <div class="col-lg-3 col-md-12 col-sm-12 sidebar-side">
                <div class="blog-sidebar">
                    <!-- Recent Posts Widget -->
                    <?php if (count($recent_posts) > 0): ?>
                    <div class="sidebar-widget post-widget" style="background: #fff; padding: 30px; border-radius: 8px; box-shadow: 0 2px 15px rgba(0,0,0,0.1); margin-bottom: 30px;">
                        <div class="widget-title" style="margin-bottom: 25px; padding-bottom: 15px; border-bottom: 2px solid var(--primary-color);">
                            <h3 style="font-size: 22px; font-weight: 700; color: #222; margin: 0;">Recent Posts</h3>
                        </div>
                        <div class="widget-content">
                            <?php foreach ($recent_posts as $recent): ?>
                            <div class="post" style="display: flex; gap: 15px; margin-bottom: 20px; padding-bottom: 20px; border-bottom: 1px solid #f0f0f0;">
                                <?php if (!empty($recent['featured_image'])): ?>
                                <figure class="post-thumb" style="flex-shrink: 0; margin: 0; width: 80px; height: 80px; border-radius: 5px; overflow: hidden;">
                                    <a href="<?php echo BASE_URL; ?>post/<?php echo htmlspecialchars($recent['slug']); ?>">
                                        <img src="<?php echo BASE_URL . htmlspecialchars($recent['featured_image']); ?>" alt="<?php echo htmlspecialchars($recent['title']); ?>" style="width: 100%; height: 100%; object-fit: cover;">
                                    </a>
                                </figure>
                                <?php endif; ?>
                                <div style="flex: 1;">
                                <h5 style="margin-bottom: 8px; font-size: 16px; line-height: 1.4;"><a href="<?php echo BASE_URL; ?>post/<?php echo htmlspecialchars($recent['slug']); ?>" style="color: #222; text-decoration: none;"><?php echo htmlspecialchars($recent['title']); ?></a></h5>
                                <span class="post-date" style="font-size: 13px; color: #999;">
                                    <?php 
                                    $recent_date = !empty($recent['published_at']) ? strtotime($recent['published_at']) : strtotime($recent['created_at']);
                                    echo date('M d, Y', $recent_date);
                                    ?>
                                </span>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Contact Widget -->
                    <div class="sidebar-widget contact-widget" style="border-radius: 8px; overflow: hidden; box-shadow: 0 2px 15px rgba(0,0,0,0.1);">
                        <div class="widget-content" style="background-image: url(<?php echo BASE_URL; ?>assets/images/resource/sidebar-1.jpg); position: relative; padding: 40px 30px; text-align: center; background-size: cover; background-position: center;">
                            <div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7);"></div>
                            <div style="position: relative; z-index: 1;">
                            <h3 style="color: #fff; font-size: 24px; font-weight: 700; margin-bottom: 15px;">Have Questions?</h3>
                            <p style="color: #fff; margin-bottom: 25px; opacity: 0.9;">Contact us for more information</p>
                            <a href="<?php echo BASE_URL; ?>contact" style="display: inline-block; padding: 12px 35px; background: var(--primary-color); color: #fff; text-decoration: none; border-radius: 5px; font-weight: 600;">Contact Us</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
<!-- sidebar-page-container end -->

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

