<?php
session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Conexão com o Banco de Dados
$host = 'localhost';
$db = 'digupdog_FEED';
$user = 'digupdog_FEEDadmin';
$pass = 'Raimundinho1';
$charset = 'utf8mb4';

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
    die("Erro na conexão com o banco de dados: " . $conn->connect_error);
}

function getAuthorAvatarByUsername($username, $conn) {
    $username = $conn->real_escape_string($username);
    $query = "SELECT thumbnail FROM pinfeeds WHERE author = '$username' ORDER BY pubDate DESC LIMIT 1";
    $result = $conn->query($query);
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        return $row['thumbnail'];
    } else {
        return false;
    }
}

// Parte para exibir tags
$tagsFile = 'tags.json';
$tags = file_exists($tagsFile) ? json_decode(file_get_contents($tagsFile), true) : [];
shuffle($tags); // Embaralha as tags
$randomTags = array_slice($tags, 0, 80); // Pega 80 tags aleatórias
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:site" content="@nomeDoSeuSite">
    <meta name="twitter:title" content="Título da Página">
    <meta name="twitter:description" content="Descrição da Página">
    <meta name="twitter:image" content="URL_da_Imagem">

    <title>DigUpDOG.com</title>
    <meta id="base-url" content="https://digupdog.com/">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet">
    <link href="styles.css" rel="stylesheet" type="text/css">
    <!-- Scripts Externos -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script async src="https://static.addtoany.com/menu/page.js"></script>
</head>
<body>

<div class="header-content">
    <div class="search-bar">
        <button class="home-button"><i class="fas fa-hashtag"></i></button>
        <button class="menu-button"><i class="fas fa-bars menu-icon"></i></button>
        <input id="search-query" placeholder="#..." type="text" />
        <button id="search-button">
            <i class="fas fa-search search-icon"></i>
        </button>
        <a class="button pin" id="addPinButton" href="https://digupdog.com/aaa1.php" target="_self"><i class="fas fa-plus"></i></a>
        <a class="category-button plus" href="https://digupdog.com/plus.php" target="_self">18+</a>
    </div>
    
    <div id="side-menu" class="side-menu">
        <!-- Conteúdo do menu aqui -->
        <a href="#">Link 1</a>
        <a href="#">Link 2</a>
        <!-- Mais links do menu -->
    </div>

    <!-- Overlay -->
    <div class="overlay"></div>

    <div class="category-buttons-container">
        <div class="category-buttons">
            <div class="left-arrow"></div>
            <div class="category-buttons-wrapper" style="display: flex; justify-content: center; flex-wrap: wrap;">
                <!-- Tags Container -->
                <div id="tags-container" style="margin-top: 2px; text-align: center; width: 100%;">
                    <?php foreach ($randomTags as $tag): ?>
                        <a href="#" class="tag-link tag-search-link" data-tag="<?php echo htmlspecialchars($tag); ?>">#<?php echo htmlspecialchars($tag); ?></a>
                    <?php endforeach; ?>
                    <a href="#" id="reload-tags" title="Recarregar tags"><i class="fas fa-sync-alt"></i></a>
                </div>
            </div>
            <div class="right-arrow"></div>
        </div>
    </div>

    <!-- Login/Register Section or Welcome Message -->
    <div class="container"></div>
    <div class="login-register-section" id="loginSection">
        <?php
        // Verifica se o usuário está logado
        if (isset($_SESSION['username'])) {
            $username = htmlspecialchars($_SESSION['username']);
            $authorAvatar = getAuthorAvatarByUsername($username, $conn);
            echo "<a href='perfil.php?autor=$username'>";
            if ($authorAvatar !== false) {
                echo "<img src='$authorAvatar' alt='Avatar' class='author-avatar' style='width: 20px; height: 20px; margin-right: 5px; border: 2px solid black; border-radius: 20px; vertical-align: middle;'>";
            }
            echo "@" . $username . "</a>"; // Adicionando "@" antes do nome do usuário
            echo "<a href='logout.php'><i class='fas fa-sign-out-alt'></i></a>";
        } else {
            // Usuário não está logado
            echo "<a href='login.html'><i class='fas fa-sign-in-alt'></i></a>";
            echo "<a href='register.html'><i class='fas fa-user-plus'></i></a>";
        }
        ?>
    </div>
</div>

<div class="result-list" id="feeds"></div>

<p>
    <button id="myBtn" onclick="topFunction()" title="Go to top">
        <i class="fas fa-arrow-up"></i>
    </button>
</p>

<footer>Beta 6.0</footer>

<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v10.0" nonce="nonceValue"></script>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
<script async src="https://telegram.org/js/telegram-widget.js?22"></script>

<!-- Scripts Próprios -->
<script src="https://digupdog.com/utils.js"></script>
<script src="https://digupdog.com/feeds.js"></script>
<script src="https://digupdog.com/search.js"></script>
<script src="https://digupdog.com/ui.js"></script>
<script src="https://digupdog.com/main.js"></script>
<script src="https://digupdog.com/loadFeeds.js"></script>

<script>
$(document).ready(function() {
    $('.tag-link').click(function(e) {
        e.preventDefault();
        var tag = $(this).text().substr(1); // Remove o '#'
        $('#search-query').val(tag);
        // Implemente a lógica de busca aqui
    });

    document.getElementById('addPinButton').addEventListener('click', function(e) {
        <?php if (!isset($_SESSION['username'])): ?>
            e.preventDefault();
            window.location.href = 'login.html';
        <?php endif; ?>
    });

    window.addEventListener('scroll', function() {
        var loginSection = document.querySelector('.login-register-section');
        var scrollPosition = window.scrollY;
        var categoryButtons = document.querySelector('.category-buttons-container');

        if (scrollPosition > 100) {
            loginSection.style.position = 'fixed';
            loginSection.style.bottom = '10px';
            loginSection.style.left = '10px';
            loginSection.style.zIndex = '50';
            categoryButtons.style.marginBottom = loginSection.offsetHeight + 'px';
        } else {
            loginSection.style.position = 'static';
            categoryButtons.style.marginBottom = '0';
        }
    });

    document.addEventListener('DOMContentLoaded', function() {
        var tagElements = document.querySelectorAll('.tag-link');

        tagElements.forEach(function(tagElement) {
            var tagText = tagElement.dataset.tag;
            var bgColor = stringToColor(tagText);
            var textColor = isColorDark(bgColor) ? 'white' : 'black';

            tagElement.style.backgroundColor = bgColor;
            tagElement.style.color = textColor;
            tagElement.style.border = '2px solid black';
            tagElement.style.padding = '5px 10px';
            tagElement.style.marginRight = '5px';
            tagElement.style.borderRadius = '5px';
            tagElement.style.textDecoration = 'none';
            tagElement.style.display = 'inline-block';
            tagElement.style.marginBottom = '5px';
            tagElement.style.fontWeight = 'bold';

            tagElement.addEventListener('click', function(e) {
                e.preventDefault();
                var tag = this.dataset.tag;
                $('#search-query').val(tag);
                clearResults();
                performSearch();
            });
        });
    });

    function clearResults() {
        $('#feeds').empty();
    }

    function reloadTags() {
        $.ajax({
            url: 'tags.json',
            method: 'GET',
            dataType: 'json',
            success: function(response) {
                updateTags(response);
            }
        });
    }

    function updateTags(tags) {
        var container = $('#tags-container');
        container.empty();

        shuffleArray(tags);
        var limitedTags = tags.slice(0, 80);

        limitedTags.forEach(function(tag) {
            var tagElement = $('<a href="#" class="tag-link tag-search-link" data-tag="' + tag + '">#' + tag + '</a>');
            var bgColor = stringToColor(tag);
            var textColor = isColorDark(bgColor) ? 'white' : 'black';

            tagElement.css({
                'backgroundColor': bgColor,
                'color': textColor,
                'border': '2px solid black',
                'padding': '3px 3px',
                'marginRight': '5px',
                'borderRadius': '5px',
                'textDecoration': 'none',
                'display': 'inline-block',
                'marginBottom': '5px',
                'fontWeight': 'bold'
            });

            container.append(tagElement);
        });

        container.append('<a href="#" id="reload-tags" title="Recarregar tags"><i class="fas fa-sync-alt"></i></a>');

        // Adiciona novamente o evento ao botão de recarregar tags
        document.getElementById('reload-tags').addEventListener('click', function(e) {
            e.preventDefault();
            reloadTags();
        });
    }

    function shuffleArray(array) {
        for (var i = array.length - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }

    reloadTags();

    document.querySelector('.menu-button').addEventListener('click', function() {
        let icon = this.querySelector('.menu-icon');
        let sideMenu = document.querySelector('.side-menu');
        let overlay = document.querySelector('.overlay');

        if (sideMenu.style.width === '30%' || sideMenu.style.width === '95%') {
            sideMenu.style.width = '0';
            overlay.style.display = 'none';
            document.body.style.overflow = 'auto';
            this.classList.remove('open');
            icon.classList.remove('fa-times');
            icon.classList.add('fa-bars');
        } else {
            sideMenu.style.width = window.innerWidth <= 768 ? '95%' : '30%';
            overlay.style.display = 'block';
            document.body.style.overflow = 'hidden';
            this.classList.add('open');
            icon.classList.remove('fa-bars');
            icon.classList.add('fa-times');
        }
    });

    document.querySelector('.home-button').addEventListener('click', function() {
        window.location.reload();
    });
});
</script>

</body>
</html>