<?php
// Início da sessão e verificação de login
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: login.html");
    exit;
}

// 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) {
    throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

$perPage = 28;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $perPage;

// Obtendo feeds
$sql = "SELECT SQL_CALC_FOUND_ROWS id, title, description, thumbnail, link FROM pinfeeds WHERE user_id = ? ORDER BY id DESC LIMIT ?, ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$_SESSION['user_id'], $start, $perPage]);
$feeds = $stmt->fetchAll();

// Cálculo do total de páginas
$totalRows = $pdo->query("SELECT FOUND_ROWS() as total")->fetch()['total'];
$totalPages = ceil($totalRows / $perPage);

// Início do HTML
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>My Hashtag.iO</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" rel="stylesheet">
    <link href="styles.css" rel="stylesheet">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.0.0/animate.min.css"/>

    <style>
        body {
            font-family: 'Arial', sans-serif; /* Modern font */
        }
        .login-register-section {
            text-align: center; /* Centraliza o título */
            color: #333; /* Cor do texto */
            font-size: 2.5em; /* Tamanho da fonte */
            text-shadow: 2px 2px 4px #aaa; /* Sombra no texto para um efeito elegante */
            margin-top: 20px; /* Espaçamento maior no topo */
            margin-bottom: 20px; /* Espaçamento menor embaixo */
        }
    </style>
</head>
<body>


    <!-- Botões de Categoria -->
  <div class="category-buttons-container">
        <div class="category-buttons">
            <div class="left-arrow"></div>
            <div class="category-buttons-wrapper">
                <a class="category-button pins" href="https://digupdog.com" target="_self">Pins</a>
                <a class="category-button all" href="https://digupdog.net/FEED/home.html" target="_self">All</a>
                <a class="category-button world-news" href="https://digupdog.net/FEED/news.html" target="_self">World News</a>
                <a class="category-button entertainment" href="https://digupdog.net/FEED/entertainment.html" target="_self">Entertainment</a>
                <a class="category-button sports" href="https://digupdog.net/FEED/sports.html" target="_self">Sports</a>
                <a class="category-button videogames" href="https://digupdog.net/FEED/videogames.html" target="_self">Video Games</a>
                <a class="category-button plus" href="https://digupdog.com/plus.php" target="_self">18+</a>
            </div>
            <div class="right-arrow"></div>
        </div>
    </div>
</div>

    <div class="login-register-section">
        <!-- Seção de Login/Register -->
        <?php if (isset($_SESSION['username'])): ?>
            <span>Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?></span>
            <a href='logout.php'><i class='fas fa-sign-out-alt'></i> Logout</a>
        <?php else: ?>
            <a href='login.html'><i class='fas fa-sign-in-alt'></i> Login</a>
            <a href='register.html'><i class='fas fa-user-plus'></i> Register</a>
        <?php endif; ?>
    </div>

    <!-- Listagem de Resultados (Feeds) -->
    <div class="result-list" id="feeds">
        <?php foreach ($feeds as $feed): ?>
            <div class='result fadeIn' id='feed-<?php echo htmlspecialchars($feed['id']); ?>'>
                <?php if (!empty($feed['thumbnail'])): ?>
                    <img class="lazy-load" src="placeholder.jpg" data-src="<?php echo htmlspecialchars($feed['thumbnail']); ?>" alt='Thumbnail' loading="lazy">
                <?php endif; ?>
                <h2><?php echo htmlspecialchars($feed['title']); ?></h2>
                <p class='description'><?php echo htmlspecialchars($feed['description']); ?></p>
                <a href='<?php echo htmlspecialchars($feed['link']); ?>' target='_blank'>Read more</a>
            </div>
        <?php endforeach; ?>
    </div>

    <!-- Paginação -->
    <nav aria-label="Page navigation">
        <ul class="pagination justify-content-center">
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <li class="page-item <?php echo ($i === $page) ? 'active' : ''; ?>">
                    <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                </li>
            <?php endfor; ?>
        </ul>
    </nav>

    <!-- Scripts JavaScript -->
    <script>
    // Lazy loading para imagens
    document.addEventListener("DOMContentLoaded", function() {
        var lazyImages = [].slice.call(document.querySelectorAll("img.lazy-load"));
        if ("IntersectionObserver" in window) {
            let observer = new IntersectionObserver(function(entries, observer) {
                entries.forEach(function(entry) {
                    if (entry.isIntersecting) {
                        let image = entry.target;
                        image.src = image.dataset.src;
                        observer.unobserve(image);
                    }
                });
            });
            lazyImages.forEach(function(image) {
                observer.observe(image);
            });
        } else {
            // Fallback para navegadores sem suporte a IntersectionObserver
            lazyImages.forEach(function(image) {
                image.src = image.dataset.src;
            });
        }
    });

    // Funções adicionais para manipulação de tags
    document.addEventListener('DOMContentLoaded', (event) => {
        const feedElements = document.querySelectorAll('.result');
        feedElements.forEach(feedElement => {
            const title = feedElement.querySelector('h2').innerText;
            createTagsForTitle(title, feedElement.id);
        });
    });

    function extractTagsFromTitle(title) {
        let normalizedTitle = title.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "").toLowerCase();
        let words = normalizedTitle.split(" ");
        let commonWords = ["a", "an", "the", "and", "or", "but", "in", "at", "on", "with", "to", "–", "for", "is", "of", "that", "it", "by", "from", "as", "are", "was", "be", "has", "have", "will", "this", "which", "its", "about", "up", "more", "who", "also", "they", "out", "he", "she", "you", "their", "we", "her", "his", "them", "been", "these", "would", "some", "can", "like", "there", "if", "all", "my", "what", "so", "then", "into", "just", "over", "do", "than", "when", "other", "how", "our", "any", "new", "me", "after", "most", "made", "only", "time", "will", "where", "year", "years", "make", "does", "could", "were", "your", "good", "well", "them"];
        return words.filter(word => !commonWords.includes(word) && word.length > 2);
    }

    function stringToColor(str) {
        let hash = 0;
        for (let i = 0; i < str.length; i++) {
            hash = str.charCodeAt(i) + ((hash << 5) - hash);
        }
        let color = '#';
        for (let i = 0; i < 3; i++) {
            let value = (hash >> (i * 8)) & 0xFF;
            color += ('00' + value.toString(16)).substr(-2);
        }
        return color;
    }

    function isColorDark(hex) {
        let r = parseInt(hex.slice(1, 3), 16);
        let g = parseInt(hex.slice(3, 5), 16);
        let b = parseInt(hex.slice(5, 7), 16);
        let brightness = (r * 299 + g * 587 + b * 114) / 1000;
        return brightness < 128;
    }

    function createTagsForTitle(title, feedId) {
    const keywords = extractTagsFromTitle(title);
    let tagsHtml = '<p class="tags">'; // Start of the tags paragraph

    keywords.forEach((tag, i) => {
        const bgColor = stringToColor(tag);
        const textColor = isColorDark(bgColor) ? 'white' : 'black';

        // Your provided code snippet
        tagsHtml += (i > 0 ? ', ' : '') + `<a href="#" class="tag-search-link" data-tag="${tag}" style="background-color: ${bgColor}; color: ${textColor}; border: 2px solid black; padding: 2px 5px; margin-top: 5px; margin-bottom: 5px; display: inline-block; border-radius: 5px;">#${tag}</a>`;
    });

    tagsHtml += '</p>'; // End of the tags paragraph

    const feedElement = document.getElementById(feedId);
    const descriptionElement = feedElement.querySelector('.description');
    descriptionElement.insertAdjacentHTML('afterend', tagsHtml);
}

</script>
</body>
</html>