<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/app/bootstrap.php';

$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
if (str_starts_with($path, '/api/trpc/')) { Trpc::serve(); exit; }
if ($path === '/api/admin/events') { serveEvents(); exit; }
if ($path === '/sitemap.xml') { serveSitemap(); exit; }
if ($path === '/robots.txt') { serveRobots(); exit; }
if ($path === '/llms.txt') { serveLlms(); exit; }
if (str_starts_with($path, '/api/')) {
    http_response_code(404);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['error' => 'Not Found']);
    exit;
}
if (PHP_SAPI === 'cli-server') {
    $file = __DIR__ . $path;
    if ($path !== '/' && is_file($file)) return false;
}
$index = __DIR__ . '/index.html';
if (!is_file($index)) { http_response_code(503); echo 'Website files are not installed.'; exit; }
header('Content-Type: text/html; charset=utf-8');
readfile($index);
exit;

function origin(): string
{
    $protocol = strtolower(trim(explode(',', $_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')[0]));
    if (!in_array($protocol, ['http', 'https'], true)) $protocol = isHttps() ? 'https' : 'http';
    $host = trim(explode(',', $_SERVER['HTTP_X_FORWARDED_HOST'] ?? '')[0]) ?: ($_SERVER['HTTP_HOST'] ?? 'localhost');
    if (!preg_match('/^[a-z0-9.\-:\[\]]+$/i', $host)) $host = 'localhost';
    return $protocol . '://' . $host;
}

function seoContent(): array
{
    $settings = [];
    foreach (dbAll('SELECT setting_key, setting_value FROM site_settings') as $row) $settings[$row['settingKey']] = $row['settingValue'];
    return [
        'products' => dbAll("SELECT * FROM products WHERE status = 'published' ORDER BY sort_order ASC, id DESC"),
        'articles' => dbAll("SELECT * FROM articles WHERE status = 'published' ORDER BY published_at DESC"),
        'faqs' => dbAll("SELECT * FROM faqs WHERE status = 'published' ORDER BY sort_order ASC, id ASC"),
        'pages' => dbAll("SELECT * FROM pages WHERE status = 'published'"),
        'settings' => $settings,
    ];
}

function serveSitemap(): void
{
    $base = origin();
    $data = seoContent();
    $urls = [['loc' => $base . '/'], ['loc' => $base . '/products'], ['loc' => $base . '/news'], ['loc' => $base . '/faqs'], ['loc' => $base . '/about'], ['loc' => $base . '/contact'], ['loc' => $base . '/showroom'], ['loc' => $base . '/sitemap']];
    foreach ($data['products'] as $row) $urls[] = ['loc' => $base . '/products/' . rawurlencode($row['slug']), 'lastmod' => $row['updatedAt']];
    foreach ($data['articles'] as $row) $urls[] = ['loc' => $base . '/news/' . rawurlencode($row['slug']), 'lastmod' => $row['updatedAt']];
    foreach ($data['faqs'] as $row) $urls[] = ['loc' => $base . '/faqs/' . rawurlencode($row['slug']), 'lastmod' => $row['updatedAt']];
    foreach ($data['pages'] as $row) if (!in_array($row['slug'], ['home', 'about', 'contact', 'showroom'], true)) $urls[] = ['loc' => $base . '/pages/' . rawurlencode($row['slug']), 'lastmod' => $row['updatedAt']];
    $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    foreach ($urls as $url) {
        $xml .= "\n  <url><loc>" . htmlspecialchars($url['loc'], ENT_XML1 | ENT_QUOTES, 'UTF-8') . '</loc>';
        if (!empty($url['lastmod'])) $xml .= '<lastmod>' . gmdate('Y-m-d', strtotime($url['lastmod'])) . '</lastmod>';
        $xml .= '<changefreq>weekly</changefreq></url>';
    }
    $xml .= "\n</urlset>";
    header('Content-Type: application/xml; charset=UTF-8');
    header('Cache-Control: public, max-age=300');
    echo $xml;
}

function serveRobots(): void
{
    header('Content-Type: text/plain; charset=UTF-8');
    echo "User-agent: *\nAllow: /\nDisallow: /admin\nDisallow: /api/\n\nSitemap: " . origin() . "/sitemap.xml\n";
}

function serveLlms(): void
{
    $base = origin();
    $data = seoContent();
    $settings = $data['settings'];
    $company = $settings['companyName'] ?? 'Tianjin Allway Valve Co., Ltd.';
    $lines = ['# ' . ($settings['siteName'] ?? 'ALLWAY VALVE'), '', '> ' . $company . '. Industrial valve manufacturer providing valves, pipe fittings and one stop service.', '', '## Main pages', '- [Products](' . $base . '/products)', '- [About Us](' . $base . '/about)', '- [News](' . $base . '/news)', '- [Industry Q&A](' . $base . '/faqs)', '- [Contact](' . $base . '/contact): ' . ($settings['email'] ?? 'sales@allwayvalve.com') . '; ' . ($settings['phone'] ?? '+86-15510865705'), '', '## Products'];
    foreach ($data['products'] as $row) $lines[] = '- [' . $row['title'] . '](' . $base . '/products/' . $row['slug'] . '): ' . mb_substr(plainText($row['summary']), 0, 220);
    $lines[] = ''; $lines[] = '## Articles';
    foreach ($data['articles'] as $row) $lines[] = '- [' . $row['title'] . '](' . $base . '/news/' . $row['slug'] . '): ' . mb_substr(plainText($row['summary']), 0, 220);
    $lines[] = ''; $lines[] = '## Industry Q&A';
    foreach ($data['faqs'] as $row) $lines[] = '- [' . $row['question'] . '](' . $base . '/faqs/' . $row['slug'] . '): ' . mb_substr(plainText($row['summary']), 0, 220);
    $lines[] = '';
    header('Content-Type: text/plain; charset=UTF-8');
    header('Cache-Control: public, max-age=300');
    echo implode("\n", $lines);
}

function plainText(string $html): string
{
    return trim(preg_replace('/\s+/u', ' ', html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8')) ?? '');
}

function serveEvents(): void
{
    if (!Auth::current()) { http_response_code(401); header('Content-Type: text/plain; charset=UTF-8'); echo 'Unauthorized'; exit; }
    @set_time_limit(25);
    ignore_user_abort(false);
    while (ob_get_level() > 0) ob_end_clean();
    header('Content-Type: text/event-stream; charset=UTF-8');
    header('Cache-Control: no-cache, no-transform');
    header('Connection: keep-alive');
    header('X-Accel-Buffering: no');
    echo "retry: 3000\n";
    echo "event: ready\ndata: {}\n\n";
    flush();
    $lastId = (int)($_SERVER['HTTP_LAST_EVENT_ID'] ?? 0);
    if ($lastId < 1) $lastId = (int)(dbOne('SELECT COALESCE(MAX(id), 0) AS id FROM inquiries')['id'] ?? 0);
    $started = time();
    $lastPing = time();
    while (time() - $started < 18 && !connection_aborted()) {
        $rows = dbAll('SELECT id, name, product FROM inquiries WHERE id > :id ORDER BY id ASC LIMIT 10', ['id' => $lastId]);
        foreach ($rows as $row) {
            $lastId = (int)$row['id'];
            echo 'id: ' . $lastId . "\n";
            echo "event: inquiry\n";
            echo 'data: ' . json_encode($row, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n\n";
            flush();
        }
        if (time() - $lastPing >= 8) { echo "event: ping\ndata: {}\n\n"; flush(); $lastPing = time(); }
        sleep(2);
    }
    echo "event: ping\ndata: {}\n\n";
    flush();
}
