<?php
declare(strict_types=1);

require __DIR__ . '/app/functions.php';
require __DIR__ . '/app/database.php';
require __DIR__ . '/app/router.php';
require __DIR__ . '/app/renderer.php';

$themes = require __DIR__ . '/app/themes.php';
try {
    $site = load_site();
} catch (RuntimeException $exception) {
    http_response_code(404);
    echo '<!doctype html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,follow"><title>Website not found</title></head><body><main style="max-width:720px;margin:15vh auto;padding:24px;font-family:system-ui,sans-serif;text-align:center"><h1>Website not found</h1><p>This website address is not active.</p><a href="https://www.odesk.top/">Go to platform</a></main></body></html>';
    exit;
}
$theme = $themes[$site['theme']] ?? $themes['platform'];
$route = resolve_route($theme);
if (($route['type'] ?? '') === 'redirect') { header('Location: ' . $route['location'], true, (int)$route['status']); exit; }
if (($route['slug'] ?? '') === 'home' && ($site['theme'] ?? '') === 'education') {
    $site['education_notices'] = database_configured() ? load_updates(database(), (int) $site['id']) : [];
}


if ($route['slug'] === 'search') {
    $query = trim((string) ($_GET['q'] ?? ''));
    if (mb_strlen($query) > 100) $query = mb_substr($query, 0, 100);
    $route['query'] = $query;
    $route['results'] = database_configured() ? search_site_content(database(), (int) $site['id'], $query) : [];
    if ($query !== '' && (str_contains(strtolower('Sitemap'), strtolower($query)) || str_contains(strtolower($query), 'sitemap'))) {
        $route['results'][] = ['title'=>'Sitemap','url'=>'/sitemap','type'=>'Page','excerpt'=>'Browse all important pages on this website.'];
    }
    $route['seo'] = ['title'=>'Search','description'=>'Search this website.'];
}

if ($route['slug'] === 'posts') {
    $route['updates'] = database_configured() ? load_updates(database(), (int) $site['id']) : development_updates();
} elseif ($route['slug'] === 'updates-article') {
    $post = database_configured() ? load_update_by_slug(database(), (int) $site['id'], (string) ($route['post_slug'] ?? '')) : null;
    if (!$post && ($site['theme'] ?? '') === 'education') {
        foreach (default_education_notices() as $candidate) {
            if ($candidate['slug'] !== ($route['post_slug'] ?? '')) continue;
            $post = $candidate + ['id'=>0,'excerpt'=>'','image'=>'','featured'=>false,'published_at'=>date('Y-m-d H:i:s'),'status'=>'published'];
            break;
        }
    }
    if (!$post && !database_configured()) {
        foreach (development_updates() as $candidate) if ($candidate['slug'] === ($route['post_slug'] ?? '')) $post = $candidate;
    }
    if (!$post) $route = ['status'=>404,'type'=>'error','slug'=>'404','title'=>'Page not found'];
    else {
        $route['post'] = $post;
        $route['title'] = $post['title'];
        $route['seo'] = ['title'=>$post['title'],'description'=>$post['excerpt']];
        $route['related_updates'] = array_values(array_filter(database_configured() ? load_updates(database(), (int) $site['id']) : development_updates(), static fn(array $item): bool => $item['slug'] !== $post['slug']));
    }
}

if (($route['slug'] ?? '') === 'product-detail') {
    $product = null;
    foreach (array_values((array) ($site['ecommerce_featured_products'] ?? default_ecommerce_featured_products())) as $index => $candidate) {
        $candidateName = (string) ($candidate['name'] ?? 'Product');
        if (ecommerce_product_id($candidateName, $index) === ($route['product_id'] ?? '')) {
            $product = $candidate + ['id' => (string) $route['product_id']];
            break;
        }
    }
    if (!$product) {
        $route = ['status'=>404,'type'=>'error','slug'=>'404','title'=>'Page not found'];
    } else {
        $route['product'] = $product;
        $route['title'] = (string) ($product['name'] ?? 'Product');
        $route['seo'] = ['title' => (string) ($product['name'] ?? 'Product'), 'description' => 'View product details, price and ordering information.'];
    }
}

if (($route['slug'] ?? '') === 'category-products') {
    $category = null;
    foreach ((array) ($site['ecommerce_categories'] ?? default_ecommerce_categories()) as $candidate) {
        if (($candidate['type'] ?? '') === ($route['category_type'] ?? '')) { $category = $candidate; break; }
    }
    if (!$category) {
        $route = ['status'=>404,'type'=>'error','slug'=>'404','title'=>'Page not found'];
    } else {
        $route['category'] = $category;
        $route['title'] = (string) ($category['name'] ?? 'Category');
        $route['seo'] = ['title' => (string) ($category['name'] ?? 'Category'), 'description' => 'Browse products in this category.'];
    }
}

$page = null;
if ($route['type'] === 'page' && !in_array($route['slug'], ['updates-article', 'search'], true)) {
    $page = load_page((int) $site['id'], (string) $route['slug']);
} elseif ($route['status'] === 404) {
    $candidateSlug = ltrim(request_path(), '/');
    if ($candidateSlug !== '' && !str_contains($candidateSlug, '/')) {
        $page = load_page((int) $site['id'], $candidateSlug);
        if ($page) {
            $route = ['status' => 200, 'type' => 'page', 'slug' => $candidateSlug, 'title' => (string) $page['title']];
        }
    }
}

if ($page && ($page['status'] ?? 'published') === 'hidden') {
    $route = ['status' => 404, 'type' => 'error', 'slug' => '404', 'title' => 'Page not found'];
} elseif ($page) {
    $route['title'] = (string) $page['title'];
    $route['content'] = (string) ($page['content'] ?? '');
    $route['seo'] = $page['seo'];
}
render_site($site, $theme, $themes, $route);
