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

$resultsPerPage = 25;

try {
    $conn = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(['error' => 'Erro na conexão com o banco de dados: ' . $e->getMessage()]);
    exit;
}

$keyword = isset($_GET['search']) ? trim($_GET['search']) : '';
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$offset = ($page - 1) * $resultsPerPage;
$domainName = null;
$feedsplusEnabled = isset($_GET['feedsplusEnabled']) ? filter_var($_GET['feedsplusEnabled'], FILTER_VALIDATE_BOOLEAN) : false;

if (strpos($keyword, 'source:') !== false) {
    list($sourcePrefix, $domainKeyword) = explode(':', $keyword, 2);
    $domainName = $domainKeyword;
    $keyword = ''; // Limpa a keyword para busca textual quando focando em domain
}

function executeQuery($conn, $query, $bindings) {
    $stmt = $conn->prepare($query);
    foreach ($bindings as $key => $value) {
        $stmt->bindValue($key, $value['value'], $value['type']);
    }
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Consulta combinada para ambas as tabelas
$baseQueryFeedsplus = "SELECT id, title, description, pubDate, link, 'feedsplus' AS source FROM feedsplus WHERE 1=1 ";
$baseQueryPinfeeds = "SELECT id, title, description, pubDate, link, user_id, 'pinfeeds' AS source FROM pinfeeds WHERE 1=1 ";
$bindings = [
    ':offset' => ['value' => $offset, 'type' => PDO::PARAM_INT],
    ':limit' => ['value' => $resultsPerPage, 'type' => PDO::PARAM_INT]
];

if (!empty($keyword)) {
    // Modo booleano com todos os termos para ambas as tabelas
    $modifiedKeyword = '+' . implode(' +', explode(' ', $keyword));
    $baseQueryFeedsplus .= "AND MATCH(title) AGAINST(:keyword IN BOOLEAN MODE) ";
    $baseQueryPinfeeds .= "AND MATCH(title) AGAINST(:keyword IN BOOLEAN MODE) ";
    $bindings[':keyword'] = ['value' => $modifiedKeyword, 'type' => PDO::PARAM_STR];
} elseif (!is_null($domainName)) {
    // Filtro por domínio para ambas as tabelas
    $baseQueryFeedsplus .= "AND link LIKE :domainName ";
    $baseQueryPinfeeds .= "AND link LIKE :domainName ";
    $bindings[':domainName'] = ['value' => '%' . $domainName . '%', 'type' => PDO::PARAM_STR];
}

// Ordenação e Limite para ambas as tabelas
if ($feedsplusEnabled) {
    $finalQuery = "($baseQueryFeedsplus) UNION ALL ($baseQueryPinfeeds) ORDER BY pubDate DESC LIMIT :offset, :limit";
} else {
    $finalQuery = "$baseQueryPinfeeds ORDER BY pubDate DESC LIMIT :offset, :limit";
}

try {
    $feeds = executeQuery($conn, $finalQuery, $bindings);
    echo json_encode($feeds);
} catch (PDOException $e) {
    echo json_encode(['error' => 'Erro na consulta ao banco de dados: ' . $e->getMessage()]);
}
?>
