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

define('ROOT_PATH', dirname(__DIR__));

spl_autoload_register(function ($class) {
    $class = ltrim($class, '\\');
    $relativePath = str_replace('\\', '/', $class) . '.php';
    $relativePath = str_replace(['Core/', 'System/', 'App/'], ['core/', 'system/', 'app/'], $relativePath);
    $file = ROOT_PATH . '/' . $relativePath;
    if (is_file($file)) {
        require_once $file;
    }
});

require_once ROOT_PATH . '/core/system/Env.php';
\Core\System\Env::bootstrap(ROOT_PATH);
$dbHelper = ROOT_PATH . '/core/app/Helpers/db.php';
if (is_file($dbHelper)) {
    require_once $dbHelper;
}

use Core\App\Models\AiLandingPage;
use Core\App\Models\CategoryModel;
use Core\App\Models\Page;
use Core\App\Models\ProductModel;

/**
 * Returns the trusted base URL, preferring APP_URL from .env
 * to prevent Host Header Injection in sitemap output.
 */
function sitemap_base(): string
{
    $appUrl = \Core\System\Env::get('APP_URL', '');
    if ($appUrl !== '') {
        return rtrim($appUrl, '/');
    }
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host   = $_SERVER['SERVER_NAME'] ?? ($_SERVER['HTTP_HOST'] ?? '');
    return rtrim($scheme . '://' . $host, '/');
}

function sitemap_url(string $path = ''): string
{
    return sitemap_base() . '/' . ltrim($path, '/');
}

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

$urls = [];
$urls[] = ['loc' => sitemap_url('/'), 'changefreq' => 'daily', 'priority' => '1.0'];
$urls[] = ['loc' => sitemap_url('/products'), 'changefreq' => 'daily', 'priority' => '0.9'];

try {
    foreach ((new Page())->getAllPublished() as $page) {
        if (empty($page['slug'])) {
            continue;
        }
        $urls[] = [
            'loc' => sitemap_url('/' . $page['slug']),
            'changefreq' => 'monthly',
            'priority' => '0.6',
            'lastmod' => !empty($page['updated_at']) ? date('Y-m-d', strtotime($page['updated_at'])) : null,
        ];
    }
} catch (Throwable $e) {
}

try {
    foreach ((new CategoryModel())->getActive() as $category) {
        if (empty($category['slug'])) {
            continue;
        }
        $urls[] = [
            'loc' => sitemap_url('/category/' . $category['slug']),
            'changefreq' => 'weekly',
            'priority' => '0.7',
            'lastmod' => !empty($category['updated_at']) ? date('Y-m-d', strtotime($category['updated_at'])) : null,
        ];
    }
} catch (Throwable $e) {
}

try {
    $productModel = new ProductModel();
    $batchSize    = 500;
    $offset       = 0;
    do {
        $batch = $productModel->getForSitemap($batchSize, $offset);
        foreach ($batch as $product) {
            if (empty($product['id'])) {
                continue;
            }
            $path = '/product/' . (!empty($product['slug']) ? $product['slug'] : (int)$product['id']);
            $entry = [
                'loc'        => sitemap_url($path),
                'changefreq' => 'weekly',
                'priority'   => '0.8',
                'lastmod'    => !empty($product['updated_at']) ? date('Y-m-d', strtotime($product['updated_at'])) : null,
                'images'     => [],
            ];
            // Collect product images for image sitemap
            if (!empty($product['featured_image'])) {
                $entry['images'][] = [
                    'loc'   => sitemap_url(ltrim($product['featured_image'], '/')),
                    'title' => $product['title'] ?? '',
                ];
            }
            if (!empty($product['images']) && is_array($product['images'])) {
                foreach (array_slice($product['images'], 0, 5) as $img) {
                    if (is_string($img) && $img !== '') {
                        $entry['images'][] = [
                            'loc'   => sitemap_url(ltrim($img, '/')),
                            'title' => $product['title'] ?? '',
                        ];
                    }
                }
            }
            $urls[] = $entry;
        }
        $offset += $batchSize;
    } while (count($batch) === $batchSize);
} catch (Throwable $e) {
}

// ── AI Landing Pages (published) ─────────────────────────────────────────────
try {
    foreach ((new AiLandingPage())->getPublishedForSitemap() as $lp) {
        if (empty($lp['slug'])) {
            continue;
        }
        $urls[] = [
            'loc'        => sitemap_url('/lp/' . $lp['slug']),
            'changefreq' => 'weekly',
            'priority'   => '0.7',
            'lastmod'    => !empty($lp['updated_at']) ? date('Y-m-d', strtotime($lp['updated_at'])) : null,
        ];
    }
} catch (Throwable $e) {
}
// ─────────────────────────────────────────────────────────────────────────────

foreach ($urls as $url) {
    echo "\n<url>\n";
    echo '    <loc>' . htmlspecialchars($url['loc'], ENT_QUOTES, 'UTF-8') . '</loc>' . "\n";
    echo '    <changefreq>' . htmlspecialchars($url['changefreq'], ENT_QUOTES, 'UTF-8') . '</changefreq>' . "\n";
    echo '    <priority>' . htmlspecialchars($url['priority'], ENT_QUOTES, 'UTF-8') . '</priority>' . "\n";
    if (!empty($url['lastmod'])) {
        echo '    <lastmod>' . htmlspecialchars($url['lastmod'], ENT_QUOTES, 'UTF-8') . '</lastmod>' . "\n";
    }
    // Output image entries if any
    foreach ($url['images'] ?? [] as $image) {
        echo '    <image:image>' . "\n";
        echo '        <image:loc>' . htmlspecialchars($image['loc'], ENT_QUOTES, 'UTF-8') . '</image:loc>' . "\n";
        if (!empty($image['title'])) {
            echo '        <image:title>' . htmlspecialchars($image['title'], ENT_QUOTES, 'UTF-8') . '</image:title>' . "\n";
        }
        echo '    </image:image>' . "\n";
    }
    echo '</url>';
}

echo "\n</urlset>";
