<?php

// Load composer autoloader first so we can use VersionUtils utility
require_once __DIR__ . '/vendor/autoload.php';

use ChurchCRM\Authentication\AuthenticationManager;
use ChurchCRM\dto\SystemConfig;
use ChurchCRM\dto\SystemURLs;
use ChurchCRM\Utils\MiscUtils;
use ChurchCRM\Utils\RedirectUtils;
use ChurchCRM\Utils\VersionUtils;

// Get required PHP version from composer.json (single source of truth)
// Throws RuntimeException if system state cannot be determined
try {
    $requiredPhp = VersionUtils::getRequiredPhpVersion();
} catch (\RuntimeException $e) {
    // System cannot determine PHP requirements - fail loudly with clear error
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo"Critical System Error:" . $e->getMessage() ."\n\n";
    echo"Please contact your system administrator or check your ChurchCRM installation.";
    exit(1);
}

// Derive install prefix from SCRIPT_NAME — works for root and nested subdir installs.
// Computed before any redirect so both the PHP-version and setup redirects resolve correctly.
//   /churchcrm/index.php  →  dirname → /churchcrm
//   /index.php            →  dirname → /  → ''
$_idx_script = str_replace('\\', '/', $_SERVER['SCRIPT_NAME'] ?? '/index.php');
$_idx_root   = dirname($_idx_script);
if ($_idx_root === '/' || $_idx_root === '.') {
    $_idx_root = '';
}

$phpVersion = phpversion();
if (version_compare($phpVersion, $requiredPhp, '<')) {
    header("Location: {$_idx_root}/errors/php-error.php");
    exit;
}

if (file_exists(__DIR__ . '/Include/Config.php')) {
    require_once __DIR__ . '/Include/Config.php';
} else {
    header("Location: {$_idx_root}/setup");
    exit;
}

mb_internal_encoding('UTF-8');

// Get the current request path and convert it into a magic filename
// e.g. /list-events => /ListEvents.php
$shortName = str_replace(SystemURLs::getRootPath() . '/', '', $_SERVER['REQUEST_URI']);
$fileName = MiscUtils::dashesToCamelCase($shortName, true) . '.php';

// First, ensure that the user is authenticated.
AuthenticationManager::ensureAuthentication();

// On a fresh install (sChurchName empty), redirect admin users to complete setup.
if (empty(SystemConfig::getValue('sChurchName'))) {
    try {
        $currentUser = AuthenticationManager::getCurrentUser();
        if ($currentUser->isAdmin()) {
            RedirectUtils::redirect('admin/system/church-info');
        }
    } catch (\Throwable) {
        // Not logged in or session error — ensureAuthentication() above handles it
    }
}

if (strtolower($shortName) === 'index.php' || strtolower($fileName) === 'index.php') {
    // Index.php -> v2/dashboard
    RedirectUtils::redirect('v2/dashboard');
} elseif (is_file($shortName)) {
    // Try actual path
    require $shortName;
} elseif (file_exists($fileName)) {
    // Try magic filename
    require $fileName;
} elseif (strpos($_SERVER['REQUEST_URI'], 'js') || strpos($_SERVER['REQUEST_URI'], 'css')) { // if this is a CSS or JS file that we can't find, return 404
    header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found', true, 404);
    exit;
} else {
    RedirectUtils::redirect('index.php');
}
