<?php
declare(strict_types=1);

/**
 * StudyInfoWeb Agency Studio: separate-document-root entry point.
 * Deploy into the agency.studyinfoweb.com.ng CloudPanel document root.
 * The application code remains in the sibling studyinfoweb.com.ng document root.
 * This file does not replace the main website's index.php.
 */

$host = strtolower((string) preg_replace('/:\d+$/', '', (string) ($_SERVER['HTTP_HOST'] ?? '')));
if ($host !== 'agency.studyinfoweb.com.ng') {
    http_response_code(404);
    exit('Page not found.');
}

// PHP fallback for public assets on an Nginx subdomain. Configure matching
// Nginx redirects too if its static-location handling bypasses the front controller.
$siwAssetPath = (string)(parse_url((string)($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH) ?: '/');
if ($siwAssetPath === '/favicon.ico' ||
    (preg_match('~^/(?:assets|resume/assets)/[a-zA-Z0-9_./%\-]+\.(?:css|js|png|jpe?g|gif|webp|svg|ico|woff2?|ttf|map)$~iD', $siwAssetPath)
        && !str_contains($siwAssetPath, '..'))) {
    $siwAssetQuery = preg_replace('/[\r\n]/', '', (string)($_SERVER['QUERY_STRING'] ?? ''));
    header('Location: https://studyinfoweb.com.ng' . $siwAssetPath . ($siwAssetQuery !== '' ? '?' . $siwAssetQuery : ''), true, 302);
    exit;
}

// CloudPanel/HostWager: the subdomain and main website are sibling document roots.
// Set SIW_MAIN_APP_ROOT explicitly in PHP-FPM only when a custom directory is used.
$siwRootCandidates = [];
$siwConfiguredRoot = getenv('SIW_MAIN_APP_ROOT');
if (is_string($siwConfiguredRoot) && trim($siwConfiguredRoot) !== '') {
    $siwRootCandidates[] = trim($siwConfiguredRoot);
}
$siwRootCandidates[] = dirname(__DIR__) . '/studyinfoweb.com.ng';
$siwRootCandidates[] = dirname(__DIR__) . '/studyinfoweb.com.ng/public_html';
$appRoot = '';
foreach ($siwRootCandidates as $siwCandidate) {
    $siwResolved = realpath($siwCandidate);
    if ($siwResolved !== false && is_file($siwResolved . '/app/bootstrap.php')) {
        $appRoot = $siwResolved;
        break;
    }
}
if ($appRoot === '') {
    error_log('StudyInfoWeb portal: main shared application root not found; verify sibling website directories.');
    http_response_code(503);
    header('Content-Type: text/plain; charset=utf-8');
    exit('Shared StudyInfoWeb application is not accessible. Verify CloudPanel site paths.');
}
$required = [
    $appRoot . '/app/bootstrap.php',
    $appRoot . '/app/Middleware/Security.php',
    $appRoot . '/app/Middleware/Maintenance.php',
    $appRoot . '/routes/agency.php',
];

foreach ($required as $file) {
    if (!is_file($file) || !is_readable($file)) {
        error_log('Agency Studio setup: a required shared application file is unavailable: ' . $file);
        http_response_code(503);
        header('Content-Type: text/plain; charset=utf-8');
        exit('Agency Studio setup incomplete. Check that Phases 1-4 are installed in the main StudyInfoWeb directory, and that the hosting account permits PHP access to that directory.');
    }
}

// Some shared application components use relative filesystem paths.
if (!@chdir($appRoot)) {
    error_log('Agency Studio setup: cannot change working directory to shared application root.');
    http_response_code(503);
    header('Content-Type: text/plain; charset=utf-8');
    exit('Agency Studio could not access the shared application directory.');
}

// Bootstrap defines ROOT_PATH using the actual main application directory.
require $appRoot . '/app/bootstrap.php';
require ROOT_PATH . '/app/Middleware/Security.php';
require ROOT_PATH . '/app/Middleware/Maintenance.php';

$path = parse_url((string) ($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH) ?: '/';
if ($path === '/index.php') {
    $path = '/';
}
$path = preg_replace('#/+#', '/', $path) ?: '/';
if ($path !== '/') {
    $path = rtrim($path, '/');
}
if (!empty($GLOBALS['SIW_FORCED_ROUTE'])) {
    $path = (string) $GLOBALS['SIW_FORCED_ROUTE'];
}

enforce_security($path);
enforce_maintenance($path);

// Use the installed agency routes, including any Phase 4 additions.
require ROOT_PATH . '/routes/agency.php';
$router->dispatch((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'), $path);
