<?php

declare(strict_types=1);

/**
 * TownOS — public entry point
 * All HTTP requests are routed through here via .htaccess
 */

define('BASE_PATH', dirname(__DIR__));
define('START_TIME', microtime(true));

// ── Autoloader (PSR-4: App\ → /app/) ─────────────────────────────────────────
spl_autoload_register(function (string $class): void {
    if (!str_starts_with($class, 'App\\')) {
        return;
    }

    // App\Core\TownResolver        → /app/core/TownResolver.php
    // App\Controllers\Admin\X     → /app/controllers/admin/X.php
    // App\Controllers\TownAdmin\X → /app/controllers/townadmin/X.php
    // App\Services\SEO\SeoService → /app/services/SEO/SeoService.php
    // App\Helpers\CsrfHelper      → /app/helpers/CsrfHelper.php
    $relative = substr($class, 4); // strip "App\"
    $parts    = explode('\\', $relative);
    $dir      = strtolower(array_shift($parts)); // Controllers → controllers
    $filename = array_pop($parts);               // keep original case for filename
    // Try lowercased subpath first; if not found, try original case (for dirs like SEO/, AI/)
    if (!empty($parts)) {
        $subpathLower = implode('/', array_map('strtolower', $parts)) . '/';
        $subpathOrig  = implode('/', $parts) . '/';
    } else {
        $subpathLower = $subpathOrig = '';
    }
    $file = BASE_PATH . '/app/' . $dir . '/' . $subpathLower . $filename . '.php';
    if (!file_exists($file) && $subpathOrig !== $subpathLower) {
        $file = BASE_PATH . '/app/' . $dir . '/' . $subpathOrig . $filename . '.php';
    }

    if (file_exists($file)) {
        require_once $file;
    }
});

// ── Load environment ──────────────────────────────────────────────────────────
require_once BASE_PATH . '/app/core/EnvLoader.php';
loadEnv(BASE_PATH . '/.env');

// ── Error reporting ───────────────────────────────────────────────────────────
$debug = filter_var($_ENV['APP_DEBUG'] ?? false, FILTER_VALIDATE_BOOLEAN);
if ($debug) {
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
} else {
    error_reporting(0);
    ini_set('display_errors', '0');
    ini_set('log_errors', '1');
    ini_set('error_log', BASE_PATH . '/storage/logs/php_errors.log');
}

// ── Security headers ─────────────────────────────────────────────────────────
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('Referrer-Policy: strict-origin-when-cross-origin');
if (!$debug && isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
    header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
}

// ── Session ───────────────────────────────────────────────────────────────────
ini_set('session.save_path', BASE_PATH . '/storage/sessions');
ini_set('session.cookie_httponly', '1');
ini_set('session.use_strict_mode', '1');
ini_set('session.cookie_samesite', 'Lax');
if (!$debug && isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
    ini_set('session.cookie_secure', '1');
}
session_start();

// ── Resolve current town ──────────────────────────────────────────────────────
$townResolver = new \App\Core\TownResolver();
$town = $townResolver->resolve();

// ── Inactive town splash ──────────────────────────────────────────────────────
// If the requesting host belongs to a registered but inactive town, show a
// "coming soon" page instead of falling through to the default town.
(function () use ($town): void {
    $platformDomain = $_ENV['PLATFORM_DOMAIN'] ?? '';
    $host = strtolower(preg_replace('/:\d+$/', '', $_SERVER['HTTP_HOST'] ?? ''));

    // Only applies on town domains (not the platform domain itself)
    if ($host === $platformDomain || $host === 'localhost') {
        return;
    }

    // The resolved town's domain matches — town is active, carry on
    if (isset($town['domain']) && strtolower($town['domain']) === $host) {
        return;
    }

    // Host doesn't match resolved town — check if it's a known inactive town
    $db       = \App\Core\Database::getInstance();
    $inactive = $db->fetch('SELECT name FROM towns WHERE domain = ? AND status = ? LIMIT 1', [$host, 'inactive']);

    if ($inactive) {
        http_response_code(503);
        header('Retry-After: 86400'); // ask crawlers to retry in 24 hours
        $townName = $inactive['name'];
        require BASE_PATH . '/app/views/pages/coming-soon.php';
        exit;
    }
})();

// ── Platform domain override ──────────────────────────────────────────────────
// On the TownOS platform domain (e.g. townos.co.uk) only platform pages are
// accessible. Town content is only reachable via the town's own domain.
$platformDomain = $_ENV['PLATFORM_DOMAIN'] ?? '';
if ($platformDomain !== '') {
    $host        = strtolower(preg_replace('/:\d+$/', '', $_SERVER['HTTP_HOST'] ?? ''));
    $requestPath = strtok($_SERVER['REQUEST_URI'] ?? '/', '?');

    if ($host === $platformDomain) {
        // Paths (or prefixes) permitted on the platform domain
        $platformPaths = [
            '/townos',
            '/privacy-policy',
            '/privacy',
            '/login',
            '/logout',
            '/register',
            '/forgot-password',
            '/reset-password',
            '/password',
            '/admin',
            '/impersonate',
            '/town-admin',    // super-admin town preview via sa_town_preview session override
            '/dashboard',     // super-admin town preview — navigating dashboard pages
            '/business-dashboard', // impersonating a business owner
            '/editor',        // impersonating an editor
            '/profile',       // impersonating any user
            '/api/',          // AJAX calls from admin JS (autocomplete, favourites, reviews)
        ];

        if ($requestPath === '/') {
            // Root → serve the TownOS marketing page
            $_SERVER['REQUEST_URI'] = '/townos';
        } else {
            $allowed = false;
            foreach ($platformPaths as $p) {
                if ($requestPath === $p || str_starts_with($requestPath, $p . '/')) {
                    $allowed = true;
                    break;
                }
            }
            if (!$allowed) {
                // Not a platform page — bounce back to TownOS home
                header('Location: /', true, 301);
                exit;
            }
        }
    } else {
        // ── Town domain: block platform-only paths ────────────────────────────
        // /admin is a super-admin platform area — redirect to the platform domain.
        $platformOnlyPaths = ['/admin', '/impersonate'];
        $requestPath = strtok($_SERVER['REQUEST_URI'] ?? '/', '?');
        foreach ($platformOnlyPaths as $p) {
            if ($requestPath === $p || str_starts_with($requestPath, $p . '/')) {
                $scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
                $port   = $_SERVER['SERVER_PORT'] ?? 80;
                $portSuffix = ($scheme === 'http' && $port != 80) || ($scheme === 'https' && $port != 443)
                    ? ':' . $port : '';
                header('Location: ' . $scheme . '://' . $platformDomain . $portSuffix . $requestPath, true, 301);
                exit;
            }
        }
    }
}

// ── Router ─────────────────────────────────────────────────────────────────
$router = new \App\Core\Router();
require_once BASE_PATH . '/app/routes.php';
$router->dispatch();
