<?php

ob_start();
require_once __DIR__ . '/backend/config.php';
require_once __DIR__ . '/backend/helpers.php';
ob_clean();

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

$https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['SERVER_PORT'] ?? 80) == 443);
$protocol = $https ? 'https://' : 'http://';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$scriptName = $_SERVER['SCRIPT_NAME'] ?? '/sitemap.php';
$basePath = trim(str_replace('\\', '/', dirname($scriptName)), '/');
$base = $protocol . $host . ($basePath !== '' && $basePath !== '.' ? '/' . $basePath : '') . '/';

$urls = [];
$addUrl = function (string $loc, ?string $lastmod = null, string $changefreq = 'weekly', string $priority = '0.8') use (&$urls): void {
    $urls[] = [
        'loc' => $loc,
        'lastmod' => $lastmod ?: date('Y-m-d'),
        'changefreq' => $changefreq,
        'priority' => $priority,
    ];
};

$addUrl($base, date('Y-m-d'), 'daily', '1.0');
$addUrl($base . 'services/', date('Y-m-d'), 'weekly', '0.9');
$addUrl($base . 'service-combinations/', date('Y-m-d'), 'weekly', '0.8');

$serviceRows = getActiveServices($pdo);
$serviceCategoryRows = getActiveServiceCategories($pdo);
$cityRowsStmt = $pdo->query("
    SELECT name, slug, state_name, state_slug, display_name, featured, sort_order, updated_at
    FROM cities
    WHERE status = 'active'
    ORDER BY featured DESC, sort_order ASC, name ASC
");
$cityRows = $cityRowsStmt ? $cityRowsStmt->fetchAll(PDO::FETCH_ASSOC) : [];

foreach ($serviceRows as $service) {
    $serviceSlug = trim((string)($service['slug'] ?? ''));
    if ($serviceSlug === '') {
        continue;
    }
    $addUrl($base . $serviceSlug . '/', date('Y-m-d', strtotime($service['updated_at'] ?? 'now')), 'weekly', '0.9');
}

foreach ($cityRows as $city) {
    $citySlug = trim((string)($city['slug'] ?? ''));
    $stateSlug = trim((string)($city['state_slug'] ?? ''));

    if ($citySlug === '') {
        continue;
    }

    foreach ($serviceRows as $service) {
        $serviceSlug = trim((string)($service['slug'] ?? ''));
        if ($serviceSlug === '') {
            continue;
        }
        $addUrl($base . $citySlug . '/' . $serviceSlug . '/', date('Y-m-d', strtotime($city['updated_at'] ?? 'now')), 'weekly', '0.7');
    }

    if ($stateSlug !== '') {
        foreach ($serviceRows as $service) {
            $serviceSlug = trim((string)($service['slug'] ?? ''));
            if ($serviceSlug === '') {
                continue;
            }
            $addUrl($base . $stateSlug . '/' . $serviceSlug . '/', date('Y-m-d', strtotime($city['updated_at'] ?? 'now')), 'weekly', '0.6');
        }
    }
}

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

foreach ($urls as $url) {
    echo "  <url>\n";
    echo '    <loc>' . htmlspecialchars($url['loc'], ENT_XML1) . "</loc>\n";
    echo '    <lastmod>' . htmlspecialchars($url['lastmod'], ENT_XML1) . "</lastmod>\n";
    echo '    <changefreq>' . htmlspecialchars($url['changefreq'], ENT_XML1) . "</changefreq>\n";
    echo '    <priority>' . htmlspecialchars($url['priority'], ENT_XML1) . "</priority>\n";
    echo "  </url>\n";
}

echo "</urlset>\n";
