<?php
// ============================================================================
// DOSYALINK.NET — OFFICIAL XML SITEMAP (sitemap.xml)
// ============================================================================

ob_start();

require_once __DIR__ . '/db.php';
if (file_exists(__DIR__ . '/config.php')) {
    require_once __DIR__ . '/config.php';
}

if (!function_exists('format_sitemap_date')) {
    function format_sitemap_date($date_str, $default_date) {
        if (empty($date_str) || $date_str === '0000-00-00 00:00:00' || $date_str === '0000-00-00') {
            return $default_date;
        }
        $ts = strtotime($date_str);
        return ($ts && $ts > 0) ? date('Y-m-d', $ts) : $default_date;
    }
}

if (!function_exists('clean_xml_string')) {
    function clean_xml_string($str) {
        if (empty($str)) return '';
        $str = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $str);
        return htmlspecialchars($str, ENT_XML1 | ENT_QUOTES, 'UTF-8');
    }
}

$base = 'https://dosyalink.net';
$today = date('Y-m-d');

$pdo = DB::getPDO();

$english_tools = [
    'hash-checker',
    'exif-viewer',
    'image-converter',
    'image-compressor',
    'pdf-text-extractor',
    'pdf-to-image',
    'image-to-pdf',
    'qr-code-generator',
    'base64-converter',
    'pdf-merger',
    'pdf-splitter',
    'pdf-page-remover',
    'zip-creator',
    'zip-extractor',
    'audio-trimmer',
    'video-trimmer',
    'ocr-text-extractor',
];

$blogs = [];
try {
    $stmt = $pdo->query("SELECT slug, slug_en, created_at FROM blogs ORDER BY created_at DESC");
    $blogs = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {}

if (ob_get_length()) {
    ob_clean();
}

if (!headers_sent()) {
    header('Content-Type: application/xml; charset=utf-8');
}

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

$static_pages = [
    ['url' => '/',                    'priority' => '1.0', 'freq' => 'daily'],
    ['url' => '/tools/',              'priority' => '0.9', 'freq' => 'weekly'],
    ['url' => '/blog/',               'priority' => '0.8', 'freq' => 'daily'],
    ['url' => '/report.php',          'priority' => '0.5', 'freq' => 'monthly'],
    ['url' => '/privacy-policy.php',  'priority' => '0.3', 'freq' => 'yearly'],
    ['url' => '/terms-of-use.php',    'priority' => '0.3', 'freq' => 'yearly'],
    ['url' => '/cookie-policy.php',   'priority' => '0.3', 'freq' => 'yearly'],
    ['url' => '/data-protection.php', 'priority' => '0.3', 'freq' => 'yearly'],
];

foreach ($static_pages as $p) {
    $clean_url = clean_xml_string($base . $p['url']);
    echo "    <url>\n";
    echo "        <loc>$clean_url</loc>\n";
    echo "        <lastmod>$today</lastmod>\n";
    echo "        <changefreq>{$p['freq']}</changefreq>\n";
    echo "        <priority>{$p['priority']}</priority>\n";
    echo "    </url>\n";
}

foreach ($english_tools as $slug) {
    $clean_url = clean_xml_string($base . '/tools/' . $slug);
    echo "    <url>\n";
    echo "        <loc>$clean_url</loc>\n";
    echo "        <lastmod>$today</lastmod>\n";
    echo "        <changefreq>monthly</changefreq>\n";
    echo "        <priority>0.7</priority>\n";
    echo "    </url>\n";
}

foreach ($blogs as $b) {
    $slug = !empty($b['slug_en']) ? $b['slug_en'] : $b['slug'];
    if (empty($slug)) continue;
    $lastmod = format_sitemap_date($b['created_at'] ?? '', $today);
    $clean_url = clean_xml_string($base . '/blog/' . $slug);

    echo "    <url>\n";
    echo "        <loc>$clean_url</loc>\n";
    echo "        <lastmod>$lastmod</lastmod>\n";
    echo "        <changefreq>monthly</changefreq>\n";
    echo "        <priority>0.6</priority>\n";
    echo "    </url>\n";
}

echo '</urlset>';

if (ob_get_level() > 0) {
    ob_end_flush();
}
