<?php
declare(strict_types=1);

require_once __DIR__ . '/admin/inc/baglan.php';

header('Content-Type: application/xml; charset=UTF-8');

if (!isset($db) || !($db instanceof PDO)) {
    http_response_code(500);
    exit;
}

$baseUrl = 'https://turkkanymm.com';

function tk_sitemap_date($value): string
{
    $time = strtotime((string)$value);
    return $time !== false ? date('Y-m-d', $time) : date('Y-m-d');
}

function tk_sitemap_url(string $loc, string $lastmod, string $changefreq = 'weekly', string $priority = '0.80'): void
{
    echo "    <url>\n";
    echo '        <loc>' . htmlspecialchars($loc, ENT_XML1, 'UTF-8') . "</loc>\n";
    echo '        <lastmod>' . htmlspecialchars($lastmod, ENT_XML1, 'UTF-8') . "</lastmod>\n";
    echo '        <changefreq>' . htmlspecialchars($changefreq, ENT_XML1, 'UTF-8') . "</changefreq>\n";
    echo '        <priority>' . htmlspecialchars($priority, ENT_XML1, 'UTF-8') . "</priority>\n";
    echo "    </url>\n";
}

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php
tk_sitemap_url($baseUrl . '/', date('Y-m-d'), 'daily', '1.00');

$staticUrls = [
    'hakkimizda' => '0.90',
    'vergi-hizmetleri' => '0.90',
    'vergi-rehberi' => '0.85',
    'ymm-vergi-soru-cevap' => '0.80',
    'iletisim' => '0.85',
];

foreach ($staticUrls as $slug => $priority) {
    tk_sitemap_url($baseUrl . '/' . $slug, date('Y-m-d'), 'weekly', $priority);
}

$tables = [
    'sayfalar' => ['priority' => '0.80'],
    'hizmetler' => ['priority' => '0.85'],
    'haberler' => ['priority' => '0.75'],
    'sss' => ['priority' => '0.70'],
];

foreach ($tables as $table => $meta) {
    try {
        $stmt = $db->query("SELECT seo, tarih FROM `{$table}` WHERE seo IS NOT NULL AND seo != '' ORDER BY id DESC");
        $rows = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];

        foreach ($rows as $row) {
            $slug = trim((string)($row['seo'] ?? ''), '/');

            if ($slug === '') {
                continue;
            }

            tk_sitemap_url(
                $baseUrl . '/' . rawurlencode($slug),
                tk_sitemap_date($row['tarih'] ?? ''),
                'weekly',
                $meta['priority']
            );
        }
    } catch (Throwable $e) {
        error_log('SITEMAP TABLO HATASI [' . $table . ']: ' . $e->getMessage());
    }
}
?>
</urlset>