<?php
/**
 * Public Blog Post Detail Page
 * Display individual blog post
 */

require_once '../config/config.php';

$isMobile = preg_match('/Mobile|Android|iPhone|iPad|iPod/', $_SERVER['HTTP_USER_AGENT']);

$db = getDB();

// Get post slug
$slug = $_GET['slug'] ?? '';

if (empty($slug)) {
    redirect('blog.php');
}

// Get post
$stmt = $db->prepare("
    SELECT p.*, u.first_name, u.last_name, u.id as author_user_id
    FROM cms_posts p
    LEFT JOIN users u ON p.author_id = u.id
    WHERE p.slug = ? AND p.status = 'published'
");
$stmt->execute([$slug]);
$post = $stmt->fetch();

if (!$post) {
    redirect('blog.php');
}

// Increment view count
$stmt = $db->prepare("UPDATE cms_posts SET views = views + 1 WHERE id = ?");
$stmt->execute([$post['id']]);

// Get related posts
$stmt = $db->prepare("
    SELECT p.*, u.first_name, u.last_name
    FROM cms_posts p
    LEFT JOIN users u ON p.author_id = u.id
    WHERE p.status = 'published' AND p.id != ?
    ORDER BY p.published_at DESC
    LIMIT 3
");
$stmt->execute([$post['id']]);
$relatedPosts = $stmt->fetchAll();

$pageTitle = $post['meta_title'] ?: $post['title'];
$metaDescription = $post['meta_description'] ?: $post['excerpt'];
$metaKeywords = $post['meta_keywords'];

// Include appropriate header based on device
if ($isMobile) {
    include '../templates/mobile-header.php';
} else {
    include '../templates/header.php';
}
?>

<!-- Post Header -->
<article class="blog-post">
    <header class="bg-light py-5">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-lg-8">
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="<?php echo SITE_URL; ?>">Home</a></li>
                            <li class="breadcrumb-item"><a href="blog.php">Blog</a></li>
                            <li class="breadcrumb-item active" aria-current="page"><?php echo e($post['title']); ?></li>
                        </ol>
                    </nav>
                    
                    <h1 class="display-4 fw-bold mb-3"><?php echo e($post['title']); ?></h1>
                    
                    <div class="d-flex align-items-center text-muted mb-3">
                        <div class="me-4">
                            <i class="fas fa-user"></i>
                            <a href="researcher-profile.php?id=<?php echo $post['author_user_id']; ?>" 
                               class="text-decoration-none">
                                <?php echo e($post['first_name'] . ' ' . $post['last_name']); ?>
                            </a>
                        </div>
                        <div class="me-4">
                            <i class="fas fa-calendar"></i>
                            <?php echo date('F j, Y', strtotime($post['published_at'])); ?>
                        </div>
                        <div>
                            <i class="fas fa-eye"></i>
                            <?php echo number_format($post['views']); ?> views
                        </div>
                    </div>
                    
                    <?php if ($post['excerpt']): ?>
                        <p class="lead text-muted"><?php echo e($post['excerpt']); ?></p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </header>

    <!-- Featured Image -->
    <?php if ($post['featured_image']): ?>
    <section class="py-4">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-lg-10">
                    <img src="<?php echo e($post['featured_image']); ?>" 
                         alt="<?php echo e($post['title']); ?>"
                         class="img-fluid rounded shadow-lg">
                </div>
            </div>
        </div>
    </section>
    <?php endif; ?>

    <!-- Post Content -->
    <section class="py-5">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-lg-8">
                    <div class="post-content">
                        <?php echo $post['content']; ?>
                    </div>
                    
                    <!-- Share Buttons -->
                    <div class="border-top border-bottom py-4 my-5">
                        <h5 class="mb-3">Share this post:</h5>
                        <div class="d-flex gap-2">
                            <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode(SITE_URL . '/public/post.php?slug=' . $post['slug']); ?>" 
                               target="_blank" 
                               class="btn btn-outline-primary">
                                <i class="fab fa-facebook-f"></i> Facebook
                            </a>
                            <a href="https://twitter.com/intent/tweet?url=<?php echo urlencode(SITE_URL . '/public/post.php?slug=' . $post['slug']); ?>&text=<?php echo urlencode($post['title']); ?>" 
                               target="_blank" 
                               class="btn btn-outline-info">
                                <i class="fab fa-twitter"></i> Twitter
                            </a>
                            <a href="https://www.linkedin.com/shareArticle?mini=true&url=<?php echo urlencode(SITE_URL . '/public/post.php?slug=' . $post['slug']); ?>&title=<?php echo urlencode($post['title']); ?>" 
                               target="_blank" 
                               class="btn btn-outline-primary">
                                <i class="fab fa-linkedin-in"></i> LinkedIn
                            </a>
                            <button onclick="copyToClipboard()" class="btn btn-outline-secondary">
                                <i class="fas fa-link"></i> Copy Link
                            </button>
                        </div>
                    </div>
                    
                    <!-- Author Bio -->
                    <div class="card shadow-sm mb-5">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="flex-shrink-0">
                                    <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center" 
                                         style="width: 80px; height: 80px; font-size: 2rem;">
                                        <?php echo strtoupper(substr($post['first_name'], 0, 1) . substr($post['last_name'], 0, 1)); ?>
                                    </div>
                                </div>
                                <div class="flex-grow-1 ms-3">
                                    <h5 class="mb-1">
                                        <a href="researcher-profile.php?id=<?php echo $post['author_user_id']; ?>" 
                                           class="text-decoration-none">
                                            <?php echo e($post['first_name'] . ' ' . $post['last_name']); ?>
                                        </a>
                                    </h5>
                                    <p class="text-muted mb-0">Author</p>
                                </div>
                                <div>
                                    <a href="researcher-profile.php?id=<?php echo $post['author_user_id']; ?>" 
                                       class="btn btn-outline-primary btn-sm">
                                        View Profile
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</article>

<!-- Related Posts -->
<?php if (!empty($relatedPosts)): ?>
<section class="py-5 bg-light">
    <div class="container">
        <div class="row mb-4">
            <div class="col-12">
                <h2 class="h3">Related Posts</h2>
            </div>
        </div>
        <div class="row g-4">
            <?php foreach ($relatedPosts as $relatedPost): ?>
                <div class="col-lg-4 col-md-6">
                    <div class="card h-100 shadow-sm hover-shadow">
                        <?php if ($relatedPost['featured_image']): ?>
                            <img src="<?php echo e($relatedPost['featured_image']); ?>" 
                                 class="card-img-top" 
                                 alt="<?php echo e($relatedPost['title']); ?>"
                                 style="height: 200px; object-fit: cover;">
                        <?php else: ?>
                            <div class="bg-secondary d-flex align-items-center justify-content-center" 
                                 style="height: 200px;">
                                <i class="fas fa-image fa-3x text-white opacity-25"></i>
                            </div>
                        <?php endif; ?>
                        
                        <div class="card-body">
                            <h5 class="card-title">
                                <a href="post.php?slug=<?php echo e($relatedPost['slug']); ?>" 
                                   class="text-decoration-none text-dark">
                                    <?php echo e($relatedPost['title']); ?>
                                </a>
                            </h5>
                            
                            <div class="text-muted small mb-3">
                                <i class="fas fa-calendar"></i> <?php echo date('M j, Y', strtotime($relatedPost['published_at'])); ?>
                            </div>
                            
                            <p class="card-text">
                                <?php echo e($relatedPost['excerpt'] ?: substr(strip_tags($relatedPost['content']), 0, 100) . '...'); ?>
                            </p>
                            
                            <a href="post.php?slug=<?php echo e($relatedPost['slug']); ?>" 
                               class="btn btn-outline-primary btn-sm">
                                Read More <i class="fas fa-arrow-right ms-1"></i>
                            </a>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>

<!-- Back to Blog -->
<section class="py-4">
    <div class="container">
        <div class="row">
            <div class="col-12 text-center">
                <a href="blog.php" class="btn btn-outline-primary">
                    <i class="fas fa-arrow-left"></i> Back to Blog
                </a>
            </div>
        </div>
    </div>
</section>

<style>
.post-content {
    font-size: 1.1rem;
    line-height: 1.8;
}

.post-content h2 {
    margin-top: 2rem;
    margin-bottom: 1rem;
    font-weight: 600;
}

.post-content h3 {
    margin-top: 1.5rem;
    margin-bottom: 0.75rem;
    font-weight: 600;
}

.post-content p {
    margin-bottom: 1.5rem;
}

.post-content img {
    max-width: 100%;
    height: auto;
    border-radius: 0.5rem;
    margin: 2rem 0;
}

.post-content ul, .post-content ol {
    margin-bottom: 1.5rem;
    padding-left: 2rem;
}

.post-content li {
    margin-bottom: 0.5rem;
}

.post-content blockquote {
    border-left: 4px solid #007bff;
    padding-left: 1.5rem;
    margin: 2rem 0;
    font-style: italic;
    color: #6c757d;
}

.hover-shadow {
    transition: all 0.3s ease;
}

.hover-shadow:hover {
    transform: translateY(-5px);
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
}
</style>

<script>
function copyToClipboard() {
    const url = window.location.href;
    navigator.clipboard.writeText(url).then(function() {
        alert('Link copied to clipboard!');
    }, function(err) {
        console.error('Could not copy text: ', err);
    });
}
</script>

<?php // Include appropriate footer based on device
if ($isMobile) {
    include '../templates/mobile-footer.php';
} else {
    include '../templates/footer.php';
} ?>
