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

$slug = $_GET['slug'] ?? '';
$id = $_GET['id'] ?? null;

$post = null;
if ($slug) {
    $post = getPostBySlug($slug);
} elseif ($id) {
    $post = getPostById($id);
}

// Fetch other published articles (prefer same category) for the sidebar navigation.
$pdo = getDB();
$related_posts = [];
try {
    if (!empty($post['category_id'])) {
        $rel_stmt = $pdo->prepare("SELECT p.id, p.slug, p.title, p.featured_image, p.created_at FROM posts p WHERE p.status='published' AND p.category_id = ? AND p.id != ? ORDER BY p.created_at DESC LIMIT 8");
        $rel_stmt->execute([$post['category_id'], $post['id']]);
        $related_posts = $rel_stmt->fetchAll();
    }
    if (count($related_posts) < 8) {
        $remaining = 8 - count($related_posts);
        $exclude = array_merge([$post['id'] ?? 0], array_column($related_posts, 'id'));
        $placeholders = rtrim(str_repeat('?,', count($exclude)), ',');
        $more_stmt = $pdo->prepare("SELECT p.id, p.slug, p.title, p.featured_image, p.created_at FROM posts p WHERE p.status='published' AND p.id NOT IN ($placeholders) ORDER BY p.created_at DESC LIMIT $remaining");
        $more_stmt->execute($exclude);
        $related_posts = array_merge($related_posts, $more_stmt->fetchAll());
    }
} catch (Exception $e) {
    $related_posts = [];
}

if (!$post) {
    header('HTTP/1.0 404 Not Found');
    $page_title = 'Post Not Found';
    $use_tailwind = true;
    include 'includes/header.php';
    ?>
    <div class="container">
        <div class="error-message">
            <h1>Post Not Found</h1>
            <p>The post you are looking for does not exist.</p>
            <a href="<?php echo BASE_URL; ?>home" class="btn btn-primary">Back to Home</a>
        </div>
    <?php
    include 'includes/footer.php';
    exit;
}

// Fetch previous and next posts
$prev_stmt = $pdo->prepare("SELECT slug, title FROM posts WHERE status='published' AND created_at < ? ORDER BY created_at DESC LIMIT 1");
$prev_stmt->execute([$post['created_at']]);
$prev_post = $prev_stmt->fetch();

$next_stmt = $pdo->prepare("SELECT slug, title FROM posts WHERE status='published' AND created_at > ? ORDER BY created_at ASC LIMIT 1");
$next_stmt->execute([$post['created_at']]);
$next_post = $next_stmt->fetch();

$page_title = $post['title'];

// Prepare Open Graph meta tags
$og_description = !empty($post['excerpt']) ? $post['excerpt'] : truncateText(strip_tags($post['content']), 160);
$og_image = !empty($post['featured_image']) ? BASE_URL . $post['featured_image'] : BASE_URL . 'assets/images/logo_1757657395.jpg'; // Default to site logo
$og_url = BASE_URL . 'post.php?slug=' . $post['slug'];
$site_name = getSiteSetting('site_name') ?: 'Mutalex Academy';

$use_tailwind = true;

// Add Open Graph and Twitter Card meta tags for social sharing
echo '<meta property="og:title" content="' . htmlspecialchars($post['title']) . '">' . "\n";
echo '<meta property="og:description" content="' . htmlspecialchars($og_description) . '">' . "\n";
echo '<meta property="og:image" content="' . htmlspecialchars($og_image) . '">' . "\n";
echo '<meta property="og:url" content="' . htmlspecialchars($og_url) . '">' . "\n";
echo '<meta property="og:type" content="article">' . "\n";
echo '<meta property="og:site_name" content="' . htmlspecialchars($site_name) . '">' . "\n";

// Twitter Card meta tags
echo '<meta name="twitter:card" content="summary_large_image">' . "\n";
echo '<meta name="twitter:title" content="' . htmlspecialchars($post['title']) . '">' . "\n";
echo '<meta name="twitter:description" content="' . htmlspecialchars($og_description) . '">' . "\n";
echo '<meta name="twitter:image" content="' . htmlspecialchars($og_image) . '">' . "\n";

include 'includes/header.php';
?>

<style>
    /* Scoped styles that mirror the resources/L5M9_tutorial_notes visual language */
    .post-l5 {
        --primary: #1a365d;
        --primary-light: #2c5282;
        --accent: #d69e2e;
        --accent-light: #ecc94b;
        --bg: #f7fafc;
        --card-bg: #ffffff;
        --text: #2d3748;
        --text-light: #718096;
        --border: #e2e8f0;
        --shadow: 0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06);
        --shadow-lg: 0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -2px rgba(0,0,0,0.05);

        font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
        background: var(--bg);
        color: var(--text);
        line-height: 1.7;
        font-size: 15px;
    }

    .post-l5 .l5-hero {
        background: linear-gradient(135deg, var(--primary) 0%, #234876 50%, var(--primary-light) 100%);
        color: white;
        padding: 56px 24px;
        text-align: center;
        position: relative;
        overflow: hidden;
    }

    .post-l5 .l5-hero::before {
        content: '';
        position: absolute;
        top: -50%;
        right: -20%;
        width: 600px;
        height: 600px;
        background: radial-gradient(circle, rgba(214,158,46,0.15) 0%, transparent 70%);
        border-radius: 50%;
    }

    .post-l5 .l5-hero-content {
        max-width: 900px;
        margin: 0 auto;
        position: relative;
        z-index: 1;
    }

    .post-l5 .l5-badge {
        display: inline-block;
        background: var(--accent);
        color: white;
        padding: 6px 18px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 1px;
        margin-bottom: 20px;
    }

    .post-l5 .l5-hero h1 {
        font-size: 40px;
        font-weight: 800;
        margin-bottom: 16px;
        line-height: 1.2;
        letter-spacing: -1px;
    }

    .post-l5 .l5-hero-meta {
        display: flex;
        justify-content: center;
        gap: 28px;
        margin-top: 22px;
        flex-wrap: wrap;
    }

    .post-l5 .l5-hero-meta-item {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
        opacity: 0.92;
    }

    .post-l5 .l5-container {
        max-width: 1400px;
        margin: 0 auto;
        padding: 32px 24px;
        display: grid;
        grid-template-columns: 300px 1fr;
        gap: 32px;
        align-items: start;
    }

    /* Sidebar navigation */
    .post-l5 .l5-sidebar {
        position: sticky;
        top: 88px;
        max-height: calc(100vh - 110px);
        overflow-y: auto;
        padding-right: 8px;
    }

    .post-l5 .l5-sidebar::-webkit-scrollbar { width: 6px; }
    .post-l5 .l5-sidebar::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }

    .post-l5 .l5-toc-title {
        font-size: 13px;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 1px;
        color: var(--text-light);
        margin-bottom: 14px;
        padding-bottom: 8px;
        border-bottom: 2px solid var(--accent);
        display: inline-block;
    }

    .post-l5 .l5-article-link {
        display: flex;
        gap: 12px;
        align-items: flex-start;
        padding: 10px 12px;
        text-decoration: none;
        color: var(--text);
        font-size: 13px;
        border-radius: 8px;
        transition: all 0.2s;
        border-left: 3px solid transparent;
    }

    .post-l5 .l5-article-link:hover {
        background: var(--card-bg);
        border-left-color: var(--accent);
        color: var(--primary);
    }

    .post-l5 .l5-article-link.active {
        background: var(--card-bg);
        border-left-color: var(--accent);
        color: var(--primary);
        font-weight: 600;
    }

    .post-l5 .l5-article-thumb {
        width: 44px;
        height: 44px;
        border-radius: 8px;
        object-fit: cover;
        flex-shrink: 0;
        background: var(--primary-light);
    }

    .post-l5 .l5-article-thumb-fallback {
        width: 44px;
        height: 44px;
        border-radius: 8px;
        flex-shrink: 0;
        background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--accent-light);
        font-size: 16px;
    }

    .post-l5 .l5-article-title {
        line-height: 1.35;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

    .post-l5 .l5-article-date {
        display: block;
        font-size: 11px;
        color: var(--text-light);
        margin-top: 4px;
    }

    /* Main content card */
    .post-l5 .l5-main {
        background: var(--card-bg);
        border-radius: 16px;
        padding: 40px;
        box-shadow: var(--shadow);
    }

    .post-l5 .l5-author-row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid var(--border);
        padding-bottom: 20px;
        margin-bottom: 28px;
        gap: 16px;
        flex-wrap: wrap;
    }

    .post-l5 .l5-author {
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .post-l5 .l5-author-avatar {
        width: 44px;
        height: 44px;
        border-radius: 50%;
        background: var(--primary);
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 700;
        font-size: 16px;
    }

    .post-l5 .l5-author-name {
        font-weight: 600;
        color: var(--text);
        font-size: 14px;
        line-height: 1.2;
    }

    .post-l5 .l5-author-date {
        color: var(--text-light);
        font-size: 12px;
        display: flex;
        align-items: center;
        gap: 6px;
        margin-top: 3px;
    }

    .post-l5 .l5-follow-btn {
        font-size: 12px;
        font-weight: 600;
        padding: 8px 16px;
        border-radius: 8px;
        border: 1px solid var(--border);
        background: #fff;
        color: var(--text);
        cursor: pointer;
        transition: all 0.2s;
    }

    .post-l5 .l5-follow-btn:hover {
        background: var(--primary);
        color: #fff;
        border-color: var(--primary);
    }

    .post-l5 .l5-body {
        color: var(--text);
        font-size: 16px;
    }

    .post-l5 .l5-body h2 {
        font-size: 26px;
        font-weight: 800;
        color: var(--primary);
        margin: 32px 0 18px;
        padding-bottom: 10px;
        border-bottom: 3px solid var(--accent);
    }

    .post-l5 .l5-body h3 {
        font-size: 20px;
        font-weight: 700;
        color: var(--primary-light);
        margin: 26px 0 12px;
    }

    .post-l5 .l5-body p { margin-bottom: 16px; }

    .post-l5 .l5-body img {
        max-width: 100%;
        border-radius: 12px;
        margin: 16px 0;
    }

    .post-l5 .l5-body a { color: var(--primary-light); text-decoration: underline; }

    .post-l5 .l5-body blockquote {
        border-left: 4px solid var(--accent);
        background: #fffbeb;
        padding: 16px 20px;
        margin: 20px 0;
        border-radius: 0 12px 12px 0;
        font-style: italic;
        color: #744210;
    }

    /* Share + page navigation footer */
    .post-l5 .l5-footer {
        margin-top: 36px;
        padding-top: 28px;
        border-top: 1px solid var(--border);
    }

    .post-l5 .l5-share-title {
        font-weight: 700;
        font-size: 12px;
        color: var(--text-light);
        text-transform: uppercase;
        letter-spacing: 1px;
        margin-bottom: 12px;
    }

    .post-l5 .l5-share-links {
        display: flex;
        gap: 10px;
    }

    .post-l5 .l5-share-links a {
        width: 38px;
        height: 38px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 10px;
        background: #edf2f7;
        color: var(--text);
        text-decoration: none;
        transition: all 0.2s;
    }

    .post-l5 .l5-share-links a:hover { background: var(--primary); color: #fff; }

    .post-l5 .l5-pager {
        margin-top: 32px;
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 16px;
    }

    .post-l5 .l5-pager a {
        display: flex;
        flex-direction: column;
        padding: 18px 20px;
        border: 1px solid var(--border);
        border-radius: 12px;
        text-decoration: none;
        color: var(--text);
        transition: all 0.2s;
    }

    .post-l5 .l5-pager a.next { text-align: right; align-items: flex-end; }

    .post-l5 .l5-pager a:hover {
        border-color: var(--accent);
        background: #fffdf5;
    }

    .post-l5 .l5-pager .l5-pager-label {
        font-size: 11px;
        color: var(--text-light);
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 1px;
        margin-bottom: 6px;
    }

    .post-l5 .l5-pager .l5-pager-title {
        font-weight: 600;
        font-size: 14px;
        color: var(--primary);
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

    @media (max-width: 900px) {
        .post-l5 .l5-container { grid-template-columns: 1fr; }
        .post-l5 .l5-sidebar { position: static; max-height: none; }
        .post-l5 .l5-hero h1 { font-size: 30px; }
        .post-l5 .l5-main { padding: 24px; }
    }
</style>

<div class="post-l5">
    <!-- Hero -->
    <section class="l5-hero">
        <div class="l5-hero-content">
            <span class="l5-badge"><?php echo htmlspecialchars($post['category_name'] ?? 'Article'); ?></span>
            <h1><?php echo htmlspecialchars($post['title']); ?></h1>
            <div class="l5-hero-meta">
                <div class="l5-hero-meta-item">
                    <i class="far fa-user"></i>
                    <?php echo htmlspecialchars($post['author_name']); ?>
                </div>
                <div class="l5-hero-meta-item">
                    <i class="far fa-calendar"></i>
                    <?php echo formatDate($post['created_at']); ?>
                </div>
                <div class="l5-hero-meta-item">
                    <i class="far fa-clock"></i>
                    <?php echo isset($post['read_time']) ? htmlspecialchars($post['read_time']) : '5 min read'; ?>
                </div>
            </div>
        </div>
    </section>

    <div class="l5-container">
        <!-- Sidebar Navigation: other available articles -->
        <aside class="l5-sidebar">
            <div class="l5-toc-title">More Articles</div>
            <?php if (empty($related_posts)): ?>
                <p style="font-size:13px;color:var(--text-light);">No other articles yet.</p>
            <?php else: ?>
                <?php foreach ($related_posts as $article): ?>
                    <a href="post.php?slug=<?php echo htmlspecialchars($article['slug']); ?>"
                       class="l5-article-link<?php echo ($article['slug'] === ($post['slug'] ?? '')) ? ' active' : ''; ?>">
                        <?php if (!empty($article['featured_image'])): ?>
                            <img class="l5-article-thumb" src="<?php echo htmlspecialchars(BASE_URL . $article['featured_image']); ?>" alt="">
                        <?php else: ?>
                            <span class="l5-article-thumb-fallback"><i class="fas fa-newspaper"></i></span>
                        <?php endif; ?>
                        <span>
                            <span class="l5-article-title"><?php echo htmlspecialchars($article['title']); ?></span>
                            <span class="l5-article-date"><?php echo formatDate($article['created_at']); ?></span>
                        </span>
                    </a>
                <?php endforeach; ?>
            <?php endif; ?>
        </aside>

        <!-- Main Content -->
        <main class="l5-main">
            <div class="l5-author-row">
                <div class="l5-author">
                    <div class="l5-author-avatar"><?php echo htmlspecialchars(substr($post['author_name'], 0, 1)); ?></div>
                    <div>
                        <div class="l5-author-name"><?php echo htmlspecialchars($post['author_name']); ?></div>
                        <div class="l5-author-date"><i class="far fa-calendar"></i> <?php echo formatDate($post['created_at']); ?></div>
                    </div>
                </div>
                <button type="button" class="l5-follow-btn">Follow</button>
            </div>

            <article class="l5-body">
                <?php echo $post['content']; ?>
            </article>

            <footer class="l5-footer">
                <h3 class="l5-share-title">Share this post</h3>
                <div class="l5-share-links">
                    <a href="https://twitter.com/intent/tweet?text=<?php echo urlencode($post['title']); ?>&url=<?php echo urlencode(BASE_URL . 'post.php?slug=' . $post['slug']); ?>" target="_blank" title="Share on Twitter"><i class="fab fa-twitter"></i></a>
                    <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode(BASE_URL . 'post.php?slug=' . $post['slug']); ?>" target="_blank" title="Share on Facebook"><i class="fab fa-facebook"></i></a>
                    <a href="https://www.linkedin.com/sharing/share-offsite/?url=<?php echo urlencode(BASE_URL . 'post.php?slug=' . $post['slug']); ?>" target="_blank" title="Share on LinkedIn"><i class="fab fa-linkedin"></i></a>
                </div>

                <div class="l5-pager">
                    <?php if ($prev_post): ?>
                        <a href="post.php?slug=<?php echo htmlspecialchars($prev_post['slug']); ?>">
                            <span class="l5-pager-label"><i class="fas fa-arrow-left"></i> Previous</span>
                            <span class="l5-pager-title"><?php echo htmlspecialchars($prev_post['title']); ?></span>
                        </a>
                    <?php else: ?>
                        <span></span>
                    <?php endif; ?>
                    <?php if ($next_post): ?>
                        <a href="post.php?slug=<?php echo htmlspecialchars($next_post['slug']); ?>" class="next">
                            <span class="l5-pager-label">Next <i class="fas fa-chevron-right"></i></span>
                            <span class="l5-pager-title"><?php echo htmlspecialchars($next_post['title']); ?></span>
                        </a>
                    <?php else: ?>
                        <span></span>
                    <?php endif; ?>
                </div>
            </footer>
        </main>
    </div>
</div>

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