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

define('ROOT_PATH', dirname(__DIR__));
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;
}

// Prefer APP_URL from .env — prevents Host Header Injection in Sitemap directive
$appUrl = \Core\System\Env::get('APP_URL', '');
if ($appUrl !== '') {
    $baseUrl = rtrim($appUrl, '/');
} else {
    $scheme  = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host    = $_SERVER['SERVER_NAME'] ?? ($_SERVER['HTTP_HOST'] ?? '');
    $baseUrl = rtrim($scheme . '://' . $host, '/');
}
$default = implode("\n", [
    'User-agent: *',
    'Allow: /',
    '',
    'Disallow: /admin/',
    'Disallow: /api/',
    'Disallow: /install/',
    'Disallow: /public/install/',
    'Disallow: /cron/',
    'Disallow: /storage/',
    'Disallow: /uploads/admins/',
    'Disallow: /uploads/reviews/',
    'Disallow: /lp-order-form/',
    'Disallow: /order/success',
    'Disallow: /license/',
    'Disallow: /public/',
    '',
    '# Performance bots',
    'User-agent: AhrefsBot',
    'Crawl-delay: 10',
    '',
    'User-agent: SemrushBot',
    'Crawl-delay: 10',
    '',
    'Sitemap: {BASE_URL}/sitemap.xml',
]);
$content = '';

try {
    if (function_exists('db')) {
        $stmt = db()->prepare("SELECT setting_value FROM settings WHERE setting_key = 'robots_txt_content' LIMIT 1");
        $stmt->execute();
        $content = (string)($stmt->fetchColumn() ?: '');
    }
} catch (Throwable $e) {
}

$content = trim($content) !== '' ? $content : $default;
$content = str_replace('{BASE_URL}', $baseUrl, $content);
echo $content;
