<?php
// 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";
$opt = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

$pdo = new PDO($dsn, $user, $pass, $opt);

// Busca o título do feed baseado no ID fornecido
$id = $_GET['id'];
$stmt = $pdo->prepare('SELECT title FROM pinfeeds WHERE id = ?');
$stmt->execute([$id]);
$feed = $stmt->fetch();

// Stop words em português
$stopWords = ['a', 'as', 'de', 'da', 'do', 'das', 'dos', 'e', 'em', 'o', 'os', 'um', 'uns', 'uma', 'umas', 'ou'];

$title = $feed['title'];
$words = explode(' ', $title);

$keywords = [];
foreach ($words as $word) {
    if (!in_array(strtolower($word), $stopWords)) {
        $keywords[] = $word;
    }
}

// Obter a página atual
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 16;
$offset = ($page - 1) * $limit;

$relatedFeeds = [];
$relatedFeedIds = [];

foreach ($keywords as $keyword) {
    if (count($relatedFeeds) >= $limit) {
        break;
    }
    $query = 'SELECT * FROM pinfeeds WHERE title LIKE ? ORDER BY id DESC LIMIT ? OFFSET ?';
    $stmt = $pdo->prepare($query);
    $stmt->execute(['%' . $keyword . '%', $limit - count($relatedFeeds), $offset]);
    while ($row = $stmt->fetch()) {
        if (!in_array($row['id'], $relatedFeedIds)) {
            $relatedFeeds[] = $row;
            $relatedFeedIds[] = $row['id'];
        }
        if (count($relatedFeeds) >= $limit) {
            break;
        }
    }
}

header('Content-Type: application/json');
echo json_encode($relatedFeeds);
?>