<?php
declare(strict_types=1);

/**
 * StudyInfoWeb Student Portal — separate subdomain entry point.
 * Install ONLY in:
 * The student.studyinfoweb.com.ng CloudPanel document root.
 * The shared application stays in the sibling studyinfoweb.com.ng document root.
 *
 * Allowed: student login, registration, recovery, dashboard, profile, messages.
 * Excluded: administration, agency design tools and commerce routes.
 */

$host = strtolower((string) preg_replace('/:\d+$/', '', (string) ($_SERVER['HTTP_HOST'] ?? '')));
if ($host !== 'student.studyinfoweb.com.ng') {
    http_response_code(404);
    header('Content-Type: text/plain; charset=utf-8');
    exit('Page not found.');
}

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

// The Student portal opens with its existing dashboard or login screen.
if ($path === '/' || $path === '/index.php') {
    header('Location: /dashboard', true, 302);
    exit;
}

// Restrict this subdomain to existing STUDENT routes only.
// This prevents /studyng-main/*, /studio/*, /billing/* and other application
// functions from being dispatched through the student subdomain.
$allowed = [
    '/login'             => ['GET', 'POST'],
    '/register'          => ['GET', 'POST'],
    '/password-recovery' => ['GET', 'POST'],
    '/forgot-password'   => ['GET'],
    '/reset-password'    => ['GET'],
    '/logout'            => ['GET'],
    '/dashboard'         => ['GET'],
    '/dashboard/profile' => ['GET', 'POST'],
    '/dashboard/messages'=> ['GET'],
    '/dashboard/messages/trash'=> ['GET'],
    '/dashboard/messages/action'=> ['POST'],
];
$method = strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'));
if (!isset($allowed[$path]) || !in_array($method, $allowed[$path], true)) {
    http_response_code(404);
    header('Content-Type: text/plain; charset=utf-8');
    exit('Student portal route not found.');
}

// Do not replace the main website files or copy application code here.
// 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/web.php',
];
foreach ($required as $file) {
    if (!is_file($file) || !is_readable($file)) {
        error_log('StudyInfoWeb Student portal: missing/unreadable shared application file: ' . $file);
        http_response_code(503);
        header('Content-Type: text/plain; charset=utf-8');
        exit('Student portal setup is incomplete. Verify the main StudyInfoWeb application files.');
    }
}

// Some existing helpers use relative filesystem paths.
if (!@chdir($appRoot)) {
    error_log('StudyInfoWeb Student portal: cannot change to shared application directory.');
    http_response_code(503);
    header('Content-Type: text/plain; charset=utf-8');
    exit('Student portal could not access the main application directory.');
}

require $appRoot . '/app/bootstrap.php';
require ROOT_PATH . '/app/Middleware/Security.php';
require ROOT_PATH . '/app/Middleware/Maintenance.php';

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

// The existing AuthController verifies role='student'; DashboardController
// requires an authenticated student. We do not duplicate those controllers.
require ROOT_PATH . '/routes/web.php';
$router->dispatch($method, $path);
