<?php
// --- LOGIC BLOCK ---
include 'includes/header.php'; 

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) { 
    header("Location: articles.php"); 
    exit(); 
}
$article_id = intval($_GET['id']);

// --- VIEW COUNTING LOGIC ---
if (!isset($_SESSION['viewed_article_' . $article_id])) {
    $conn->query("UPDATE articles SET view_count = view_count + 1 WHERE id = $article_id");
    $_SESSION['viewed_article_' . $article_id] = true;
}

// --- HANDLE COMMENT SUBMISSION ---
$comment_message = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_comment'])) {
    if (!isset($_SESSION['user_id'])) {
        header("Location: login.php"); exit();
    }
    $comment_text = trim($_POST['comment_text']);
    if (!empty($comment_text)) {
        $stmt = $conn->prepare("INSERT INTO comments (article_id, user_id, comment_text) VALUES (?, ?, ?)");
        $stmt->bind_param("iis", $article_id, $_SESSION['user_id'], $comment_text);
        if ($stmt->execute()) {
            $comment_message = '<div class="alert alert-success">Your comment has been submitted and is awaiting moderation.</div>';
        }
    }
}

// --- DATA FETCHING ---
// 1. Fetch article details
$stmt = $conn->prepare("SELECT * FROM articles WHERE id = ?");
$stmt->bind_param("i", $article_id);
$stmt->execute();
$article_result = $stmt->get_result();
if ($article_result->num_rows === 0) { header("Location: articles.php"); exit(); }
$article = $article_result->fetch_assoc();

// 2. Check if current user has liked this article
$user_has_liked = false;
if (isset($_SESSION['user_id'])) {
    $stmt_like_check = $conn->prepare("SELECT id FROM likes WHERE user_id = ? AND item_id = ? AND item_type = 'article'");
    $stmt_like_check->bind_param("ii", $_SESSION['user_id'], $article_id);
    $stmt_like_check->execute();
    if ($stmt_like_check->get_result()->num_rows > 0) {
        $user_has_liked = true;
    }
}

// 3. Fetch gallery images
$stmt_gallery = $conn->prepare("SELECT * FROM galleries WHERE item_id = ? AND item_type = 'article'");
$stmt_gallery->bind_param("i", $article_id);
$stmt_gallery->execute();
$gallery_images = $stmt_gallery->get_result()->fetch_all(MYSQLI_ASSOC);

// 4. Fetch approved comments
$comments_stmt = $conn->prepare("SELECT c.*, u.full_name, u.profile_image_url FROM comments c JOIN users u ON c.user_id = u.id WHERE c.article_id = ? AND c.is_approved = 1 ORDER BY c.created_at ASC");
$comments_stmt->bind_param("i", $article_id);
$comments_stmt->execute();
$comments_result = $comments_stmt->get_result();

// 5. Prepare variables for social sharing
$page_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$share_title = urlencode($article['title']);
$page_url_encoded = urlencode($page_url);
$image_url_encoded = urlencode("http://$_SERVER[HTTP_HOST]/" . $article['image_url']);
// --- END LOGIC BLOCK ---

// --- PRESENTATION BLOCK ---
?>
<main class="container my-5">
    <div class="row justify-content-center">
        <div class="col-lg-9">
            <article>
                <header class="mb-4 text-center">
                    <h1 class="fw-bolder mb-1"><?php echo htmlspecialchars($article['title']); ?></h1>
                </header>
                
                <?php if(!empty($article['image_url'])): ?>
                <figure class="mb-3">
                    <img class="img-fluid rounded shadow" src="<?php echo htmlspecialchars($article['image_url']); ?>" alt="<?php echo htmlspecialchars($article['title']); ?>" style="width:100%; max-height:450px; object-fit: cover;"/>
                </figure>
                <?php endif; ?>

                <div class="text-center text-muted fst-italic mb-4">
                    Posted on <?php echo date("F d, Y", strtotime($article['publish_date'])); ?> by <?php echo htmlspecialchars($article['author']); ?>
                </div>

                <section class="mb-5 fs-5">
                    <?php echo $article['content']; ?>
                </section>

                <div class="card bg-light border-0 my-4">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center flex-wrap">
                            <div class="d-flex align-items-center gap-3 mb-3 mb-md-0">
                                <button id="likeBtn" class="btn <?php echo $user_has_liked ? 'btn-danger' : 'btn-outline-danger'; ?>" data-article-id="<?php echo $article_id; ?>" <?php if(!isset($_SESSION['user_id'])) echo 'disabled title="You must be logged in to like"'; ?>>
                                    <i class="bi <?php echo $user_has_liked ? 'bi-heart-fill' : 'bi-heart'; ?>"></i> Like
                                </button>
                                <span class="text-muted fw-bold"><i class="bi bi-heart-fill"></i> <span id="likeCount"><?php echo $article['like_count']; ?></span></span>
                                <span class="text-muted"><i class="bi bi-eye-fill"></i> <?php echo $article['view_count']; ?> Views</span>
                            </div>
                            <div class="social-share-buttons">
                                <span class="me-2 text-muted small">Share on:</span>
                                <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo $page_url_encoded; ?>" target="_blank" class="share-facebook" title="Share on Facebook"><i class="bi bi-facebook"></i></a>
                                <a href="https://twitter.com/intent/tweet?url=<?php echo $page_url_encoded; ?>&text=<?php echo $share_title; ?>" target="_blank" class="share-twitter" title="Share on Twitter (X)"><i class="bi bi-twitter"></i></a>
                                <a href="https://pinterest.com/pin/create/button/?url=<?php echo $page_url_encoded; ?>&media=<?php echo $image_url_encoded; ?>&description=<?php echo $share_title; ?>" target="_blank" class="share-pinterest" title="Pin on Pinterest"><i class="bi bi-pinterest"></i></a>
                                <a href="https://api.whatsapp.com/send?text=<?php echo $share_title; ?>%20<?php echo $page_url_encoded; ?>" target="_blank" class="share-whatsapp" title="Share on WhatsApp"><i class="bi bi-whatsapp"></i></a>
                            </div>
                        </div>
                    </div>
                </div>
            </article>

            <?php if (!empty($gallery_images)): ?>
            <hr class="my-5"><h3 class="text-center mb-4">Photo Gallery</h3>
            <div id="articleCarousel" class="carousel slide shadow rounded" data-bs-ride="carousel"><div class="carousel-inner rounded">
                <?php foreach ($gallery_images as $i => $img): ?>
                <div class="carousel-item <?php echo $i == 0 ? 'active' : ''; ?>"><img src="<?php echo htmlspecialchars($img['image_url']); ?>" class="d-block w-100 tour-details-img" alt="Gallery image"></div>
                <?php endforeach; ?>
            </div><button class="carousel-control-prev" type="button" data-bs-target="#articleCarousel" data-bs-slide="prev"><span class="carousel-control-prev-icon"></span></button><button class="carousel-control-next" type="button" data-bs-target="#articleCarousel" data-bs-slide="next"><span class="carousel-control-next-icon"></span></button></div>
            <?php endif; ?>
            
            <hr class="my-5">
            <section id="comments">
                <h3 class="mb-4"><?php echo $comments_result->num_rows; ?> Comments</h3>
                <?php if ($comments_result->num_rows > 0): while($comment = $comments_result->fetch_assoc()): ?>
                <div class="d-flex mb-4">
                    <div class="flex-shrink-0">
                        <?php if (!empty($comment['profile_image_url'])): ?><img src="<?php echo htmlspecialchars($comment['profile_image_url']); ?>" class="rounded-circle" width="50" height="50" style="object-fit: cover;"><?php else: ?><div class="avatar-initial rounded-circle" style="width: 50px; height: 50px; font-size: 1.5rem;"><?php echo strtoupper(substr($comment['full_name'], 0, 1)); ?></div><?php endif; ?>
                    </div>
                    <div class="ms-3"><div class="fw-bold"><?php echo htmlspecialchars($comment['full_name']); ?></div><div class="text-muted small"><?php echo date("F j, Y \a\\t g:i a", strtotime($comment['created_at'])); ?></div><?php echo nl2br(htmlspecialchars($comment['comment_text'])); ?></div>
                </div>
                <?php endwhile; endif; ?>
                <div class="card bg-light mt-5"><div class="card-body">
                    <?php echo $comment_message; ?>
                    <?php if(isset($_SESSION['user_id'])): ?>
                    <h5 class="card-title">Leave a Comment</h5>
                    <form method="POST" action="#comments">
                        <input type="hidden" name="article_id" value="<?php echo $article_id; ?>">
                        <div class="mb-3"><textarea class="form-control" name="comment_text" rows="3" required></textarea></div>
                        <button type="submit" name="submit_comment" class="btn btn-primary">Submit Comment</button>
                    </form>
                    <?php else: ?>
                    <p class="text-center mb-0"><a href="login.php?redirect=<?php echo urlencode($page_url); ?>">Log in</a> to leave a comment.</p>
                    <?php endif; ?>
                </div></div>
            </section>
        </div>
    </div>
</main>

<script>
// JavaScript for the like button
document.addEventListener('DOMContentLoaded', function() {
    const likeBtn = document.getElementById('likeBtn');
    if (likeBtn) {
        likeBtn.addEventListener('click', function() {
            if (this.disabled) return; this.disabled = true;
            const articleId = this.dataset.articleId;
            fetch('like-handler.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ item_id: articleId }) })
            .then(response => { if (!response.ok) { return response.json().then(errorData => Promise.reject(errorData)); } return response.json(); })
            .then(data => {
                if (data.success) {
                    document.getElementById('likeCount').textContent = data.like_count;
                    const icon = this.querySelector('i');
                    if (data.liked) { this.classList.remove('btn-outline-danger'); this.classList.add('btn-danger'); icon.classList.remove('bi-heart'); icon.classList.add('bi-heart-fill'); } 
                    else { this.classList.remove('btn-danger'); this.classList.add('btn-outline-danger'); icon.classList.remove('bi-heart-fill'); icon.classList.add('bi-heart'); }
                } else { if (data.message && data.message.includes('logged in')) { window.location.href = 'login.php'; } else { alert(data.message || 'An error occurred.'); } }
            })
            .catch(error => { console.error('Fetch Error:', error); alert(error.message || 'A critical error occurred.'); })
            .finally(() => { this.disabled = false; });
        });
    }
});
</script>

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