<?php
// Ativa debug FORTEMENTE
$bootstrapPath = __DIR__ . '/../bootstrap.php';
if (file_exists($bootstrapPath)) {
    require_once $bootstrapPath;
} else {
    echo "<!-- bootstrap não encontrado  -->\n";
}
define('DEBUG_MODE', true); //mude para false para não exibir os erros
ob_start('compress_output');
//
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
//error_reporting(E_ALL);
// ─── Headers para noCache ─────────────────────────────────────────────────────────────────────────────────────────────
/*
if (function_exists('opcache_invalidate')) {
    opcache_invalidate(__FILE__, true); // Força recarregar este arquivo
}
// Desliga cache de opcode para execução atual
ini_set('opcache.enable', 0);
ini_set('opcache.enable_cli', 1); // Para CLI se for o caso
// Força revalidação a cada requisição
ini_set('opcache.revalidate_freq', 0);
ini_set('opcache.validate_timestamps', 1);
//
header_remove('Cache-Control');
header_remove('Pragma');
header_remove('Expires');
// Headers anti-cache MÁXIMO
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0');
header('Pragma: no-cache');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Data no passado
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
// Previne cache em proxies
header('Cache-Control: private');
// Força sempre nova requisição
header('ETag: "' . md5(uniqid()) . '"'); // ETag aleatório  
*/
// ─── Headers  ─────────────────────────────────────────────────────────────────────────────────────────────

ini_set('session.cookie_secure', 1); // Garante que o cookie só seja enviado por HTTPS
ini_set('session.cookie_httponly', 1); // Impede acesso ao cookie via JavaScript
ini_set('session.cookie_samesite', 'Strict'); // Protege contra ataques CSRF

//ob_start();
header('Vary: User-Agent');
header("Content-Type: text/html; charset=UTF-8", true);
header("Pragma: cache");
header('Cache-Control: public, max-age=259200');
header("Strict-Transport-Security: max-age=31536000");
header("X-Content-Type-Options: nosniff");
header("X-Frame-Options: SAMEORIGIN");
header("Content-Security-Policy-Report-Only: default-src 'self';script-src https://*.googletagmanager.com 'unsafe-inline' 'report-sample' 'self' https://www.google-analytics.com/analytics.js https://www.googletagmanager.com/gtag/js;style-src 'unsafe-inline' 'report-sample' 'self';object-src 'none';base-uri 'self';connect-src 'self' https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com;font-src 'self';frame-src 'self' https://pub.lojadosom.com.br;img-src https://*.google-analytics.com https://*.googletagmanager.com 'self' https://img.lojadosom.com.br https://pix.lojadosom.com.br data:;manifest-src 'self';media-src 'self';report-uri https://6532ebbfb6167cf8f68c6cf7.endpoint.csper.io/?v=0;worker-src 'none';");


// ─── Funções ─────────────────────────────────────────────────────────────────────────────────────────────
function criaLogs($nomArq, $tempoExec, $qtdProds, $qtdSubsMenu, $criar = 'N', $dtaCreate, $pasta, $erro = '')
{
  //criaLogs($arqCache, $scripts->displaytime(), count($products[0]['produtos']), $qtos, 'N'); 
  $ip = getenv("REMOTE_ADDR");
  $today = date("Ymd");
  $user = $_SERVER["HTTP_USER_AGENT"];
  $hora = date("H");
  $bot = (preg_match('|www.google.com/bot.html|i', $user)) ? 'B' : 'U';
  if (preg_match('|www.google.com/bot.html|i', $user)) {
    $bot = 'B';
    $user = "googlebot";
  } elseif (preg_match('|bot|i', $user)) {
    $bot = 'R';
    $user = "Robo-bot";
  } elseif (preg_match('|spider|i', $user)) {
    $bot = 'R';
    $user = "Spider-bot";
  } elseif (preg_match('|GoogleOther|i', $user)) {
    $bot = 'B';
    $user = "GoogleOther";
  } elseif (preg_match('/crawle|admantx/i', $user)) {
    $bot = "C";
    $user = "crawler-bot";
  } elseif (preg_match('|facebookexternalhit|i', $user)) {
    $bot = "F";
    $user = "face-bot";
  } else {
    $bot = 'U';
    $dif =  intval((strtotime(date("Ymd")) - strtotime($dtaCreate)) / 86400);
    $modDesk = (Scripts::isMobile()) ? 'M' : 'D';
    $rota = "/var/www/lojadosom/html/caches/vendas/logs/{$erro}{$today}-ultimos-acessos.txt";
    $dados = "{$hora}|{$ip}|{$nomArq}|{$tempoExec}|{$qtdProds}|{$qtdSubsMenu}|{$modDesk}|{$bot}|{$criar}|{$dif}|$pasta|$user\n";
    if ($fpn = fopen($rota, 'a+')) {
      fwrite($fpn, $dados);
      fclose($fpn);
    }
  }
  if ($bot == 'B') {
    $dif =  intval((strtotime(date("Ymd")) - strtotime($dtaCreate)) / 86400);
    $modDesk = (Scripts::isMobile()) ? 'M' : 'D';
    $rota = "/var/www/lojadosom/html/caches/vendas/logs/{$today}-robos.txt";
    $dados = "{$hora}|{$ip}|{$nomArq}|{$tempoExec}|{$qtdProds}|{$qtdSubsMenu}|{$modDesk}|{$bot}|{$criar}|{$dif}|$pasta|$user\n";
    if ($fpn = fopen($rota, 'a+')) {
      fwrite($fpn, $dados);
      fclose($fpn);
    }
  }
}
function pegaMarcasProdutos(array $prods){
    $nameMarca = [];
    $keyMarcas = '';
    foreach ($prods as  $value) {

        if (count($nameMarca) < 5) {
            $newM = isset($value['subtitle']) ? trim(preg_replace('/.*marca:\s*([^|]+).*/', '$1', $value['subtitle'])) : '';
            $newMarca = Scripts::tiraAcento(strtolower(preg_replace('/\\s\\s+/', ' ', $newM)));
            if (!in_array($newMarca, $nameMarca)) {
                if ($newMarca) {
                    $nameMarca[] = $newMarca;
                    $keyMarcas .= "$newM, ";
                }
            }
        }
        
    }
    return $keyMarcas;

}
function criaSubmenuHtml(array $subM, string $path, string $amp){
   
    $wordsMenu = '';
    $idCat = '';
    $cols = 0;
    $categAnterior = '';
    $idCatAnterior = '';
    $primeiraCategoria = '';
    $primeiraCatId = '';
    $firstCateg = '';
    $keyNro = '';
    $relacionados = '';
    $buscaIdsShop = [];
  

    $qtos = !empty($subM) ? count($subM) : 0;
    
    if (!$qtos) {
        return; // ou whatever o fluxo exige
    }

    $shopUrl   = 'https://www.lojadosom.com.br/shopping/comprar-';
    $similUrl  = 'https://www.lojadosom.com.br/similares/';
    $especUrl  = 'https://www.lojadosom.com.br/especiais/';

    $bgColors = [
        'categAnterior' => '#CCCCCC',
        'subcat'        => '#CCCCCC',
        'categ'         => '#FFCC66',
        'similares'     => '#79B7EA',
    ];

    foreach ($subM as $key => $subMenus) {
        $caminho  = $subMenus['caminhos'];
        $idCat_s  = $subMenus['idCat'];
        $nomCat   = $subMenus['nomCat'];
        $nomUC    = ucwords($nomCat);
        $nomSlug  = Scripts::tiraAcento($nomCat, true);
        $nomDash  = urlencode(str_replace(' ', '-', $nomCat));
        $isShop   = ($path === 'shopping');

        // Registra firstCateg e buscaIdsShop
//        if ($firstCateg === '' && in_array($caminho, ['categAnterior', 'subcat'])) {
        if ($firstCateg === '' && in_array($caminho, ['categAnterior'])) {
            $firstCateg = $nomUC;
            $keyNro = $key;
        }

        if ($key < 3 && in_array($caminho, ['categAnterior', 'subcat', 'categ'])) {
            $buscaIdsShop[] = ['id' => $idCat_s, 'nomCat' => $nomCat];
        }

        // Monta os links
        $link = match(true) {
            in_array($caminho, ['categAnterior', 'subcat', 'categ']) =>
                sprintf(
                    '<a href="%s%s_br/Loja-de-%s/%s" class="subcat-bot" title="%s | Loja do Som"><b>%s</b></a>',
                    $shopUrl, $idCat_s, $nomSlug, $amp, $nomUC, $nomUC
                ),
            $caminho === 'similares' =>
                sprintf(
                    '<a href="%s%s/" target="_self" title="%s | Loja do Som" class="subbotoes btn-blue"><b>%s</b></a>',
                    $similUrl, $nomDash, $nomCat, $nomCat
                ),
            $caminho === 'especiais' && $isShop =>
                sprintf(
                    '<a href="%s%s/" target="_self" title="%s | Loja do Som" class="subbotoes btn-blue"><b>%s</b></a>',
                    $especUrl, $nomDash, $nomCat, $nomCat
                ),
            default => null
        };

        if (!$link) continue;

        // Define limites e bgcolor por tipo
        $limite = ($caminho === 'similares') ? 25 : 15;
        $bg     = $bgColors[$caminho] ?? '#79B7EA';

        $dentroDoMenu = ($key < $limite);

        // Similares em página shopping vai sempre para relacionados
        if ($caminho === 'similares' && $isShop) {
            $relacionados .= $link;
            continue;
        }

        // Especiais em shopping vai para relacionados
        if ($caminho === 'especiais' && $isShop) {
            $relacionados .= $link;
            continue;
        }

        if ($dentroDoMenu) {
            $wordsMenu .= sprintf(
                '<td width="50%%" bgcolor="%s" class="subbotc">%s</td>',
                $bg, $link
            );

            // Primeira categoria
            if ($caminho === 'categ') {
                if (!$primeiraCategoria) {
                    $primeiraCategoria = $nomUC;
                    $primeiraCatId = $idCat_s;
                }
                if (!$categAnterior) {
                    $categAnterior = $nomUC;
                    $idCatAnterior = $idCat_s;
                }
            }
        } else {
            $relacionados .= $link;
        }

        // Controle de colunas (2 por linha)
        $cols++;
        if ($cols > 1) {
            $cols = 0;
            $wordsMenu .= '</tr><tr>';
        }

        // Atualiza categAnterior
        if ($caminho !== 'similares') {
            if ($idCat != $idCat_s) {
                $categAnterior = $nomCat;
                $idCatAnterior = $idCat_s;
            } else {
                $primeiraCategoria = $categAnterior;
                $primeiraCatId     = $idCatAnterior;
            }
        }
    }
    return [
        'wordsMenu'     => $wordsMenu,
        'relacionados'  => $relacionados,
        'firstCateg'       => $firstCateg,
        'idsShop' => $buscaIdsShop
    ];
}
function limparCod($cod) {
    return Script::tiraAcento(urldecode(trim(preg_replace('/[?#].*$/', '', $cod), '/')));
}
/*
$actual_link = $_SERVER['REQUEST_URI'];
if (strpos($actual_link, '?') && !strpos($actual_link, 'musica-cd')) {
    $nurl = '/' . implode('/', array_slice(explode('/', trim(parse_url($actual_link, PHP_URL_PATH), '/')), 0, 2)) . '/';
    $location = "https://www.lojadosom.com.br{$nurl}";
    header('Location: ' . $location);
    exit;
}
*/




// ─── Variaveis ─────────────────────────────────────────────────────────────────────────────────────────────
 
$scripts = new Scripts();
$scripts->starttime();

$diasDeCache = 14;
$criadoEm = date('Ymd', strtotime('-14 days'));
$path = isset($_GET['path']) ? $_GET['path'] : 'similares';
$pathCache = CACHE_PATH . "/vendas/{$path}/";
$qcod = $_GET['cod'] ?? null; // Use null se não existir
$formato = isset($_GET['formato']) ? $_GET['formato'] : '';
$amp = ($formato == 'amp') ? 'amp' : '';

$pagesProibidas = array('absolut', 'hinode', 'ropahrara', 'vans');
$vendProibidos  = array('220115213', '0000', '1930800100');
$blockAdsense = false;

$hoje = date("dmY");
$dia = (int)substr($hoje, 0, 2);
$diavar = (int)substr($hoje, 1, 1);
$temCache = 'N';

$totalDiaSemana = 39; // começou dia 27/01/24 antes era 31

if (in_array($diavar, [3, 6, 9], true)) {
    $totalDiaSemana = 38;
} elseif (in_array($diavar, [7, 8], true)) {
    $totalDiaSemana = 40;
} elseif (in_array($diavar, [0, 1, 4, 5], true)) {
    $totalDiaSemana = 43;
}

$urlOrig = $_SERVER['REQUEST_URI'];
$wordSearch = $_GET['cod'] ??  null;
$urlGet = $wordSearch;
$wordSearch = limparCod($wordSearch);
//$wordSearch =  Shopping::tiraAcento(urldecode($wordSearch));//str_replace(['-#a', '-#b'], '', $wordSearch);
$wordSearch = mb_strtolower($wordSearch);
$wordSearch = trim( str_replace(['_', '/', '-'], ' ', $wordSearch ?? ''));
$nroMinKeys = (count(explode(' ', $wordSearch)) > 5) ? 2 : 1;
$urlSlug  = trim(preg_replace("/ /", "-", $wordSearch));

$canonical =  ($wordSearch == 'mais vendidos') ? 'https://www.lojadosom.com.br/shopping' :  "https://www.lojadosom.com.br/similares/" . urlencode($urlSlug);
 
$arqCache = strtolower(Scripts::tiraAcento($wordSearch, true));

//$cachePathFile = "{$pathCache}{$arqCache}.txt";
$cachePathFile = "{$pathCache}{$urlSlug}.txt";
//echo "$cachePathFile <BR>";

$products   = null;
$temCache   = 'N';
$criadoEm   = null;
$criaArqJson = null;
$dataCriacao = null;
$textoBusca = null;
$publyFindDesk = '';
$publyFindMob = '';

if (is_file($cachePathFile) && is_readable($cachePathFile)) {

    $content = file_get_contents($cachePathFile);

    // ─── Exibe publicidade Site Giovanna ───────────────────────────────────────
        $publyFind = false;
        if($content){
            $searchTerms = ['consultorio', 'gineco'];
            foreach ($searchTerms as $term) {
                $pos = strpos($content, $term);
                if ($pos !== false) {
                    
                        $publyFindMob = '<article><div class="publicidadeDir" style="background-repeat: no-repeat;background-color: #aae1f5;padding:3px;padding-top: 10px;padding-bottom: 10px;background-size: 100%;">
                            <div class="jumbotron" style="margin-top:0px;background-color: rgba(244, 242, 236, 0.65);padding: 11px;line-height: 110%;">
                                <b>Ginecologista e Obstetrícia</b>
                                <span style="font-color:green;position: absolute;margin-left:73px;"></span><br><br>
                                <p>Saúde da Mulher</p>
                                <p> Cuidado da adolescência à menopausa.</p>
                                <p>Acompanhamento desde o pré-natal até o parto.</p><p></p><p>Grande experiência.</p>
                                <p>Atendimento personalizado</p><br>
                                <p><a class="btn-desl" href="https://www.perovanoginecologia.com.br/" role="button" style="width:90%;margin-left: 4%;text-align:center">Saiba mais</a></p>
                            </div>
                        </div></article><br />';
                    
                    $publyFindDesk = '<article><div class="publicidadeDir" style="background-image: url(/design/happy.gif);padding:3px;padding-top: 10px;    padding-bottom: 10px;">
                            <div class="jumbotron" style="margin-top:0px;background-color: rgba(244, 242, 236, 0.65);padding:1px;line-height: 110%;">
                                    <b>Ginecologista e Obstetrícia</b>
                                    <span style="font-color:green;position: absolute;margin-left:73px;"></span><br><br>
                                    <p>Saúde da Mulher</p>
                                    <p> Cuidado da adolescência à menopausa.</p>
                                    <p>Acompanhamento desde o pré-natal até o parto.</p><p></p><p>Grande experiência</b></p>
                                    <p>Atendimento personalizado</p><br>
                                    <p><a class="btn-desl" href="https://www.perovanoginecologia.com.br/" role="button" style="width:90%;margin-left: 4%;text-align:center">Saiba mais</a></p>
                                </div>
                            </div></article><br />';
                    break; // Para no primeiro encontrado
                }
            }
        } 
    // ─── Exibe publicidade Site Giovanna ───────────────────────────────────────

    if ($content !== false && $content !== '') {

        $decoded = json_decode($content, true);

        if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {

            $products = $decoded;
            $temCache = 'S';

            // 🔹 valida estrutura antes de acessar
            if (!empty($products[0]['criadoEm'])) {

                $criadoEm = $products[0]['criadoEm'];

                $dataCriacao = strtotime($criadoEm);
                $agora       = time();

                if ($dataCriacao !== false) {

                    $difDias = (int)(($agora - $dataCriacao) / 86400);

                    if ($difDias > $diasDeCache ) {

                        $criaArqJson = CACHE_PATH . DIRECTORY_SEPARATOR .
                            "vendas" . DIRECTORY_SEPARATOR .
                            "atualiza" . DIRECTORY_SEPARATOR .
                            "atualizarSimilares.txt";

                        // Scripts::saveCriaCache($criaArqJson, $arqCache, $path);
                    }
                }
            }
        }
    }
}else{
   
  $products = null;
  criaLogs($cachePathFile, $scripts->displaytime(), 0, 0, 'N', date('Ymd'), $urlGet, 'Erro-');

}
$shopping =  new Shopping();
$textoBusca = (implode(' ', Scripts::extrairPalavras($wordSearch)))?? null;
    //echo "<pre>$textoBusca\n</pre>";

if (!$products) {
   
    // ─── Vou fazer pesquisa no Bando de Dados V_produtos ───────────────────────────────────────
    
    

    //Scripts::limpaNome(Scripts::tiraAcento($wordSearch));
    //$products = $shopping->getProds($nomespec, $vendProibidos, 'words');

}


$pagina = $products[0] ?? null;
$produtos = $pagina['produtos'] ?? [];
$nomePage = $pagina['nomePG'] ?? 'Sem nome';
$subMenu = '';

$desvio = intval($pagina['DesvioPadrao'] ?? 0);
$media = floatval($pagina['valorMedio'] ?? 0);

// Prevenção contra divisão por zero
$variacao = ($media > 0 && $desvio > 0) ? ($desvio / $media) : 0;

$precoMedio = match(true) {
    $media <= 0 => " a consultar",
    $desvio == 0 || $variacao > 0.5 => ' médio de R$ ' . Scripts::formatarMoeda($media),
    default => "de R$ " . Scripts::formatarMoeda(max(0, $media - $desvio)) . 
               ' até R$ ' . Scripts::formatarMoeda($media + $desvio)
};

$qtos = ($pagina['subCategorias']) ? count($pagina['subCategorias']) : 0;
$categoriasFiltradas = [];
//print_r($pagina['subCategorias']);
if($pagina['subCategorias']){
    $categoriasFiltradas = Shopping::filtrarTaxonomia($pagina['subCategorias'], [
        'limite' => 6,
        'genericos' => ['produto','original','novo','completo'],
        'similaridade_limite' => 85
    ]);
   $subMenu = criaSubmenuHtml($categoriasFiltradas, $path, $amp);
}

$buscaIdsShop = $subMenu['idsShop'];
$idsRelacionados = '';
$caminho = CACHE_PATH."/vendas/shopping/";
//
if ($buscaIdsShop) {
  $TT = (count($buscaIdsShop) == 1) ? 4 : 1;
  foreach ($buscaIdsShop as $Nvalue) {
    $fileCache = file_get_contents($caminho . $Nvalue['id'] . '.txt');
    if ($fileCache) {
      $idsRelacionados .= "<div class='relaCat'>\n<h3>{$Nvalue['nomCat']}</h3>";
      $catProducts = json_decode($fileCache, true);
      foreach ($catProducts[0]['produtos'] as $k => $value) {
        if ($formato == 'amp') {
          $idsRelacionados .= "<span class='blocoItens'> \n
                                 <span class='titleCat'><strong>" . substr($value['title'], 0, 40) . "</strong></span> \n
                                 <a href='https://www.lojadosom.com.br/shopping/comprar-{$Nvalue['id']}_br/Loja-de-" . urlencode(Scripts::tiraAcento($Nvalue['nomCat'], true)) . "/' title='{$Nvalue['nomCat']} - " . substr($value['title'], 0, 40) . "' class='menuL'>
                                <amp-img src='{$value['photo']}' width='60' height='60' alt='{$value['title']}'></amp-img>
                                 " . substr($value['title'], 0, 110) . " \n
                                <b style='text-decoration:none; color:darkred; text-align:right; float:right;padding: 3px;'><br>Preço R$ {$value['price']}<br>Comprar</b>
                                </a>
                              </span>  \n";
        } else {
          $idsRelacionados .= "<span class='blocoItens'> \n
                              <span class='titleCat'><strong>" . substr($value['title'], 0, 40) . "</strong></span> \n
                                 <a href='https://www.lojadosom.com.br/shopping/comprar-{$Nvalue['id']}_br/Loja-de-" . urlencode(Scripts::tiraAcento($Nvalue['nomCat'], true)) . "/' title='{$Nvalue['nomCat']} - " . substr($value['title'], 0, 40) . "' class='menuL'>
                                <img src='{$value['photo']}' width='60' height='60' alt='{$value['title']}' loading='lazy'>
                                 " . substr($value['title'], 0, 110) . " \n
                                <b style='text-decoration:none; color:darkred; text-align:right; float:right;padding: 3px;'><br>Preço R$ {$value['price']}<br>Comprar</b>
                                </a></span>  \n";
        }
        if ($k > $TT)  break;
      }
      $idsRelacionados .= "</div>";
    }
  }
}

//$relacionados = ($relacionados) ? $idsRelacionados . "<h3>Links Semelhantes</h3>" . $relacionados : "<br>" . $idsRelacionados;

/*
echo '<pre>';
echo json_encode($pagina, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
echo '</pre>';
*/
/*
echo "<BR><BR>";
print_r($categoriasFiltradas);
echo "<BR><BR>";
*/
//print_r($pagina['produtos']);
//echo "<BR><BR>";
$prices = array_column($produtos, 'price');

$avg = array_sum($prices) / count($prices);

// desvio padrão
$variance = array_sum(array_map(fn($p) => pow($p - $avg, 2), $prices)) / count($prices);
$std = sqrt($variance);
//$newProdutos = Shopping::rankProdutos($produtos, $textoBusca, $avg, $std);
$stats = Shopping::getPriceStatsFromArray(
    $produtos,
    $nomePage,
    0.75
);

/*

echo "<BR><BR>$std =========== $avg <BR><BR>";
//print_r($newProdutos);
echo "<BR><BR>";
print_r($stats);

echo "<BR><BR><BR><BR>";

*/
 // ─── Cria lista de produtos ────────────────────────────────────────────
$result = Shopping::process($produtos, $textoBusca, false); // true = debug

$titlesAll= [];
$quadrinhos = '';
$refazer = false;
$nroAncora = 0;
foreach ($result['products'] as  $value) {
    $titlesAll[] = $value['title'];
     if ($nroAncora < 11) {
      $nroAncora++;
      $title = $value['title'];
      
      if (trim($title) == '') {
        $descPhoto = $value['photo'];
        $ini = strstr($descPhoto, 'imageshop');
        $ini = str_replace('imageshop/', '', $ini);
        $descTitle = strstr($ini, '-sls-', true);
        $descTitle = preg_replace('/-/', ' ', $descTitle);
        $title = $descTitle;
      }
      $photoT = str_replace("-O.jpg", "-T.jpg", $value['photo']);

      $photoT = str_replace("http:", "https:", $photoT);
      if (!preg_match("/.jpg/i", $photoT)) {
        if (!preg_match("/.png/i", $photoT)) {
          $photoT = $photoT . ".jpg";
        }
      }
      $primLetra = substr(strtolower($title), 0, 1);
      if ($primLetra > 'g') {
        $photoT = str_replace("pix.", "img.", $photoT);
      } else {
        $photoT = str_replace("img.", "pix.", $photoT);
      }

      $ancora = explode(' ', $title);
      $quadrinhos .= '
      <a href="#'.$value['nroPhoto'].'" title="' . $title . '">
      <img  src="' . $photoT . '" width="49" height="49" alt="' . $title . '" loading="eager"/></a>';
   
    }
    
}
$titlesAll = Shopping::processTituloImg($titlesAll);
$listProdutos = Shopping::getHtmlProdutos( $result, $titlesAll, $totalDiaSemana,  $nroMinKeys);
//print_r($listProdutos);
/*
//────────────────────────────────────────────────────────────────────────


echo "<pre>$textoBusca\n</pre>";
foreach ($result['products'] as  $value) {
    echo $value['title'].'<BR>';
}
echo "<BR><BR><BR>";
//print_r($result);
*/
//echo $totalDiaSemana." ==== ".$nroMinKeys."<BR>";
//echo '<pre>';
//echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
//echo '</pre>';

$confidence = $result['confidence'];
if ($confidence >= 0.75) {
    $robots = 'index,follow';

} elseif ($confidence >= 0.45) {
    $robots = 'index,follow';

} elseif ($confidence >= 0.25) {
    $robots = 'noindex,follow';

} else {
    $robots = 'noindex,nofollow';
}
$descPrecos = '';
$priceInsight = $result['price_insight'] ?? null;
if ($priceInsight) {

    if ($priceInsight['type'] === 'range') {
        $descPrecos = " na faixa de preço: R$ {$priceInsight['min']} a R$ {$priceInsight['max']}";
    } else {
        $descPrecos = "com preço médio: R$ {$priceInsight['value']}";
    }

}else{
    $descPrecos = "com preço médio a consultar";
}

$title = '';
$firstCateg = $subMenu['firstCateg'] ?? '';
$txtFinal = ' | Loja do Som - Shopping, Música, Vídeos e Letras online';

if ($firstCateg) {
    $title .= sprintf("%s   >   %s%s", ucwords($textoBusca), ucwords($firstCateg), $txtFinal);
} else {
    $title .= sprintf("%s   >   %s",ucwords($wordSearch), $txtFinal);
}
$produto = $result['products'] ?? null; 
$nroProds = count($produto);
$photo = '';
$metaKey = '';
$qMarcas = '';
$procura = '';
if ($produto) {
    $photo = str_replace("-O.jpg", "-T.jpg", $produto[0]['photo']);
    $primeiraLetra = strtolower(substr($produto[0]['title'], 0, 1));
    
    $de = $primeiraLetra > 'g' ? "pix." : "img.";
    $para = $primeiraLetra > 'g' ? "img." : "pix.";
//    echo $photo." ".$produto[0]['title'];
    $photo = str_replace([$de, "http:"], [$para, "https:"], $photo);
//    print_r($produto);
    $metaK = $pagina['metaKeys'];
    $qMarcas = preg_replace('/ /', ', ', 
    preg_replace('/\s+/', ' ', 
        Shopping::retiraPreposicoes(pegaMarcasProdutos($produto))
                )
    );
    $qMarcas = preg_replace('/,,/', ',', $qMarcas);

//────────────────────────────────────────────────────────────────────────
    $pageTitle = Scripts::pluraltosingular(Scripts::tiraAcento(strtolower(preg_replace('/\\s\\s+/', ' ', $nomePage))));
    $anunTitle = Scripts::pluraltosingular(Scripts::tiraAcento(strtolower(preg_replace('/\\s\\s+/', ' ', $produto[0]['title']))));
    $firstWord = explode(' ', $pageTitle);
    $firstAnunc = explode(' ', $anunTitle);
    similar_text($firstWord[0], $firstAnunc[0], $parecidos);
    if ($parecidos > 85) {
  
      if (!$procura) {
        $procura = "{$firstAnunc[0]} {$firstAnunc[1]} {$firstAnunc[2]} {$firstAnunc[3]}";
      }
    }
    $procura = ($procura) ? $procura : $wordSearch;
    $procura = "Procura por {$procura}? Encontre aqui {$descPrecos}.";
    $procura = ($confidence < 0.25) ? 'Resultados aproximados para sua busca.': $procura;
    
//────────────────────────────────────────────────────────────────────────
} else {
    error_log("Produto não encontrado");
}
$robots = ($result['stats']['count'] < 5 ) ? 'noindex,nofollow' : $robots;

$keysTitle = str_replace(' ', ', ', ucwords($wordSearch));
$metaDesc = "{$wordSearch} {$descPrecos} | {$firstCateg} - Comprar e Vender no Shopping Loja do Som.";
$titleFinal = ($firstCateg)? "{$firstCateg} > {$wordSearch} {$descPrecos}." : "{$wordSearch} {$descPrecos}";

$metaKey = "{$keysTitle} , ".str_replace(' ', ', ', ucwords($firstCateg ?? ''))." , {$metaK} {$qMarcas} Comprar, Vender, Leilão, Oferta, compra, venda, baixo, lançamentos";
$h1Title =  substr($wordSearch, 0, 40);

//────────────────────────────────────────────────────────────────────────  Lista de bandas

mt_srand((int) date('Ymd'));
$index = mt_rand(0, 199);
$file  = CACHE_PATH . "/bandasJson/{$index}MaisTocadas.json";

if (!is_file($file)) {
    $lnkBandas = '</div></aside><br />';
    return; // ou log + fallback conforme o contexto
}

$bds = json_decode(file_get_contents($file), true);

if (!is_array($bds) || $bds === []) {
    $lnkBandas = '</div></aside><br />';
    return;
}

$links = array_map(static function (array $value): string {
    $url   = htmlspecialchars($value['urlband'] ?? '', ENT_QUOTES, 'UTF-8');
    $label = htmlspecialchars($value['bandas']  ?? '', ENT_QUOTES, 'UTF-8');
    return "<a href=\"https://www.lojadosom.com.br/{$url}/\" target=\"lstMusics\">{$label}</a>";
}, $bds);

$lnkBandas = implode('', $links) . '</div></aside><br />';

//────────────────────────────────────────────────────────────────────────
if (Scripts::isMobile()) {
    require_once(BASE_PATH."/vendas/views/views-similares-mobile.php" );
}else{
    require_once(BASE_PATH."/vendas/views/views-similares-desktop.php" );
}


//────────────────────────────────────────────────────────────────────────
$vendA = array_filter($pagina['produtos'], function ($var) {
  return ($var['vendedor'] == 'amazon');
});
$vendS = array_filter($pagina['produtos'], function ($var) {
  return ($var['vendedor'] == 'shopee');
});
//$perc = intval((count($pontos) / count($pagina['produtos'])) * 100);
if (isset($pagina['produtos']) && is_array($pagina['produtos'])) {
    $totalProdutos = count($pagina['produtos']);
    $perc = 0;//($totalProdutos > 0) ? intval((count($pontos) / $totalProdutos) * 100) : 0;
} else {
    $perc = 0;
}
$qtotal = "A:" . count($vendA) . "|S:" . count($vendS) . "|T:" . count($pagina['produtos']) . "|P0:" . $perc;
//if($criaStats){
criaLogs($arqCache, $scripts->displaytime(), $qtotal, $qtos, $temCache, $criadoEm, $urlOrig);
echo "<!-- " . $scripts->displaytime() . " seconds to execute -->\n";
ob_end_flush();
