<?php
// get_pinfeeds.php - VERSÃO CORRIGIDA
// O problema pode estar na compressão gzip. Vamos torná-la opcional.

session_start();

// Verifique se o usuário está logado e defina o user_id
$user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;

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

$resultsPerPage = 21; // Número de feeds por página

try {
    // Conexão com o banco de dados usando PDO
    $conn = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    // Retorna erro em JSON
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Erro na conexão com o banco de dados: ' . $e->getMessage()]);
    exit;
}

// Variáveis de entrada
$keyword = isset($_GET['search']) ? trim($_GET['search']) : '';
$commentSearchTerm = isset($_GET['comment_search']) ? trim($_GET['comment_search']) : '';
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$offset = ($page - 1) * $resultsPerPage;
$domainName = null;

// Log para debug (remova em produção)
error_log("get_pinfeeds.php - Página: $page, Offset: $offset, Busca: $keyword");

// Se a pesquisa contiver "source:", busque por domínio
if (strpos($keyword, 'source:') !== false) {
    list($sourcePrefix, $domainKeyword) = explode(':', $keyword, 2);
    $domainName = trim($domainKeyword);
    $keyword = ''; // Limpa a pesquisa textual quando focado no domínio
}

// Adiciona o user_id aos bindings
$bindings = [
    ':offset' => ['value' => $offset, 'type' => PDO::PARAM_INT],
    ':limit' => ['value' => $resultsPerPage, 'type' => PDO::PARAM_INT],
    ':user_id' => ['value' => $user_id ?? 0, 'type' => PDO::PARAM_INT]
];

// Construir a consulta base
$baseQuery = "SELECT DISTINCT f.*, 
              (SELECT COUNT(*) FROM comments c WHERE c.feed_id = f.id) AS comments_count, 
              (SELECT COUNT(*) FROM favorites fav WHERE fav.feed_id = f.id AND fav.user_id = :user_id) AS isSaved, 
              (SELECT ld.action FROM likes_dislikes ld WHERE ld.feed_id = f.id AND ld.user_id = :user_id) AS user_action,
              CASE WHEN EXISTS (SELECT 1 FROM comments c WHERE c.feed_id = f.id AND c.user_id = :user_id) THEN 1 ELSE 0 END AS user_has_commented
              FROM pinfeeds f ";

// Filtros de pesquisa
if (!empty($keyword)) {
    $query = $baseQuery . " 
              WHERE (f.title LIKE :keyword OR f.description LIKE :keyword)
              GROUP BY f.id
              ORDER BY f.id DESC LIMIT :offset, :limit";
    $bindings[':keyword'] = ['value' => '%' . $keyword . '%', 'type' => PDO::PARAM_STR];
} elseif (!is_null($domainName)) {
    $query = $baseQuery . " 
              WHERE f.link LIKE :domainName 
              GROUP BY f.id
              ORDER BY f.id DESC LIMIT :offset, :limit";
    $bindings[':domainName'] = ['value' => '%' . $domainName . '%', 'type' => PDO::PARAM_STR];
} else {
    $query = $baseQuery . " 
              GROUP BY f.id
              ORDER BY f.id DESC LIMIT :offset, :limit";
}

// Executa a consulta e obtém os feeds
try {
    $stmt = $conn->prepare($query);
    foreach ($bindings as $key => $value) {
        $stmt->bindValue($key, $value['value'], $value['type']);
    }
    $stmt->execute();
    $feeds = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Erro na consulta: ' . $e->getMessage()]);
    exit;
}

// Se não houver feeds, retorna array vazio
if (empty($feeds)) {
    header('Content-Type: application/json');
    echo json_encode([]);
    exit;
}

// Obtém IDs de todos os feeds da página
$feedIds = array_column($feeds, 'id');

// Consulta para obter comentários
if (!empty($feedIds)) {
    $placeholders = implode(',', array_fill(0, count($feedIds), '?'));
    $commentsQuery = "
        SELECT c.comment_id, c.user_id, c.feed_id, c.comment_text, c.created_at, 
               p.author, p.thumbnail AS author_thumbnail, 
               c.link_preview, c.title, c.description, c.thumbnail
        FROM comments c
        LEFT JOIN (
            SELECT p1.user_id, p1.author, p1.thumbnail
            FROM pinfeeds p1
            INNER JOIN (
                SELECT user_id, MAX(pubDate) as max_pubDate
                FROM pinfeeds
                GROUP BY user_id
            ) p2 ON p1.user_id = p2.user_id AND p1.pubDate = p2.max_pubDate
        ) p ON c.user_id = p.user_id
        WHERE c.feed_id IN ($placeholders)
        ORDER BY c.created_at DESC";
    
    try {
        $stmt = $conn->prepare($commentsQuery);
        $stmt->execute($feedIds);
        $allComments = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Organiza comentários por feed_id
        $commentsByFeed = [];
        foreach ($allComments as $comment) {
            $commentsByFeed[$comment['feed_id']][] = $comment;
        }
        
        // Associa comentários aos feeds
        foreach ($feeds as &$feed) {
            $feed['comments'] = $commentsByFeed[$feed['id']] ?? [];
        }
    } catch (PDOException $e) {
        // Se houver erro nos comentários, continua sem eles
        foreach ($feeds as &$feed) {
            $feed['comments'] = [];
        }
    }
}

// Retorna os feeds em formato JSON
header('Content-Type: application/json');
header('Cache-Control: no-cache, must-revalidate');

// Verifica se o cliente aceita gzip
$acceptEncoding = isset($_SERVER['HTTP_ACCEPT_ENCODING']) ? $_SERVER['HTTP_ACCEPT_ENCODING'] : '';
if (strpos($acceptEncoding, 'gzip') !== false) {
    // Cliente aceita gzip
    header('Content-Encoding: gzip');
    echo gzencode(json_encode($feeds));
} else {
    // Cliente não aceita gzip
    echo json_encode($feeds);
}
?>