<?php
require "core.php";

// Load SEO features only if files exist (for production compatibility)
if (file_exists("includes/breadcrumb_schema.php")) {
    require "includes/breadcrumb_schema.php";
}
if (file_exists("includes/advanced_seo_system.php")) {
    require "includes/advanced_seo_system.php";
}

// Check if preview mode
$isPreview = isset($_GET['preview']) && $_GET['preview'] == 1 && isset($_SESSION['user_email']);
$previewId = isset($_GET['preview_id']) ? intval($_GET['preview_id']) : 0;

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

if (empty($slug)) {
    header('Location: ' . SITE_URL . '/Post');
    exit;
}

// Get blog post (include drafts if preview mode)
$statusCondition = $isPreview ? "" : "AND bp.post_status = 'published'";
$stmt = $connect->prepare("SELECT bp.*, bc.blog_cat_name, bc.blog_cat_slug, 
                           u.user_name, u.user_bio, u.user_facebook, u.user_twitter, 
                           u.user_instagram, u.user_linkedin, u.user_website, u.user_avatar
                           FROM blog_posts bp
                           LEFT JOIN blog_categories bc ON bp.post_category = bc.blog_cat_id
                           LEFT JOIN users u ON bp.post_author = u.user_id
                           WHERE bp.post_slug = :slug $statusCondition");
$stmt->execute([':slug' => $slug]);
$post = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$post) {
    header('Location: ' . SITE_URL . '/Post');
    exit;
}

// Calculate reading time
$word_count = str_word_count(strip_tags($post['post_content']));
$reading_time = ceil($word_count / 200); // 200 words per minute
$post['reading_time'] = $reading_time;

// Generate breadcrumb schema (if class exists)
if (class_exists('BreadcrumbSchema')) {
    $breadcrumb = BreadcrumbSchema::forBlogPost(
        $post['post_title'],
        $post['post_slug'],
        $post['blog_cat_name'] ?? '',
        $post['blog_cat_slug'] ?? ''
    );
}

// Generate SEO meta tags (if class exists)
if (class_exists('AdvancedSEOSystem')) {
    $seo = new AdvancedSEOSystem($connect, 'https://alonedeals.com');
}

// Generate SEO meta tags
$seo = new AdvancedSEOSystem($connect, 'https://alonedeals.com');

// Increment view count (not in preview mode)
if (!$isPreview) {
    $connect->prepare("UPDATE blog_posts SET post_views = post_views + 1 WHERE post_id = :id")
            ->execute([':id' => $post['post_id']]);
}

// Get related posts
$relatedPosts = [];
if ($post['post_category']) {
    $stmt = $connect->prepare("SELECT * FROM blog_posts 
                               WHERE post_category = :cat AND post_id != :id AND post_status = 'published'
                               ORDER BY published_at DESC LIMIT 3");
    $stmt->execute([':cat' => $post['post_category'], ':id' => $post['post_id']]);
    $relatedPosts = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// SEO - Enhanced for better ranking with AI-powered meta generation
require_once 'includes/seo_meta_generator.php';

$seoGenerator = new SEO_Meta_Generator($connect);

// Prepare data for meta generation
$metaData = [
    'type' => 'blog',
    'title' => $post['post_title'],
    'seo_title' => $post['post_seo_title'],
    'seo_description' => $post['post_seo_description'],
    'content' => $post['post_content'],
    'url' => SITE_URL . '/Post/' . $post['post_slug'],
    'image' => $featuredImageUrl,
    'keywords' => $post['post_tags'],
    'og_type' => 'article',
    'published_at' => $post['published_at'] ?: $post['created_at'],
    'updated_at' => $post['updated_at'] ?: $post['created_at'],
    'author_name' => $authorName
];

// Generate optimized meta tags
$titleSeoHeader = $seoGenerator->generate_title($metaData);
$descriptionSeoHeader = $seoGenerator->generate_description($metaData);
$canonicalUrl = SITE_URL . '/Post/' . $post['post_slug'];
$pageTitle = $post['post_title'];

// Generate excerpt for meta description if not available
$metaDescription = $descriptionSeoHeader;

// Get featured image URL
$featuredImageUrl = '';
if ($post['post_featured_image']) {
    if ($post['post_use_cdn'] && $post['post_featured_image_cdn_url']) {
        $featuredImageUrl = $post['post_featured_image_cdn_url'];
    } else {
        $featuredImageUrl = SITE_URL . '/images/' . $post['post_featured_image'];
    }
}

// Prepare keywords for meta tags
$keywords = $post['post_tags'] ? str_replace(',', ', ', $post['post_tags']) : '';

// Author information
$authorName = $post['user_name'] ?: 'Admin';
$publishedDate = date('c', strtotime($post['published_at'] ?: $post['created_at']));
$modifiedDate = date('c', strtotime($post['updated_at'] ?: $post['created_at']));

// Breadcrumb schema
$breadcrumbSchema = [
    '@context' => 'https://schema.org',
    '@type' => 'BreadcrumbList',
    'itemListElement' => [
        [
            '@type' => 'ListItem',
            'position' => 1,
            'name' => 'Home',
            'item' => SITE_URL
        ],
        [
            '@type' => 'ListItem',
            'position' => 2,
            'name' => 'Blog',
            'item' => SITE_URL . '/Post'
        ],
        [
            '@type' => 'ListItem',
            'position' => 3,
            'name' => $post['post_title'],
            'item' => $canonicalUrl
        ]
    ]
];

// Article schema for rich snippets
$articleSchema = [
    '@context' => 'https://schema.org',
    '@type' => 'Article',
    'headline' => $post['post_title'],
    'description' => $metaDescription,
    'image' => $featuredImageUrl,
    'datePublished' => $publishedDate,
    'dateModified' => $modifiedDate,
    'author' => [
        '@type' => 'Person',
        'name' => $authorName,
        'url' => SITE_URL . '/author/' . $post['post_author']
    ],
    'publisher' => [
        '@type' => 'Organization',
        'name' => $settings['st_sitename'],
        'logo' => [
            '@type' => 'ImageObject',
            'url' => SITE_URL . '/images/logo.png'
        ]
    ],
    'mainEntityOfPage' => [
        '@type' => 'WebPage',
        '@id' => $canonicalUrl
    ]
];

if ($post['blog_cat_name']) {
    $articleSchema['articleSection'] = $post['blog_cat_name'];
}

if ($keywords) {
    $articleSchema['keywords'] = $keywords;
}

// Set itemDetails for ad views
$itemDetails = [
    'page_ad_header' => 1,
    'page_ad_footer' => 1,
    'page_footer' => 1
];

include './header.php';

// Add SEO meta tags and structured data
?>
<!-- Enhanced SEO Meta Tags -->
<meta name="description" content="<?php echo htmlspecialchars($metaDescription); ?>">
<?php if ($keywords): ?>
<meta name="keywords" content="<?php echo htmlspecialchars($keywords); ?>">
<?php endif; ?>
<meta name="author" content="<?php echo htmlspecialchars($authorName); ?>">
<link rel="canonical" href="<?php echo $canonicalUrl; ?>">

<!-- Open Graph / Facebook -->
<meta property="og:type" content="article">
<meta property="og:url" content="<?php echo $canonicalUrl; ?>">
<meta property="og:title" content="<?php echo htmlspecialchars($post['post_title']); ?>">
<meta property="og:description" content="<?php echo htmlspecialchars($metaDescription); ?>">
<?php if ($featuredImageUrl): ?>
<meta property="og:image" content="<?php echo $featuredImageUrl; ?>">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<?php endif; ?>
<meta property="og:site_name" content="<?php echo htmlspecialchars($settings['st_sitename']); ?>">
<meta property="article:published_time" content="<?php echo $publishedDate; ?>">
<meta property="article:modified_time" content="<?php echo $modifiedDate; ?>">
<meta property="article:author" content="<?php echo htmlspecialchars($authorName); ?>">
<?php if ($post['blog_cat_name']): ?>
<meta property="article:section" content="<?php echo htmlspecialchars($post['blog_cat_name']); ?>">
<?php endif; ?>
<?php if ($keywords): 
    $tagArray = explode(',', $keywords);
    foreach ($tagArray as $tag): ?>
<meta property="article:tag" content="<?php echo htmlspecialchars(trim($tag)); ?>">
<?php endforeach; endif; ?>

<!-- Twitter Card -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:url" content="<?php echo $canonicalUrl; ?>">
<meta name="twitter:title" content="<?php echo htmlspecialchars($post['post_title']); ?>">
<meta name="twitter:description" content="<?php echo htmlspecialchars($metaDescription); ?>">
<?php if ($featuredImageUrl): ?>
<meta name="twitter:image" content="<?php echo $featuredImageUrl; ?>">
<?php endif; ?>

<!-- Structured Data - JSON-LD -->
<script type="application/ld+json">
<?php echo json_encode($breadcrumbSchema, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); ?>
</script>

<script type="application/ld+json">
<?php echo json_encode($articleSchema, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); ?>
</script>

<?php
include './sections/header.php';
include './sections/views/header-ad.view.php';

// Show preview banner if in preview mode
if ($isPreview && isset($_SESSION['user_email'])) {
    echo '<div style="background: #ff9800; color: white; padding: 15px; text-align: center; position: sticky; top: 0; z-index: 9999; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">';
    echo '<strong>🔍 PREVIEW MODE</strong> - This is how your post will look on the website';
    echo '<a href="' . SITE_URL . '/admin/controller/edit_blog.php?id=' . $post['post_id'] . '" style="color: white; text-decoration: underline; margin-left: 15px; font-weight: bold;">← Back to Editor</a>';
    echo '</div>';
}

include './views/single-blog.view.php';
include './sections/views/footer-ad.view.php';
include './sections/footer.php';
include './footer.php';
?>
