<?php
// File: index.php
// Halaman utama blog untuk menampilkan postingan
include 'db.php';
include 'header.php';

// Konfigurasi paginasi
$posts_per_page = 7;
$current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($current_page - 1) * $posts_per_page;

$message = '';
$type = '';
if (isset($_SESSION['toast_message'])) {
    $message = $_SESSION['toast_message'];
    $type = $_SESSION['toast_type'];
    unset($_SESSION['toast_message']);
    unset($_SESSION['toast_type']);
}
?>
<main class="w-full flex-grow">
    <?php if ($message): ?>
        <div id="toast-message" style="display:none;" data-message="<?php echo htmlspecialchars($message); ?>" data-type="<?php echo htmlspecialchars($type); ?>"></div>
    <?php endif; ?>

    <section class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
        <?php
        $posts = getPaginatedPosts($posts_per_page, $offset);
        if ($posts):
            foreach ($posts as $post): ?>
                <article class="bg-gray-100 border border-gray-300 rounded-xl p-6 shadow-lg flex flex-col justify-between">
                    <div>
                        <h2 class="text-xl font-bold mb-2"><?php echo htmlspecialchars($post['title']); ?></h2>
                        <?php if ($post['image']): ?>
                            <img src="<?php echo htmlspecialchars($post['image']); ?>" alt="<?php echo htmlspecialchars($post['title']); ?>" class="w-full h-48 object-cover rounded-md mb-4">
                        <?php endif; ?>
                        <p class="text-sm text-gray-600 mb-2">Ditulis oleh <?php echo htmlspecialchars($post['username']); ?></p>
                        <p class="text-sm text-gray-600 mb-4">pada <i><?php echo date('d F Y, H:i', strtotime($post['date'])); ?></i></p>
                        <p class="text-sm text-gray-600 mb-4"><?php echo htmlspecialchars(substr($post['content'], 0, 25)); ?>...</p>
                    </div>
                    <a href="post.php?id=<?php echo htmlspecialchars($post['id']); ?>" class="w-full bg-black text-white text-center font-bold py-3 px-4 rounded-lg hover:bg-gray-800 transition duration-300 mt-4">
                        Baca Selengkapnya
                    </a>
                </article>
            <?php endforeach;
        else: ?>
            <p class="text-center text-gray-500 col-span-full">Belum ada postingan yang tersedia.</p>
        <?php endif; ?>
    </section>

    <?php
    $total_posts = count(getPosts());
    $total_pages = ceil($total_posts / $posts_per_page);

    if ($total_pages > 1): ?>
        <nav class="flex justify-center items-center gap-2 mt-8">
            <?php if ($current_page > 1): ?>
                <a href="index.php?page=<?php echo $current_page - 1; ?>" class="px-4 py-2 border rounded-full text-black hover:bg-gray-200 transition duration-300">Sebelumnya</a>
            <?php endif; ?>

            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <a href="index.php?page=<?php echo $i; ?>" class="px-4 py-2 border rounded-full <?php echo ($i == $current_page) ? 'bg-black text-white' : 'text-black hover:bg-gray-200'; ?> transition duration-300">
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>

            <?php if ($current_page < $total_pages): ?>
                <a href="index.php?page=<?php echo $current_page + 1; ?>" class="px-4 py-2 border rounded-full text-black hover:bg-gray-200 transition duration-300">Berikutnya</a>
            <?php endif; ?>
        </nav>
    <?php endif; ?>
</main>
<footer class="text-center text-gray-500 mt-12 text-sm">
    <p>Hak Cipta &copy; <?php echo date('Y'); ?>. nido.</p>
</footer>
<script>
    function showToast(message, bgColor) {
        const toast = document.createElement('div');
        toast.className = `fixed bottom-4 right-4 text-white px-6 py-3 rounded-lg shadow-xl ${bgColor} z-50 transition-transform transform translate-y-full`;
        toast.textContent = message;
        document.body.appendChild(toast);

        setTimeout(() => {
            toast.style.transform = 'translateY(0)';
        }, 100);

        setTimeout(() => {
            toast.style.transform = 'translateY(100%)';
            toast.addEventListener('transitionend', () => {
                toast.remove();
            });
        }, 3000);
    }
    
    // Periksa apakah ada pesan toast dari session
    window.addEventListener('load', function() {
        const toastElement = document.getElementById('toast-message');
        if (toastElement) {
            const message = toastElement.getAttribute('data-message');
            const type = toastElement.getAttribute('data-type');
            const bgColor = type === 'success' ? 'bg-green-700' : 'bg-red-700';
            showToast(message, bgColor);
        }
    });

    const loadingOverlay = document.getElementById('loading-overlay');
    document.addEventListener('DOMContentLoaded', () => {
        document.querySelectorAll('a').forEach(link => {
            link.addEventListener('click', (event) => {
                if (link.href && link.target !== '_blank' && !link.href.startsWith('#')) {
                    loadingOverlay.classList.add('visible');
                }
            });
        });

        window.addEventListener('load', () => {
            loadingOverlay.classList.remove('visible');
        });
    });
</script>
</body>
</html>