<?php
header('Content-Type: application/json; charset=utf-8');
header("Access-Control-Allow-Origin: *");



// Conexão com o banco
$conn = new mysqli("mysql.sindicatoseth.com.br", "sindicatoseth", "Maqmaq1345", "sindicatoseth"); 
if ($conn->connect_error) {
    echo json_encode([]);
    exit;
}

$q = isset($_GET['q']) ? trim($_GET['q']) : '';
// if (empty($q)) {
//     echo json_encode([]);
//     exit;
// }

// Monta a consulta com placeholders
$sql = "
    SELECT noticias.NoticiaTitulo, noticias.NoticiaSubtitulo, noticias.NoticiaData, noticias.NoticiaImagem, noticias.NoticiaID, categoria.CategoriaID, categoria.CategoriaNome, noticias.noticianoar
    FROM noticias 
    INNER JOIN categoria ON noticias.NoticiaCategoria = categoria.CategoriaID
    WHERE NoticiaTitulo LIKE ? OR NoticiaCorpo LIKE ? OR CategoriaNome LIKE ?
    ORDER BY noticianoar DESC
    LIMIT 5
";

// Prepara a consulta
$stmt = $conn->prepare($sql);

// Monta o parâmetro com % para o LIKE
$search = "%$q%";
$stmt->bind_param("sss", $search, $search, $search);

// Executa e pega resultado
$stmt->execute();
$result = $stmt->get_result();

$noticias = array();

function Nome_Url($palavra) {
    $cacento = "^~`'?!.,#/:+%$()";
    $sacento = "aaaaaeeeeiiiiooooouuuuAAAAAEEEEIIIOOOOOUUUUcCnN";
    $texto = "";
    if ($palavra != "") {
        for ($x = 0; $x < mb_strlen($palavra, 'UTF-8'); $x++) {
            $letra = mb_substr($palavra, $x, 1, 'UTF-8');
            $pos_acento = mb_strpos($cacento, $letra, 0, 'UTF-8');
            if ($pos_acento !== false) {
                $letra = mb_substr($sacento, $pos_acento, 1, 'UTF-8');
            }
            $texto .= $letra;
        }
        $texto = mb_strtolower($texto, 'UTF-8');
        $texto = str_replace(" ", "-", $texto);
        return $texto;
    }
    return "";
}

while ($row = $result->fetch_assoc()) {
    array_push($noticias, [
        'titulo' => $row['NoticiaTitulo'],
        'descricao' => $row['NoticiaSubtitulo'],
        'categoria' => $row['CategoriaNome'],
        'data' => date('d \d\e F \d\e Y', strtotime($row['noticianoar'])),
        'imagem' => $row['NoticiaImagem'],
        'url' => 'https://sindicatoseth.com.br/noticia/'.$row['NoticiaID'].'/'.Nome_Url($row['NoticiaTitulo'])
    ]);
}

//print_r($noticias);

function utf8ize($mixed) {
    if (is_array($mixed)) {
        foreach ($mixed as $key => $value) {
            $mixed[$key] = utf8ize($value);
        }
    } elseif (is_string($mixed)) {
        // Corrige strings com encoding estranho
        return mb_convert_encoding($mixed, 'UTF-8', 'UTF-8, ISO-8859-1, ISO-8859-15, Windows-1252');
    }
    return $mixed;
}

echo json_encode(utf8ize($noticias), JSON_UNESCAPED_UNICODE);
//echo json_last_error_msg();