<?php
session_start();

// Database credentials
$host = 'localhost';
$db = 'digupdog_FEED';
$user = 'digupdog_FEEDadmin';
$pass = 'Raimundinho1';
$charset = 'utf8mb4';

// Check if the user is logged in, otherwise set user_id to null
$user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;

try {
    // Database connection using PDO
    $conn = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die('Database connection error: ' . $e->getMessage());
}

// Get the feed_id from the URL
$feed_id = isset($_GET['feed_id']) ? intval($_GET['feed_id']) : 0;

if ($feed_id <= 0) {
    die('Invalid Feed ID.');
}

// Search variables
$commentSearchTerm = isset($_GET['comment_search']) ? trim($_GET['comment_search']) : '';

// Insert a new comment or reply
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $comment_text = isset($_POST['comment_text']) ? trim($_POST['comment_text']) : '';
    $parent_comment_id = isset($_POST['parent_comment_id']) ? intval($_POST['parent_comment_id']) : null;

    if ($user_id && !empty($comment_text)) {
        $insertQuery = "INSERT INTO comments (feed_id, user_id, comment_text, parent_comment_id, created_at) 
                        VALUES (:feed_id, :user_id, :comment_text, :parent_comment_id, NOW())";
        $stmt = $conn->prepare($insertQuery);
        $stmt->execute([
            ':feed_id' => $feed_id,
            ':user_id' => $user_id,
            ':comment_text' => $comment_text,
            ':parent_comment_id' => $parent_comment_id
        ]);

        // Redirect to avoid form resubmission
        header("Location: ?feed_id=$feed_id");
        exit;
    }
}

// Get feed information and the author's latest thumbnail
$feedQuery = "
    SELECT f.title, f.description, f.thumbnail, u.username, (
        SELECT p.thumbnail 
        FROM pinfeeds p 
        WHERE p.user_id = f.user_id 
        ORDER BY p.pubDate DESC 
        LIMIT 1
    ) AS author_avatar
    FROM pinfeeds f
    LEFT JOIN user_myhashtag u ON f.user_id = u.ID
    WHERE f.id = :feed_id";
$feedStmt = $conn->prepare($feedQuery);
$feedStmt->execute([':feed_id' => $feed_id]);
$feed = $feedStmt->fetch(PDO::FETCH_ASSOC);

if (!$feed) {
    die('Feed not found.');
}

// Modify the comment query to include search
$commentsQuery = "
    SELECT c.comment_id, c.comment_text, c.created_at, u.username, 
           (SELECT p.thumbnail FROM pinfeeds p WHERE p.user_id = c.user_id ORDER BY p.pubDate DESC LIMIT 1) AS author_thumbnail
    FROM comments c
    LEFT JOIN user_myhashtag u ON c.user_id = u.ID
    WHERE c.feed_id = :feed_id";

// Add search filter if a term is provided
if (!empty($commentSearchTerm)) {
    $commentsQuery .= " AND c.comment_text LIKE :comment_search";
}

$commentsQuery .= " ORDER BY c.created_at DESC";

$commentsStmt = $conn->prepare($commentsQuery);
$commentsStmt->bindValue(':feed_id', $feed_id, PDO::PARAM_INT);

if (!empty($commentSearchTerm)) {
    $commentsStmt->bindValue(':comment_search', '%' . $commentSearchTerm . '%', PDO::PARAM_STR);
}

$commentsStmt->execute();
$comments = $commentsStmt->fetchAll(PDO::FETCH_ASSOC);

// Function to get replies to a comment
function getCommentReplies($conn, $comment_id, $searchTerm = null) {
    $query = "
        SELECT c.comment_id, c.comment_text, c.created_at, u.username, 
               (SELECT p.thumbnail FROM pinfeeds p WHERE p.user_id = c.user_id ORDER BY p.pubDate DESC LIMIT 1) AS author_thumbnail
        FROM comments c
        LEFT JOIN user_myhashtag u ON c.user_id = u.ID
        WHERE c.parent_comment_id = :comment_id";

    if (!empty($searchTerm)) {
        $query .= " AND c.comment_text LIKE :comment_search";
    }

    $query .= " ORDER BY c.created_at ASC";
    $stmt = $conn->prepare($query);
    $stmt->bindValue(':comment_id', $comment_id, PDO::PARAM_INT);

    if (!empty($searchTerm)) {
        $stmt->bindValue(':comment_search', '%' . $searchTerm . '%', PDO::PARAM_STR);
    }

    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Recursive function to display comments and their replies
function displayComments($conn, $comments, $searchTerm = null, $level = 0) {
    $seenComments = [];
    foreach ($comments as $comment) {
        if (in_array($comment['comment_id'], $seenComments)) {
            continue;
        }
        $seenComments[] = $comment['comment_id'];

        // Alternar bordas coloridas de acordo com o nível da resposta
        $borderClass = 'level-' . ($level % 5 + 1);
        $direction = ($level % 2 === 0) ? 'level-left' : 'level-right';
        ?>
        <div class="comment comment-card <?= $borderClass ?> <?= $direction ?>" data-comment-id="<?= $comment['comment_id'] ?>" style="margin-left: <?= $level * 10 ?>px;">
            <div class="comment-header">
                <img src="<?= htmlspecialchars($comment['author_thumbnail'] ?: 'default-avatar.png') ?>" alt="@<?= htmlspecialchars($comment['username']) ?>" class="comment-avatar">
                @<?= htmlspecialchars($comment['username']) ?>
            </div>
            <div class="comment-body">
                <?= htmlspecialchars($comment['comment_text']) ?>
            </div>
            <div class="comment-meta">
                <?= htmlspecialchars($comment['created_at']) ?>
            </div>

            <!-- Botões de ação -->
            <div class="form-buttons">
                <button class="reply-btn" data-comment-id="<?= $comment['comment_id'] ?>">Responder</button>
                <button class="edit-btn">Editar</button>
                <button class="delete-btn">Apagar</button>
            </div>

            <!-- Formulário de Reply oculto -->
            <div class="reply-form-container" id="reply-form-<?= $comment['comment_id'] ?>" style="display: none;">
                <form action="" method="POST">
                    <textarea name="comment_text" placeholder="Digite sua resposta..."></textarea>
                    <input type="hidden" name="parent_comment_id" value="<?= $comment['comment_id'] ?>">
                    <button type="submit" class="submit-btn">Enviar</button>
                </form>
            </div>

            <!-- Exibir Replies -->
            <div class="comment-replies <?= $direction ?> <?= $borderClass ?>">
                <?php
                $replies = getCommentReplies($conn, $comment['comment_id'], $searchTerm);
                if (count($replies) > 0) {
                    displayComments($conn, $replies, $searchTerm, $level + 1);
                }
                ?>
            </div>
        </div>
        <?php
    }
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Comentários com Subníveis Melhorados</title>
    <style>
        /* Container principal */
        .container {
            width: 90%;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px 0;
        }

        /* Estilo dos comentários */
        .comment-card {
            border: 1px solid #d1d1d1;
            border-radius: 8px;
            margin-bottom: 15px;
            padding: 15px 20px;
            background-color: #f8f8f8;
            box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
            transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
            position: relative;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .comment-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
        }

        /* Estilo dos subníveis */
        .comment-replies.level-left {
            margin-right: 30px;
            padding-right: 15px;
            border-right: 2px solid #007bff;
            animation: slideInLeft 0.3s ease;
        }

        .comment-replies.level-right {
            margin-left: 30px;
            padding-left: 15px;
            border-left: 2px solid #007bff;
            animation: slideInRight 0.3s ease;
        }

        /* Diferentes cores de borda para subníveis */
        .comment-replies.level-1 { border-color: #007bff; }
        .comment-replies.level-2 { border-color: #28a745; }
        .comment-replies.level-3 { border-color: #ffc107; }
        .comment-replies.level-4 { border-color: #17a2b8; }
        .comment-replies.level-5 { border-color: #dc3545; }

        /* Animação para entrada suave */
        @keyframes slideInLeft {
            from { opacity: 0; transform: translateX(-20px); }
            to { opacity: 1; transform: translateX(0); }
        }

        @keyframes slideInRight {
            from { opacity: 0; transform: translateX(20px); }
            to { opacity: 1; transform: translateX(0); }
        }

        /* Avatar do comentário */
        .comment-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-right: 15px;
            object-fit: cover;
            border: 2px solid #ccc;
        }

        /* Cabeçalho do comentário */
        .comment-header {
            font-weight: bold;
            font-size: 16px;
            margin-bottom: 8px;
            color: #333;
            display: flex;
            align-items: center;
        }

        /* Corpo do comentário */
        .comment-body {
            font-size: 14px;
            color: #555;
            margin-bottom: 10px;
        }

        /* Formulário de resposta */
        .reply-form {
            margin-top: 10px;
        }

        .reply-form textarea {
            width: 100%;
            padding: 10px;
            border-radius: 6px;
            border: 1px solid #ced4da;
            margin-bottom: 8px;
            font-size: 14px;
        }

        .form-buttons {
            display: flex;
            gap: 10px;
        }

        .reply-btn, .edit-btn, .delete-btn, .cancel-btn {
            padding: 8px 12px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 12px;
            border: none;
            transition: background-color 0.3s ease;
        }

        .reply-btn {
            background-color: #007bff;
            color: white;
        }

        .reply-btn:hover {
            background-color: #0056b3;
        }

        .edit-btn {
            background-color: #28a745;
            color: white;
        }

        .edit-btn:hover {
            background-color: #218838;
        }

        .delete-btn {
            background-color: #dc3545;
            color: white;
        }

        .delete-btn:hover {
            background-color: #c82333;
        }

        .cancel-btn {
            background-color: #6c757d;
            color: white;
        }

        .cancel-btn:hover {
            background-color: #5a6268;
        }

        /* Funções de curtir e descurtir */
        .like-dislike {
            display: flex;
            gap: 10px;
            margin-top: 8px;
        }

        .like-btn, .dislike-btn {
            background-color: transparent;
            border: none;
            cursor: pointer;
            font-size: 14px;
            display: flex;
            align-items: center;
            color: #007bff;
            transition: color 0.3s ease;
        }

        .like-btn:hover, .dislike-btn:hover {
            color: #0056b3;
        }

        .like-btn i, .dislike-btn i {
            margin-right: 5px;
        }

        /* Contador de respostas */
        .reply-count {
            font-size: 12px;
            color: #666;
            margin-left: 10px;
        }

        /* Botão para expandir/colapsar respostas */
        .toggle-replies {
            background: none;
            border: none;
            color: #007bff;
            cursor: pointer;
            padding: 0;
            font-size: 12px;
            display: flex;
            align-items: center;
            transition: color 0.3s ease;
        }

        .toggle-replies:hover {
            color: #0056b3;
        }

        .toggle-replies i {
            margin-right: 5px;
        }

        .toggle-replies i::before {
            content: '▼'; /* Ícone de seta para baixo */
        }

        .toggle-replies.collapsed i::before {
            content: '►'; /* Ícone de seta para direita ao colapsar */
        }

        /* Estilos responsivos */
        @media (max-width: 768px) {
            .comment-card {
                padding: 15px;
            }

            .comment-replies.level-left, .comment-replies.level-right {
                margin-right: 0;
                margin-left: 0;
                padding-left: 0;
                padding-right: 0;
                border: none;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="feed-header">
            <?php if ($feed['thumbnail']): ?>
                <img src="<?= htmlspecialchars($feed['thumbnail']) ?>" alt="Thumbnail" class="feed-thumbnail">
            <?php endif; ?>
            <div>
                <h1 class="feed-title"><?= htmlspecialchars($feed['title']) ?></h1>
                <p class="feed-description"><?= htmlspecialchars($feed['description']) ?></p>
                <div class="result-header">
                    <img src="<?= htmlspecialchars($feed['author_avatar'] ?: 'default-avatar.png') ?>" alt="Avatar" class="feed-author-avatar">
                    <a href="#" class="author-search-link">@<?= htmlspecialchars($feed['username']) ?></a>
                </div>
            </div>
        </div>

        <div class="comment-section">
            <h2>Comentários (<?= count($comments) ?>)</h2>

            <!-- Busca de comentários -->
            <div class="search-box">
                <form action="" method="GET">
                    <input type="hidden" name="feed_id" value="<?= $feed_id ?>">
                    <input type="text" name="comment_search" placeholder="Buscar comentários..." value="<?= htmlspecialchars($commentSearchTerm) ?>">
                    <button type="submit">Buscar</button>
                </form>
            </div>

            <!-- Exibição de comentários -->
            <?php if (count($comments) > 0): ?>
                <?php displayComments($conn, $comments, $commentSearchTerm); ?>
            <?php else: ?>
                <p>Nenhum comentário encontrado.</p>
            <?php endif; ?>
        </div>

        <!-- Novo formulário de comentário -->
        <div class="new-comment">
            <h3>Adicionar novo comentário:</h3>
            <?php if ($user_id): ?>
                <form action="" method="POST">
                    <textarea name="comment_text" placeholder="Escreva seu comentário aqui..."></textarea>
                    <input type="hidden" name="parent_comment_id" id="parent_comment_id" value="">
                    <button type="submit" class="submit-btn">Enviar Comentário</button>
                </form>
            <?php else: ?>
                <p>Você precisa <a href="login.php">fazer login</a> para comentar.</p>
            <?php endif; ?>
        </div>
    </div>

    <script>
    // Script para lidar com a visibilidade do formulário de resposta e respostas aninhadas
    document.addEventListener('DOMContentLoaded', function() {
        const replyButtons = document.querySelectorAll('.reply-btn');

        replyButtons.forEach(button => {
            button.addEventListener('click', function() {
                const commentId = this.getAttribute('data-comment-id');
                const replyForm = document.getElementById('reply-form-' + commentId);

                if (replyForm.style.display === 'block') {
                    replyForm.style.display = 'none';
                } else {
                    replyForm.style.display = 'block';
                }

                replyForm.querySelector('textarea').focus();
            });
        });

        // Script para expandir longos comentários
        const expandButtons = document.querySelectorAll('.expand-btn');
        expandButtons.forEach(button => {
            button.addEventListener('click', function() {
                const commentText = this.closest('.comment-content').querySelector('.comment-text');
                commentText.classList.toggle('expand');
                this.textContent = commentText.classList.contains('expand') ? 'Mostrar Menos' : 'Mostrar Mais';
            });
        });
    });
    </script>
</body>
</html>
