<?php
// Habilitar exibição de erros no PHP para ajudar na depuração
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Configuração da conexão com o banco de dados
$host = 'localhost';
$db = 'digupdog_FEED';
$user = 'digupdog_FEEDadmin';
$pass = 'Raimundinho1';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    echo "Database connection failed: " . $e->getMessage();
    exit;
}

// Função para carregar os feeds
if (isset($_GET['offset'])) {
    $limit = 30;
    $offset = (int)$_GET['offset'];
    $search = isset($_GET['search']) ? '%' . $_GET['search'] . '%' : '%';

    // Preparar e executar a consulta
    try {
        $stmt = $pdo->prepare("SELECT title, description, thumbnail, author, pubDate FROM pinfeeds 
                               WHERE title LIKE :search OR description LIKE :search 
                               ORDER BY pubDate DESC LIMIT :limit OFFSET :offset");
        $stmt->bindParam(':search', $search, PDO::PARAM_STR);
        $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
        $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
        $stmt->execute();

        $results = $stmt->fetchAll();
        echo json_encode($results);
    } catch (\PDOException $e) {
        echo json_encode(["error" => "Database query failed: " . $e->getMessage()]);
    }
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pinfeeds Infinite Scroll</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f9;
            margin: 0;
            padding: 0;
        }
        .feed-card {
            border: 1px solid #ccc;
            padding: 15px;
            margin: 10px auto;
            max-width: 600px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            background-color: #fff;
        }
        .feed-card img {
            max-width: 100%;
            border-radius: 4px;
        }
        #loading {
            text-align: center;
            padding: 20px;
            font-size: 1.2em;
            color: #777;
        }
    </style>
</head>
<body>
    <div id="feed-container"></div>
    <div id="loading">Loading more feeds...</div>

    <script>
        let offset = 0;
        const limit = 30;
        let loading = false;

        async function loadFeeds() {
            if (loading) return;
            loading = true;
            document.getElementById('loading').style.display = 'block';

            try {
                const response = await fetch(`?offset=${offset}`);
                if (!response.ok) throw new Error("Network response was not ok");

                const feeds = await response.json();
                if (feeds.error) {
                    console.error("Error in query:", feeds.error);
                    document.getElementById('loading').innerText = "Failed to load feeds.";
                    return;
                }

                if (feeds.length === 0) {
                    document.getElementById('loading').innerText = "No more feeds to load.";
                    return;
                }

                const feedContainer = document.getElementById('feed-container');
                feeds.forEach(feed => {
                    const feedCard = document.createElement('div');
                    feedCard.classList.add('feed-card');

                    const thumbnail = feed.thumbnail ? `<img src="${feed.thumbnail}" alt="Thumbnail">` : '';
                    const description = feed.description || 'No description available';
                    const pubDate = new Date(feed.pubDate).toLocaleDateString('en-US', {year: 'numeric', month: 'long', day: 'numeric'});

                    feedCard.innerHTML = `
                        <h3>${feed.title}</h3>
                        ${thumbnail}
                        <p>${description}</p>
                        <p><strong>Author:</strong> ${feed.author || 'Unknown'}</p>
                        <p><strong>Date:</strong> ${pubDate}</p>
                    `;
                    feedContainer.appendChild(feedCard);
                });

                offset += limit;
                loading = false;
                document.getElementById('loading').style.display = 'none';
            } catch (error) {
                console.error("Error loading feeds:", error);
                document.getElementById('loading').innerText = "Failed to load feeds.";
            }
        }

        window.addEventListener('scroll', () => {
            if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
                loadFeeds();
            }
        });

        loadFeeds(); // Carrega os primeiros feeds ao iniciar a página
    </script>
</body>
</html>
