<?php
header('Content-Type: application/xml; charset=utf-8');
header('X-Robots-Tag: noindex');

$cacheFile = sys_get_temp_dir() . '/101variant_sitemap_v2.xml';
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < 3600) {
    readfile($cacheFile);
    exit;
}

$env = [];
foreach (file(__DIR__ . '/../.env') as $line) {
    $line = trim($line);
    if (!$line || str_starts_with($line, '#') || !str_contains($line, '=')) continue;
    [$k, $v] = explode('=', $line, 2);
    $env[trim($k)] = trim($v, " \"'");
}
$pdo = new PDO(
    "mysql:host={$env['DB_HOST']};port={$env['DB_PORT']};dbname={$env['DB_DATABASE']};charset=utf8mb4",
    $env['DB_USERNAME'], $env['DB_PASSWORD'],
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

$base = 'https://101variant.ru';
$now  = date('Y-m-d');

$urls = [];

// Статические страницы
$urls[] = ['loc' => $base . '/catalog',           'priority' => '1.0', 'changefreq' => 'daily'];
$urls[] = ['loc' => $base . '/catalog/suppliers', 'priority' => '0.8', 'changefreq' => 'weekly'];

// Категории
$cats = $pdo->query("SELECT slug, updated_at FROM catalog_categories WHERE is_active=1 ORDER BY parent_id, sort_order")->fetchAll(PDO::FETCH_ASSOC);
foreach ($cats as $c) {
    $urls[] = [
        'loc'        => $base . '/catalog/category/' . $c['slug'],
        'lastmod'    => isset($c['updated_at']) ? substr($c['updated_at'], 0, 10) : $now,
        'priority'   => '0.8',
        'changefreq' => 'weekly',
    ];
}

// Товары (порциями по 500)
$stmt = $pdo->query("SELECT slug, updated_at FROM catalog_products WHERE is_active=1 ORDER BY id");
while ($p = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $urls[] = [
        'loc'        => $base . '/catalog/product/' . $p['slug'],
        'lastmod'    => isset($p['updated_at']) ? substr($p['updated_at'], 0, 10) : $now,
        'priority'   => '0.6',
        'changefreq' => 'monthly',
    ];
}

// Генерируем XML
$xml  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"' . "\n";
$xml .= '        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' . "\n";
$xml .= '        xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">' . "\n";

foreach ($urls as $u) {
    $xml .= "  <url>\n";
    $xml .= "    <loc>" . htmlspecialchars($u['loc']) . "</loc>\n";
    if (!empty($u['lastmod']))    $xml .= "    <lastmod>{$u['lastmod']}</lastmod>\n";
    if (!empty($u['changefreq'])) $xml .= "    <changefreq>{$u['changefreq']}</changefreq>\n";
    if (!empty($u['priority']))   $xml .= "    <priority>{$u['priority']}</priority>\n";
    $xml .= "  </url>\n";
}

$xml .= '</urlset>';

file_put_contents($cacheFile, $xml);
echo $xml;
