<?php
ob_start();
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/buffer_controller.php';
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/includes/functions.php';

if (function_exists('checkCountryBlocking')) {
    checkCountryBlocking();
}

$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$baseUrlPath = parse_url(BASE_URL, PHP_URL_PATH);

if (!empty($baseUrlPath) && $baseUrlPath !== '/' && strpos($uri, $baseUrlPath) === 0) {
    $uri = substr($uri, strlen($baseUrlPath));
}

if (empty($uri) || $uri === '') {
    $uri = '/';
} else {
    $uri = preg_replace('#/+#', '/', $uri);
    if ($uri !== '/' && substr($uri, -1) === '/') {
        $uri = rtrim($uri, '/');
    }
    if ($uri !== '/' && substr($uri, 0, 1) !== '/') {
        $uri = '/' . $uri;
    }
}

$routes = [
    '/' => '/index.php',
    '/index' => '/index.php',
    '/login' => '/login.php',
    '/magic_login' => '/magic_login.php',
    '/magic_verify' => '/magic_verify.php',
    '/account' => '/account.php',
    '/login_reset' => '/login_reset.php',
    '/logout' => '/logout.php',
    '/register' => '/register.php',
    '/validate_email' => '/validate_email.php',
    '/resend_validation' => '/resend_validation.php',
    '/profile' => '/profile.php',
    '/contact' => '/contact.php',
    '/faq' => '/faq.php',
    '/debug_info' => '/debug_info.php',
    '/livechat' => '/livechat.php',
    '/chat_api' => '/chat_api.php',
    '/tickets' => '/tickets.php',
    '/ticket_create' => '/ticket_create.php',
    '/ticket_view' => '/ticket_view.php',
    '/ticket_delete' => '/ticket_delete.php',
    '/faq_update' => '/faq_update.php',
    '/privacy' => '/privacy.php',
    '/about' => '/about.php',
    '/terms' => '/terms.php',
    '/services' => '/services.php',
    '/portfolio' => '/portfolio.php',
    '/news_update' => '/news_update.php',
    '/news' => '/news.php',
    '/session_refresh' => '/session_refresh.php',
    '/admin/assistant' => '/admin/assistant.php',
    '/admin/custom_fields' => '/admin/custom_fields.php',
    '/admin/templates' => '/admin/templates.php',
    '/admin/texts' => '/admin/texts.php',
    '/admin/styles' => '/admin/styles.php',
    '/admin/dashboard' => '/admin/dashboard.php',
    '/admin/settings' => '/admin/settings.php',
    '/admin/tickets' => '/admin/tickets.php',
    '/admin/snippets' => '/admin/snippets.php',
    '/admin/license' => '/admin/license.php',
    '/admin/pages' => '/admin/pages.php',
    '/admin/tickets_categories' => '/admin/tickets_categories.php',
    '/admin/users' => '/admin/users.php',
];

if (isset($routes[$uri])) {
    include __DIR__ . $routes[$uri];
    exit();
}

if (is_file(__DIR__ . $uri) && strpos(realpath(__DIR__ . $uri), realpath(__DIR__)) === 0) {
    $fileInfo = pathinfo(__DIR__ . $uri);
    $ext = strtolower($fileInfo['extension'] ?? '');
    if (in_array($ext, ['php', 'config', 'json', 'env', 'htaccess'], true)) {
        header('HTTP/1.0 403 Forbidden');
        include __DIR__ . '/404.php';
        exit();
    }
    $contentTypes = ['css' => 'text/css', 'js' => 'application/javascript', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif', 'svg' => 'image/svg+xml', 'pdf' => 'application/pdf'];
    if (isset($contentTypes[$ext])) {
        header('Content-Type: ' . $contentTypes[$ext]);
    }
    readfile(__DIR__ . $uri);
    exit();
}

$dynamicRoutes = [
    '#^/ticket_view/(\d+)$#' => ['file' => '/ticket_view.php', 'param' => 'id'],
    '#^/ticket_delete/(\d+)$#' => ['file' => '/ticket_delete.php', 'param' => 'id'],
    '#^/admin/([a-zA-Z0-9_-]+)$#' => ['resolve_admin' => true, 'param' => null],
];

foreach ($dynamicRoutes as $pattern => $route) {
    if (preg_match($pattern, $uri, $matches)) {
        if (!empty($route['param'])) {
            $_GET[$route['param']] = $matches[1];
        }
        if (!empty($route['resolve_admin'])) {
            $adminSlug = $matches[1];
            $adminRoot = realpath(__DIR__ . '/admin');
            if ($adminRoot === false) {
                header('HTTP/1.0 404 Not Found');
                include __DIR__ . '/404.php';
                exit();
            }
            $candidate = __DIR__ . '/admin/' . $adminSlug . '.php';
            if (!is_file($candidate)) {
                header('HTTP/1.0 404 Not Found');
                include __DIR__ . '/404.php';
                exit();
            }
            $resolvedAdmin = realpath($candidate);
            if ($resolvedAdmin === false || strpos($resolvedAdmin, $adminRoot) !== 0) {
                header('HTTP/1.0 404 Not Found');
                include __DIR__ . '/404.php';
                exit();
            }
            include $resolvedAdmin;
            exit();
        }
        include __DIR__ . $route['file'];
        exit();
    }
}

header('HTTP/1.0 404 Not Found');
include __DIR__ . '/404.php';
exit();
