<?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);
}

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
$pdo = getDB();
$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';
?>

    <main class="max-w-3xl mx-auto px-4 py-12 sm:py-20">
        <!-- Article Header -->
        <header class="mb-10">
            <div class="flex items-center gap-2 mb-4">
                <span class="px-3 py-1 bg-indigo-50 text-indigo-700 text-[10px] font-bold uppercase tracking-widest rounded-full">
                    <?php echo htmlspecialchars($post['category_name'] ?? 'Article'); ?>
                </span>
                <span class="text-slate-400 text-xs flex items-center gap-1">
                    <i class="fas fa-clock"></i>
                    <?php echo isset($post['read_time']) ? htmlspecialchars($post['read_time']) : '5 min read'; ?>
                </span>
            </div>

            <h1 class="text-lg sm:text-xl font-bold text-slate-900 leading-snug mb-8 tracking-tight">
                <?php echo htmlspecialchars($post['title']); ?>
            </h1>

            <div class="flex items-center justify-between border-y border-slate-200 py-4">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-full bg-slate-200 flex items-center justify-center text-slate-600 font-semibold text-sm">
                        <?php echo htmlspecialchars(substr($post['author_name'], 0, 1)); ?>
                    </div>
                    <div>
                        <p class="font-semibold text-slate-900 text-sm leading-none mb-1"><?php echo htmlspecialchars($post['author_name']); ?></p>
                        <p class="text-slate-500 text-[11px] flex items-center gap-1">
                            <i class="fas fa-calendar"></i>
                            <?php echo formatDate($post['created_at']); ?>
                        </p>
                    </div>
                </div>

                <div class="hidden sm:flex items-center gap-3">
                    <button onclick="window.location.href='https://www.linkedin.com/in/clite-mutale-bba-mba-mcips-6308a916b'" class="text-slate-600 hover:text-indigo-600 font-medium text-xs px-3 py-1.5 rounded-md border border-slate-200 transition-all">
                        Follow
                    </button>
                </div>
            </div>
        </header>

        <!-- Article Body -->
        <article class="prose prose-slate prose-lg max-w-none">
            <?php echo $post['content']; ?>
        </article>

        <!-- Article Footer & Interactions -->
        <footer class="mt-16 pt-10 border-t border-slate-200">
            <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-6">
                <div>
                    <h3 class="font-bold text-sm text-slate-500 uppercase tracking-wider mb-3">Share this post</h3>
                    <div class="flex items-center gap-2">
                        <a href="https://twitter.com/intent/tweet?text=<?php echo urlencode($post['title']); ?>&url=<?php echo urlencode(BASE_URL . 'post.php?slug=' . $post['slug']); ?>" class="w-8 h-8 flex items-center justify-center rounded-lg bg-slate-100 text-slate-600 hover:bg-slate-900 hover:text-white transition-all" target="_blank">
                            <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']); ?>" class="w-8 h-8 flex items-center justify-center rounded-lg bg-slate-100 text-slate-600 hover:bg-blue-600 hover:text-white transition-all" target="_blank">
                            <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']); ?>" class="w-8 h-8 flex items-center justify-center rounded-lg bg-slate-100 text-slate-600 hover:bg-blue-800 hover:text-white transition-all" target="_blank">
                            <i class="fab fa-linkedin"></i>
                        </a>
                    </div>
                </div>

                <div class="flex items-center gap-4">
                    <button class="flex items-center gap-2 px-3 py-2 text-slate-500 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition-all font-medium text-sm">
                    </button>
                </div>
            </div>

            <!-- Page Navigation -->
            <div class="mt-12 grid grid-cols-2 gap-4">
                <?php if ($prev_post): ?>
                <button onclick="window.location.href='post.php?slug=<?php echo htmlspecialchars($prev_post['slug']); ?>'" class="flex flex-col items-start p-4 rounded-xl border border-slate-200 hover:border-indigo-200 transition-all group">
                    <span class="text-[10px] text-slate-400 font-bold uppercase tracking-widest mb-1 flex items-center gap-1">
                        <i class="fas fa-arrow-left"></i> Previous
                    </span>
                    <span class="font-semibold text-sm text-slate-700 group-hover:text-indigo-600 transition-colors line-clamp-1"><?php echo htmlspecialchars($prev_post['title']); ?></span>
                </button>
                <?php else: ?>
                <button disabled class="flex flex-col items-start p-4 rounded-xl border border-slate-200 opacity-50 cursor-not-allowed">
                    <span class="text-[10px] text-slate-400 font-bold uppercase tracking-widest mb-1 flex items-center gap-1">
                        <i class="fas fa-arrow-left"></i> Previous
                    </span>
                    <span class="font-semibold text-sm text-slate-700 line-clamp-1">No previous post</span>
                </button>
                <?php endif; ?>
                <?php if ($next_post): ?>
                <button onclick="window.location.href='post.php?slug=<?php echo htmlspecialchars($next_post['slug']); ?>'" class="flex flex-col items-end p-4 rounded-xl border border-slate-200 hover:border-indigo-200 transition-all group text-right">
                    <span class="text-[10px] text-slate-400 font-bold uppercase tracking-widest mb-1 flex items-center gap-1">
                        Next <i class="fas fa-chevron-right"></i>
                    </span>
                    <span class="font-semibold text-sm text-slate-700 group-hover:text-indigo-600 transition-colors line-clamp-1"><?php echo htmlspecialchars($next_post['title']); ?></span>
                </button>
                <?php else: ?>
                <button disabled class="flex flex-col items-end p-4 rounded-xl border border-slate-200 opacity-50 cursor-not-allowed text-right">
                    <span class="text-[10px] text-slate-400 font-bold uppercase tracking-widest mb-1 flex items-center gap-1">
                        Next <i class="fas fa-chevron-right"></i>
                    </span>
                    <span class="font-semibold text-sm text-slate-700 line-clamp-1">No next post</span>
                </button>
                <?php endif; ?>
            </div>
        </footer>
    </main>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const bookmarkBtn = document.getElementById('bookmark-btn');
    let isBookmarked = false;

    bookmarkBtn.addEventListener('click', function() {
        isBookmarked = !isBookmarked;
        const icon = this.querySelector('i');
        if (isBookmarked) {
            this.classList.add('text-indigo-600', 'bg-indigo-50');
            this.classList.remove('text-slate-400');
            icon.classList.add('fas');
            icon.classList.remove('far');
        } else {
            this.classList.remove('text-indigo-600', 'bg-indigo-50');
            this.classList.add('text-slate-400');
            icon.classList.add('far');
            icon.classList.remove('fas');
        }
    });
});
</script>

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