<?php

declare(strict_types=1);

require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/helpers.php';
require_once __DIR__ . '/includes/i18n.php';
require_once __DIR__ . '/includes/auth.php';

init_i18n();

app_maybe_redirect_canonical_request();

if (!headers_sent()) {
    header('X-Robots-Tag: noindex, nofollow, noarchive, nosnippet', true);
}

function app_resolve_request_uri(): string
{
    if (!empty($_SERVER['KARVI_ROUTE'])) {
        $route = (string)$_SERVER['KARVI_ROUTE'];
        return str_starts_with($route, '/') ? $route : '/' . $route;
    }

    if (isset($_GET['route']) && is_string($_GET['route']) && $_GET['route'] !== '') {
        return '/' . ltrim($_GET['route'], '/');
    }

    $candidates = [];
    foreach (['REQUEST_URI', 'REDIRECT_URL', 'PATH_INFO'] as $key) {
        if (empty($_SERVER[$key])) {
            continue;
        }
        $path = parse_url((string)$_SERVER[$key], PHP_URL_PATH);
        if (is_string($path) && $path !== '') {
            $candidates[] = rtrim(str_replace('\\', '/', $path), '/') ?: '/';
        }
    }

    $basePath = app_base_path();
    foreach ($candidates as $path) {
        if ($basePath !== '' && str_starts_with($path, $basePath)) {
            $path = substr($path, strlen($basePath)) ?: '/';
        }

        $path = rtrim($path, '/') ?: '/';
        if ($path === '/index.php' || $path === '/default.php') {
            return '/';
        }

        if (!str_starts_with($path, '/admin')
            && !str_starts_with($path, '/api')
            && !str_starts_with($path, '/contract')
            && !str_starts_with($path, '/contracts')
            && (str_contains($path, 'Karvi_partner_contract') || str_contains($path, '/link/'))) {
            $extracted = app_extract_app_route_from_path($path);
            if ($extracted !== null) {
                return $extracted;
            }
        }

        return $path;
    }

    return '/';
}

$uri = app_resolve_request_uri();
$method = $_SERVER['REQUEST_METHOD'];

if ($uri === '/robots.txt') {
    $robotsFile = __DIR__ . '/robots.txt';
    header('Content-Type: text/plain; charset=utf-8');
    header('Cache-Control: public, max-age=86400');
    if (is_file($robotsFile)) {
        readfile($robotsFile);
    } else {
        echo "User-agent: *\nDisallow: /\n";
    }
    exit;
}

$routes = [
    'GET' => [
        '/' => 'pages/home.php',
        '/admin' => 'pages/admin_redirect.php',
        '/admin/login' => 'pages/admin_login.php',
        '/admin/dashboard' => 'pages/admin_dashboard.php',
        '/admin/database' => 'pages/admin_database.php',
        '/admin/api/contracts' => 'pages/admin_api_contracts.php',
        '/admin/download' => 'pages/admin_download.php',
        '/admin/download-signatures' => 'pages/admin_download_signatures.php',
        '/admin/create' => 'pages/admin_create.php',
        '/admin/website' => 'pages/admin_website.php',
        '/admin/website/create' => 'pages/admin_website_create.php',
        '/admin/pos' => 'pages/admin_pos.php',
        '/admin/pos/create' => 'pages/admin_pos_create.php',
        '/admin/pos/link' => 'pages/admin_pos_link.php',
        '/admin/website/link' => 'pages/admin_website_link.php',
        '/admin/create/link' => 'pages/admin_create_link.php',
        '/admin/template' => 'pages/admin_template.php',
        '/admin/logout' => 'pages/admin_logout.php',
    ],
    'POST' => [
        '/admin/login' => 'pages/admin_login.php',
        '/admin/create' => 'pages/admin_create.php',
        '/admin/website/create' => 'pages/admin_website_create.php',
        '/admin/pos/create' => 'pages/admin_pos_create.php',
        '/admin/contract/delete' => 'pages/admin_contract_delete.php',
        '/admin/contract/duplicate' => 'pages/admin_contract_duplicate.php',
        '/api/sign' => 'pages/api_sign.php',
        '/api/pdf-viewed' => 'pages/api_pdf_viewed.php',
        '/api/registration-email' => 'pages/api_registration_email.php',
        '/api/link-location' => 'pages/api_link_location.php',
    ],
];

if (preg_match('#^/lang/(en|de)$#', $uri, $matches)) {
    $GLOBALS['route_locale'] = $matches[1];
    require __DIR__ . '/pages/set_locale.php';
    exit;
}

if (preg_match('#^/contracts/sign/([a-zA-Z0-9_-]{8,128})$#', $uri, $matches)) {
    $_GET['sign_token'] = $matches[1];
    require __DIR__ . '/pages/public_contract_view.php';
    exit;
}

if (preg_match('#^/contract\d*$#', $uri) || $uri === '/contract') {
    redirect('/admin/login/');
}

if (preg_match('#^/contract/([a-z0-9]{32})/pdf$#', $uri, $matches)) {
    $_GET['token'] = $matches[1];
    require __DIR__ . '/pages/reg_pdf_serve.php';
    exit;
}

if (preg_match('#^/contract/([a-z0-9]{32})/document$#', $uri, $matches)) {
    $_GET['token'] = $matches[1];
    require __DIR__ . '/pages/reg_pdf_embed.php';
    exit;
}

if (preg_match('#^/contract/([a-z0-9]{32})/view$#', $uri, $matches)) {
    $_GET['token'] = $matches[1];
    require __DIR__ . '/pages/reg_pdf_view.php';
    exit;
}

if (preg_match('#^/contract/([a-z0-9]{32})$#', $uri, $matches)) {
    $_GET['token'] = $matches[1];
    require __DIR__ . '/pages/contract_view.php';
    exit;
}

if (preg_match('#^/admin/contracts/(\d+)/send$#', $uri, $matches)) {
    $_GET['id'] = $matches[1];
    require __DIR__ . '/pages/admin_contract_send.php';
    exit;
}

if (preg_match('#^/admin/contracts/(\d+)/delete$#', $uri, $matches)) {
    $_GET['id'] = $matches[1];
    require __DIR__ . '/pages/admin_contract_destroy.php';
    exit;
}

if (preg_match('#^/admin/contracts/(\d+)/edit$#', $uri, $matches)) {
    $_GET['id'] = $matches[1];
    require __DIR__ . '/pages/admin_contract_edit.php';
    exit;
}

if (preg_match('#^/admin/contracts/(\d+)$#', $uri, $matches)) {
    $_GET['id'] = $matches[1];
    require __DIR__ . '/pages/admin_contract_show.php';
    exit;
}

if (preg_match('#^/assets/(.+)$#', $uri, $matches)) {
    $assetPath = str_replace(['..', '\\'], '', $matches[1]);
    $file = __DIR__ . '/assets/' . $assetPath;
    $realBase = realpath(__DIR__ . '/assets');
    $realFile = file_exists($file) ? realpath($file) : false;
    if ($realFile && $realBase && str_starts_with($realFile, $realBase)) {
        $ext = pathinfo($realFile, PATHINFO_EXTENSION);
        $types = ['css' => 'text/css', 'js' => 'application/javascript', 'png' => 'image/png'];
        header('Content-Type: ' . ($types[$ext] ?? 'application/octet-stream'));
        readfile($realFile);
        exit;
    }
}

if (preg_match('#^/uploads/(contracts|signed)/([a-zA-Z0-9._-]+)$#', $uri)) {
    http_response_code(403);
    header('Content-Type: text/plain; charset=utf-8');
    exit('Direct file access is not allowed. Use the contract link or admin download.');
}

if (isset($routes[$method][$uri])) {
    require __DIR__ . '/' . $routes[$method][$uri];
    exit;
}

http_response_code(404);
$home = app_absolute_url('/');
$adminLogin = app_absolute_url('/admin/login');
echo '<!DOCTYPE html><html lang="de"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">';
echo '<title>404 — Karvi</title>';
echo '<style>body{font-family:Arial,sans-serif;text-align:center;padding:2rem;max-width:560px;margin:0 auto;line-height:1.6}';
echo '.box{background:#f8f8f8;border:1px solid #ddd;border-radius:10px;padding:1.25rem;margin:1.5rem 0;text-align:left}';
echo 'a.btn{display:inline-block;margin:0.5rem;padding:10px 20px;background:#b8860b;color:#fff;text-decoration:none;border-radius:6px}</style></head><body>';
echo '<h1>404 — Page Not Found</h1>';
echo '<p>Diese Seite existiert nicht: <code>' . htmlspecialchars($uri, ENT_QUOTES, 'UTF-8') . '</code></p>';
echo '<div class="box"><strong>Richtige URLs:</strong><ul>';
echo '<li><strong>Admin Login:</strong><br><a href="' . htmlspecialchars($adminLogin, ENT_QUOTES, 'UTF-8') . '">' . htmlspecialchars($adminLogin, ENT_QUOTES, 'UTF-8') . '</a></li>';
echo '<li><strong>Vertrag (Kunde):</strong><br><code>/contract/32-zeichen-token</code><br><small>Link kommt aus dem Admin-Dashboard</small></li>';
echo '</ul><p><small>/contract1 ist kein gültiger Link — Admin Login verwenden.</small></p></div>';
echo '<a class="btn" href="' . htmlspecialchars($adminLogin, ENT_QUOTES, 'UTF-8') . '">Admin Login</a> ';
echo '<a class="btn" href="' . htmlspecialchars($home, ENT_QUOTES, 'UTF-8') . '" style="background:#555">Home</a>';
echo '</body></html>';
