<?php
// Database connection
$conn = new mysqli('localhost', 'smplus_hrdc', '0991123495@Tomaida', 'smplus_hrdc');
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }

$newsId = isset($_GET['id']) ? intval($_GET['id']) : 0;
$categoryId = isset($_GET['category']) ? intval($_GET['category']) : 0;

// Build SQL query
if ($newsId) {
    $sql = "SELECT * FROM hrdc_posts WHERE ID = $newsId LIMIT 1";
} elseif ($categoryId) {
    $sql = "SELECT * FROM hrdc_posts WHERE post_category = $categoryId  AND post_status = 'publish' ORDER BY post_date DESC";
} else {
    $sql = "SELECT * FROM hrdc_posts WHERE post_status = 'publish' ORDER BY post_date DESC";
}

$result = $conn->query($sql);

// Fetch recent posts
$recentPostsResult = $conn->query("SELECT ID, post_title, post_category, post_date FROM hrdc_posts WHERE post_status = 'publish' ORDER BY post_date DESC");

// Fetch categories dynamically
$categoriesResult = $conn->query("SELECT category_id, category_name FROM hrdc_categories ORDER BY category_name ASC");
?>

<?php include 'topbar.php'; ?>
<?php include 'header.php'; ?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HRDC Malawi | News</title>

<!-- Bootstrap & FontAwesome -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">

<link rel="stylesheet" href="css/style.css">

<style>
body {
    font-family: 'Poppins', sans-serif;
    background: #f9fafe;
    color: #333;
}

/* PAGE HEADER */
.page-header {
    text-align: center;
    margin: 60px 0 40px 0;
}
.page-header h2 {
    color: #0d8ac2;
    font-weight: 700;
}
.page-header p {
    color: #555;
    font-size: 1.1rem;
}

/* NEWS GRID */
.news-card {
    transition: 0.3s ease;
}
.news-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 35px rgba(0,0,0,0.15);
}
.news-card img {
    width: 100%;
    height: 200px;
    object-fit: cover;
    border-radius: 10px;
}

.news-card h5 { color: #0d8ac2; margin-top: 15px; }
.news-card p { font-size: 0.95rem; }

.news-card a { text-decoration: none; color: #bf1e2e; }
.news-card a:hover { text-decoration: underline; }

/* SINGLE NEWS */
.news-single {
    max-width: 900px;
    margin: auto;
}

.news-date {
    color: #888;
    font-size: 0.9rem;
    margin-bottom: 20px;
}

.news-content {
    font-size: 1.05rem;
    line-height: 1.8;
}

/* SHARE BUTTONS */
.share-post h5 {
    font-weight: 600;
    color: #0d8ac2;
}
.share-post .btn i {
    margin-right: 6px;
}

/* NEWS GRID */
.news-card img {
    width: 100%; /* Ensures the image takes up the full width of its container */
    height: 250px; /* Fixed height for all images */
    object-fit: cover; /* Ensures the image covers the space without distortion */
    border-radius: 10px;
}

/* SINGLE POST IMAGE */
.news-single img {
    width: 100%; /* Ensures the image takes up the full width of the container */
    height: 400px; /* Fixed height for the single post images */
    object-fit: cover; /* Ensures the image covers the space without distortion */
    border-radius: 10px;
}


/* SIDEBAR */
.sidebar {
    background: #fff;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 5px 20px rgba(0,0,0,0.05);
}
.sidebar h4 {
    border-bottom: 2px solid #0d8ac2;
    padding-bottom: 10px;
    margin-bottom: 15px;
    color: #0d8ac2;
}
.sidebar ul li { margin-bottom: 10px; }
.sidebar ul li a { text-decoration: none; color: #333; }
.sidebar ul li a:hover { color: #0d8ac2; }
</style>
</head>
<body>

<div class="container-fluid py-5 px-5">
    <div class="page-header">
        <h2>HRDC News</h2>
        <p>Stay updated with our latest news, announcements, and events</p>
    </div>

    <div class="row g-4">
        <!-- MAIN CONTENT -->
        <div class="col-lg-8">
            <div class="row g-4">

            <?php
            if ($result->num_rows > 0) {
                while($row = $result->fetch_assoc()) {

                    $title = htmlspecialchars($row['post_title']);
                    $image = !empty($row['image']) ? 'uploads/'.$row['image'] : 'images/logo.png';
                    $date = date("F j, Y", strtotime($row['post_date']));
                    $link = 'news.php?id='.$row['ID'];
                    $commentStatus = $row['comment_status'];

                    // Generate share links
                    $shareUrl = urlencode("https://{$_SERVER['HTTP_HOST']}/$link");
                    $shareText = urlencode($title);

                    if ($newsId) {
    // SINGLE POST VIEW
    echo '
    <div class="col-12 news-single bg-white p-4 rounded shadow-sm mb-5">
        <img src="'.$image.'" alt="'.$title.'">
        <h2 class="mb-3">'.$title.'</h2>
        <div class="news-date"><i class="fas fa-calendar-alt me-2"></i>'.$date.'</div>
        <div class="news-content">'.nl2br($row['post_content']).'</div>

        <!-- SHARE BUTTONS -->
        <div class="share-post mt-4">
            <h5>Share this Post:</h5>
            <div class="d-flex gap-3 mt-2">
                <a href="https://www.facebook.com/sharer/sharer.php?u='.$shareUrl.'" target="_blank" class="btn btn-primary btn-sm">
                    <i class="fab fa-facebook-f"></i> Facebook
                </a>
                <a href="https://twitter.com/intent/tweet?url='.$shareUrl.'&text='.$shareText.'" target="_blank" class="btn btn-info btn-sm text-white">
                    <i class="fab fa-twitter"></i> Twitter
                </a>
                <a href="https://wa.me/?text='.$shareText.'%20'.$shareUrl.'" target="_blank" class="btn btn-success btn-sm">
                    <i class="fab fa-whatsapp"></i> WhatsApp
                </a>
                <a href="https://www.linkedin.com/sharing/share-offsite/?url='.$shareUrl.'" target="_blank" class="btn btn-secondary btn-sm">
                    <i class="fab fa-linkedin-in"></i> LinkedIn
                </a>
            </div>
        </div>

        <!-- COMMENTS SECTION -->
        <div id="comments" class="mt-5">
            <h4>Comments (';

    // Fetch comments count (only approved)
    $commentsResult = $conn->query("SELECT * FROM hrdc_comments WHERE comment_post_ID = $newsId AND comment_approved = 1 ORDER BY comment_date DESC");
    echo $commentsResult->num_rows;

    echo ')</h4>';

    // Display comments
    if ($commentsResult->num_rows > 0) {
        while($c = $commentsResult->fetch_assoc()) {
            $cName = htmlspecialchars($c['comment_author']);
            $cDate = date("F j, Y, g:i a", strtotime($c['comment_date']));
            $cContent = nl2br(htmlspecialchars($c['comment_content']));
            echo '<div class="mb-3 p-3 bg-light rounded">
                    <strong>'.$cName.'</strong> <small class="text-muted">'.$cDate.'</small>
                    <p>'.$cContent.'</p>
                  </div>';
        }
    } else {
        echo '<p>No comments yet. Be the first to comment!</p>';
    }

    // COMMENT FORM OR CLOSED MESSAGE
    if ($row['comment_status'] == 'open') {
        echo '  <!-- Comment Form -->
                <div class="mt-4">
                    <h5>Leave a Comment</h5>
                    <form method="post" action="post_comment.php">
                        <div class="mb-3">
                            <input type="text" name="name" class="form-control" placeholder="Your Name" required>
                            <input type="hidden" name="post_id" value="'.$newsId.'">
                            <input type="hidden" name="action" value="comment_submit">
                        </div>
                        <div class="mb-3">
                            <input type="email" name="email" class="form-control" placeholder="Your Email" required>
                        </div>
                        <div class="mb-3">
                            <textarea name="comment" class="form-control" rows="5" placeholder="Your Comment" required></textarea>
                        </div>
                        <button type="submit" name="comment_submit" class="btn btn-primary">Submit Comment</button>
                    </form>
                </div>';
    } else {
        echo '<div class="alert alert-warning mt-4">Comments are closed for this post.</div>';
    }

    echo '</div> <!-- end comments section -->
    </div>'; // end single news div
}
 else {
    // NEWS CARD LIST (leave this as is)
    echo '
    <div class="col-md-6">
        <div class="news-card bg-white p-3 rounded shadow-sm h-100 d-flex flex-column">
            <img src="'.$image.'" alt="'.$title.'">
            <h5>'.$title.'</h5>
            <small class="text-muted"><i class="fas fa-calendar-alt me-1"></i>'.$date.'</small>
            <p>'.substr(strip_tags($row['post_content']), 0, 120).'...</p>

            <div class="mt-auto">
                <a href="'.$link.'">Read More &raquo;</a>
            </div>

            <!-- Small Share Icons -->
            <div class="mt-2">
                <a href="https://www.facebook.com/sharer/sharer.php?u='.$shareUrl.'" target="_blank" class="text-primary me-2">
                    <i class="fab fa-facebook"></i>
                </a>
                <a href="https://twitter.com/intent/tweet?url='.$shareUrl.'&text='.$shareText.'" target="_blank" class="text-info me-2">
                    <i class="fab fa-twitter"></i>
                </a>
                <a href="https://wa.me/?text='.$shareText.'%20'.$shareUrl.'" target="_blank" class="text-success me-2">
                    <i class="fab fa-whatsapp"></i>
                </a>
            </div>

        </div>
    </div>';
}

                }
                
            } else {
                echo '<div class="col-12 text-center"><p>No news available at the moment.</p></div>';
            }
            ?>

            </div>
        </div>

        <!-- SIDEBAR -->
        <div class="col-lg-4">
            <div class="sidebar">

                <!-- Search -->
                <input type="text" placeholder="Search news..." class="form-control mb-4" onkeyup="filterNews(this.value)">

                <!-- Recent Posts -->
                <h4>Recent Posts</h4>
                <ul>
                <?php
                if ($recentPostsResult->num_rows > 0) {
                    while($post = $recentPostsResult->fetch_assoc()) {
                        $postDate = date("M j, Y", strtotime($post['post_date']));
                        echo '<li><a href="news.php?id='.$post['ID'].'">'.$post['post_title'].'</a> 
                              <small class="text-muted d-block">'.$postDate.'</small></li>';
                    }
                } else { echo '<li>No recent posts</li>'; }
                ?>
                </ul>

                <!-- Categories -->
                <h4>Categories</h4>
                <ul>
                <?php
                if ($categoriesResult->num_rows > 0) {
                    while($cat = $categoriesResult->fetch_assoc()) {
                        echo '<li><a href="news.php?category='.$cat['category_id'].'">'.$cat['category_name'].'</a></li>';
                    }
                } else { echo '<li>No categories</li>'; }
                ?>
                </ul>

            </div>
        </div>
    </div>
</div>
<?php include 'footer.php'; ?>
<script>
function filterNews(query) {
    query = query.toLowerCase();
    const cards = document.querySelectorAll('.news-card');
    cards.forEach(card => {
        const title = card.querySelector('h5').innerText.toLowerCase();
        card.style.display = title.includes(query) ? '' : 'none';
    });
}
</script>

<script src="navigation.js"></script>
<!-- jQuery first -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<!-- Bootstrap JS (optional, after jQuery) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<!-- Toastr JS (after jQuery) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>




<script>
document.addEventListener('DOMContentLoaded', function() {
    const urlParams = new URLSearchParams(window.location.search);
    const status = urlParams.get('status');

    console.log('Captured status:', status); // <-- This will log the status to the console

    if(status) {
        const commentsSection = document.querySelector('#comments');

        switch(status) {
            case 'success':
                toastr.success('Your comment has been submitted successfully!');
                if(commentsSection) commentsSection.scrollIntoView({ behavior: 'smooth' });
                break;
            case 'error':
                toastr.error('There was an error submitting your comment. Please try again.');
                if(commentsSection) commentsSection.scrollIntoView({ behavior: 'smooth' });
                break;
            case 'empty':
                toastr.warning('Please fill in all fields before submitting.');
                if(commentsSection) commentsSection.scrollIntoView({ behavior: 'smooth' });
                break;
        }

        // Remove the status parameter from URL after showing the message
        urlParams.delete('status');
        const newUrl = window.location.pathname + (urlParams.toString() ? '?' + urlParams.toString() : '') + window.location.hash;
        window.history.replaceState({}, '', newUrl);
    }
});
</script>



</body>
</html>
