<?php
declare(strict_types=1);

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/config/database.php';

header('Content-Type: application/xml; charset=utf-8');

echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;

function printSitemapUrl(string $loc, string $freq = 'weekly', string $prio = '0.8', ?string $lastmod = null): void {
    // Rimuove eventuali slash finali per evitare redirect 301
    $cleanLoc = rtrim($loc, '/');
    if ($cleanLoc === 'https://riscaldamentoalegna.it') {
        $cleanLoc = 'https://riscaldamentoalegna.it/';
    }
    
    echo '  <url>' . PHP_EOL;
    echo '    <loc>' . htmlspecialchars($cleanLoc) . '</loc>' . PHP_EOL;
    if ($lastmod) {
        echo '    <lastmod>' . htmlspecialchars($lastmod) . '</lastmod>' . PHP_EOL;
    }
    echo '    <changefreq>' . $freq . '</changefreq>' . PHP_EOL;
    echo '    <priority>' . $prio . '</priority>' . PHP_EOL;
    echo '  </url>' . PHP_EOL;
}

$today = date('Y-m-d');
$baseUrl = 'https://riscaldamentoalegna.it';

// 1. Pagine Istituzionali Principali (Tutte rispondono 200 OK diretto)
printSitemapUrl($baseUrl . '/', 'daily', '1.0', $today);
printSitemapUrl($baseUrl . '/categoria', 'daily', '0.9', $today);
printSitemapUrl($baseUrl . '/conto-termico', 'weekly', '0.9', $today);
printSitemapUrl($baseUrl . '/guide', 'weekly', '0.8', $today);
printSitemapUrl($baseUrl . '/chi-siamo', 'monthly', '0.8', $today);
printSitemapUrl($baseUrl . '/condizioni-garanzia', 'monthly', '0.7', $today);
printSitemapUrl($baseUrl . '/contatti', 'monthly', '0.7', $today);
printSitemapUrl($baseUrl . '/privacy-policy', 'yearly', '0.3', $today);
printSitemapUrl($baseUrl . '/cookie-policy', 'yearly', '0.3', $today);

try {
    $pdo = AgrisubDB::getConnection();

    // 2. Categorie del Catalogo (URL puliti senza redirect)
    $categories = $pdo->query("SELECT DISTINCT category FROM products WHERE category IS NOT NULL AND category != ''")->fetchAll(PDO::FETCH_COLUMN);
    foreach ($categories as $cat) {
        $slugCat = strtolower(trim(preg_replace('/[^a-zA-Z0-9]+/', '-', (string)$cat), '-'));
        if (!empty($slugCat)) {
            printSitemapUrl($baseUrl . '/categoria/' . $slugCat, 'weekly', '0.85', $today);
        }
    }

    // 3. Tutti i Prodotti Singoli Attivi con Slug Valido
    $products = $pdo->query("SELECT slug, updated_at FROM products WHERE slug IS NOT NULL AND slug != '' ORDER BY id DESC")->fetchAll();
    foreach ($products as $p) {
        $slug = trim((string)$p['slug']);
        if (!empty($slug)) {
            $lastmod = !empty($p['updated_at']) ? date('Y-m-d', strtotime($p['updated_at'])) : $today;
            printSitemapUrl($baseUrl . '/prodotto/' . $slug, 'weekly', '0.8', $lastmod);
        }
    }

} catch (Throwable $e) {}

echo '</urlset>';