<?php
declare(strict_types=1);

if (realpath((string) ($_SERVER['SCRIPT_FILENAME'] ?? '')) === __FILE__) {
    header('X-Robots-Tag: noindex, nofollow', true);
    http_response_code(404);
    exit;
}

function xml(string $value): string
{
    return htmlspecialchars($value, ENT_XML1 | ENT_QUOTES, 'UTF-8');
}

function sitemap_header(): void
{
    header('Content-Type: application/xml; charset=utf-8');
    header('Cache-Control: public, max-age=1800');
    header('X-Content-Type-Options: nosniff');
}

function sitemap_date(?string $value): ?string
{
    if (!$value) return null;
    $ts = strtotime($value);
    return $ts === false ? null : date(DATE_ATOM, $ts);
}

function sitemap_scalar(string $sql): ?string
{
    $value = db()->query($sql)->fetchColumn();
    return sitemap_date(is_string($value) ? $value : null);
}

function sitemap_map_lastmod(string $map): ?string
{
    $sql = match ($map) {
        'services' => "SELECT MAX(updated_at) FROM services WHERE is_active=1",
        'posts' => "SELECT MAX(updated_at) FROM posts WHERE status='published'",
        'images' => "SELECT GREATEST(
            COALESCE((SELECT MAX(updated_at) FROM services WHERE is_active=1),'1970-01-01'),
            COALESCE((SELECT MAX(updated_at) FROM posts WHERE status='published'),'1970-01-01'),
            COALESCE((SELECT MAX(updated_at) FROM gallery_items WHERE is_active=1),'1970-01-01')
        )",
        default => "SELECT GREATEST(
            COALESCE((SELECT MAX(updated_at) FROM pages WHERE status='published'),'1970-01-01'),
            COALESCE((SELECT MAX(updated_at) FROM gallery_items WHERE is_active=1),'1970-01-01'),
            COALESCE((SELECT MAX(updated_at) FROM settings WHERE setting_key NOT LIKE 'gemini_api_%' AND setting_key<>'gemini_api_key'),'1970-01-01')
        )",
    };
    $date = sitemap_scalar($sql);
    return $date && !str_starts_with($date, '1970-') ? $date : null;
}

function sitemap_static_lastmods(): array
{
    $home = sitemap_scalar("SELECT GREATEST(
        COALESCE((SELECT MAX(updated_at) FROM services WHERE is_active=1),'1970-01-01'),
        COALESCE((SELECT MAX(updated_at) FROM therapists WHERE is_active=1),'1970-01-01'),
        COALESCE((SELECT MAX(updated_at) FROM posts WHERE status='published'),'1970-01-01'),
        COALESCE((SELECT MAX(updated_at) FROM gallery_items WHERE is_active=1),'1970-01-01'),
        COALESCE((SELECT MAX(updated_at) FROM settings WHERE setting_key NOT LIKE 'gemini_api_%' AND setting_key<>'gemini_api_key'),'1970-01-01')
    )");
    return [
        '/' => $home,
        '/hizmetler' => sitemap_scalar("SELECT MAX(updated_at) FROM services WHERE is_active=1"),
        '/wellness-rehberi' => sitemap_scalar("SELECT MAX(updated_at) FROM posts WHERE status='published'"),
        '/galeri' => sitemap_scalar("SELECT MAX(updated_at) FROM gallery_items WHERE is_active=1"),
    ];
}

function sitemap_url_entry(string $loc, ?string $lastmod = null): string
{
    $entry = '<url><loc>' . xml($loc) . '</loc>';
    if ($lastmod) $entry .= '<lastmod>' . xml($lastmod) . '</lastmod>';
    return $entry . '</url>';
}

function render_sitemap(string $type): void
{
    sitemap_header();

    if ($type === 'index') {
        echo '<?xml version="1.0" encoding="UTF-8"?>';
        echo '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
        foreach (['pages', 'services', 'posts', 'images'] as $map) {
            echo '<sitemap><loc>' . xml(url('/sitemap-' . $map . '.xml')) . '</loc>';
            if ($lastmod = sitemap_map_lastmod($map)) echo '<lastmod>' . xml($lastmod) . '</lastmod>';
            echo '</sitemap>';
        }
        echo '</sitemapindex>';
        return;
    }

    if ($type === 'images') {
        echo '<?xml version="1.0" encoding="UTF-8"?>';
        echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">';

        foreach (db()->query("SELECT slug,name,cover_image FROM services WHERE is_active=1 AND cover_image IS NOT NULL AND cover_image<>'' ORDER BY id")->fetchAll() as $row) {
            echo '<url><loc>' . xml(url('/hizmet/' . $row['slug'])) . '</loc><image:image><image:loc>' . xml(url($row['cover_image'])) . '</image:loc><image:title>' . xml($row['name']) . '</image:title></image:image></url>';
        }

        $gallery = db()->query("SELECT title,image_path,alt_text FROM gallery_items WHERE is_active=1 AND image_path<>'' ORDER BY sort_order,id")->fetchAll();
        if ($gallery) {
            echo '<url><loc>' . xml(url('/galeri')) . '</loc>';
            foreach ($gallery as $row) {
                echo '<image:image><image:loc>' . xml(url($row['image_path'])) . '</image:loc><image:title>' . xml($row['title']) . '</image:title><image:caption>' . xml($row['alt_text'] ?: $row['title']) . '</image:caption></image:image>';
            }
            echo '</url>';
        }

        foreach (db()->query("SELECT slug,title,cover_image FROM posts WHERE status='published' AND cover_image IS NOT NULL AND cover_image<>'' ORDER BY id")->fetchAll() as $row) {
            echo '<url><loc>' . xml(url('/makale/' . $row['slug'])) . '</loc><image:image><image:loc>' . xml(url($row['cover_image'])) . '</image:loc><image:title>' . xml($row['title']) . '</image:title></image:image></url>';
        }
        echo '</urlset>';
        return;
    }

    $urls = [];
    if ($type === 'pages') {
        foreach (sitemap_static_lastmods() as $path => $lastmod) {
            $urls[] = ['loc' => url($path), 'lastmod' => $lastmod];
        }
        foreach (db()->query("SELECT slug,updated_at FROM pages WHERE status='published' ORDER BY id")->fetchAll() as $row) {
            $urls[] = ['loc' => url('/kurumsal/' . $row['slug']), 'lastmod' => sitemap_date($row['updated_at'])];
        }
    } elseif ($type === 'services') {
        foreach (db()->query('SELECT slug,updated_at FROM services WHERE is_active=1 ORDER BY id')->fetchAll() as $row) {
            $urls[] = ['loc' => url('/hizmet/' . $row['slug']), 'lastmod' => sitemap_date($row['updated_at'])];
        }
    } elseif ($type === 'posts') {
        foreach (db()->query("SELECT slug,updated_at FROM posts WHERE status='published' ORDER BY id")->fetchAll() as $row) {
            $urls[] = ['loc' => url('/makale/' . $row['slug']), 'lastmod' => sitemap_date($row['updated_at'])];
        }
    } else {
        http_response_code(404);
        return;
    }

    echo '<?xml version="1.0" encoding="UTF-8"?>';
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    foreach ($urls as $item) echo sitemap_url_entry($item['loc'], $item['lastmod']);
    echo '</urlset>';
}
