<?php

use Symfony\Component\ErrorHandler\Debug;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;

if (file_exists('.indexprepend.php')) {
    include_once '.indexprepend.php';
}

// ❱❱ Konstante Definitionen
defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
defined('APPLICATION_VERSION') || define('APPLICATION_VERSION', "evolution");
defined('APPLICATION_ENV') || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));

// ❱❱ Version und Zend-Config vorbereiten
require_once __DIR__ . '/../customer-version.php';
require_once 'Zend/Config/Ini.php';

// ❱❱ Maintenance Mode
if (file_exists(APPLICATION_PATH . '/../maintenance.ini')) {
    $mtSettings = new Zend_Config_Ini(APPLICATION_PATH . '/../maintenance.ini');
    $mtSettings = $mtSettings->toArray();

    if (!empty($mtSettings['active'])) {
        require_once('Zend/Session.php');
        Zend_Session::start();
        $sess = new Zend_Session_Namespace('maintenance');

        $overrideCode = $mtSettings['overridecode'] ?? '1';
        $overrideCookieName = 'lmsmoverride';

        if (!isset($sess->override)) {
            $sess->override = false;
        }

        if (isset($_COOKIE[$overrideCookieName]) && $overrideCode == $_COOKIE[$overrideCookieName]) {
            $sess->override = true;
        } elseif (isset($_REQUEST['maintenanceoverride'])) {
            if ($overrideCode == $_REQUEST['maintenanceoverride']) {
                setcookie($overrideCookieName, $overrideCode, 0, "", "", true, true);
                $sess->override = true;
            } else {
                $sess->override = false;
            }
        }

        if (!$sess->override) {
            if (isset($mtSettings['page'])) {
                include $mtSettings['page'];
            } else {
                echo "The application is currently not available due to planned system maintenance";
            }
            exit;
        }
    }
}

//Symfony Boot vor Zend (für Legacy-Integration wichtig)

//Sind zwei varianten überhaubt noch notwenidig?
require_once __DIR__ . '/../vendor/autoload.php';

if ('development' === APPLICATION_ENV) {

    include_once __DIR__ . '/app_dev.php';
} else {
    include_once __DIR__ . '/app.php';
}

// Kernel booten und in Registry legen
//$kernel->boot();

Debug::enable();
require_once 'Zend/Registry.php';
Zend_Registry::set('Symfony_Kernel', $kernel);

// Symfony-Request vorbereiten
$request = Request::createFromGlobals();
Zend_Registry::set('Symfony_Request', $request);

$logger = $kernel->getContainer()->get('monolog.logger.router_routing');
Zend_Registry::set('Symfony_Logger', $logger); // optional für spätere Zend-Nutzung


// Renderer in Registry ablegen
$renderer = $kernel->getContainer()->get(\App\Core\LegacyBundle\Bridge\SymfonyLegacyRenderer::class);
Zend_Registry::set('Symfony_Renderer', $renderer);

// Symfony-Router vorbereiten
$matcher = $kernel->getContainer()->get('router');

try {
    //Prüfe, ob Symfony eine passende Route kennt
    $routeInfo = $matcher->match($request->getPathInfo());

    $logger->info('[Router] Symfony übernimmt Route: ' . $request->getPathInfo(), [
        'route' => $routeInfo['_route'] ?? null,
        'method' => $request->getMethod(),
    ]);

    //Wenn ja, Symfony übernimmt komplett
    $response = $kernel->handle($request);
    Zend_Registry::set('Symfony_Response', $response);

    // Header setzen für Cache-Kompatibilität
    header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');

    // Response senden und Terminieren
    $response->send();
    $kernel->terminate($request, $response);
    exit;

} catch (ResourceNotFoundException | NotFoundHttpException $e) {
    //Symfony kennt die Route nicht – Zend übernimmt
    $logger->info('[Router] Symfony kennt die Route nicht – Zend übernimmt', [
        'path' => $request->getPathInfo()
    ]);

} catch (\Exception $e) {
    // Fehler in Symfony
    $logger->error('[Router] Fehler beim Symfony-Handling', [
        'message' => $e->getMessage(),
        'exception' => $e,
        'path' => $request->getPathInfo(),
    ]);

    if (APPLICATION_ENV === 'development') {
        throw $e;
    }
    // In Produktivsystemen lieber Zend übernehmen lassen
}

//Zend übernimmt ab hier

// Workaround für Cache-Header
header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');

// Define application cache namespace
defined('APPLICATION_CACHE_NS') || define('APPLICATION_CACHE_NS', 'n' . md5(APPLICATION_PATH) . '_');

// Include library path
set_include_path(get_include_path() . PATH_SEPARATOR . APPLICATION_PATH . '/../library');

// Load configuration
$configDir = APPLICATION_PATH . '/configs/';
$hostConfigPath = $configDir . 'application-' . $_SERVER['SERVER_NAME'] . '.ini';
$configIniPath = file_exists($hostConfigPath) ? $hostConfigPath : $configDir . 'application.ini';

$apcPresent = function_exists('apc_fetch');
$config = false;

if ($apcPresent && !(isset($_REQUEST['clearcache']) && $_REQUEST['clearcache'] === '1')) {
    $config = apc_fetch(APPLICATION_CACHE_NS . 'applicationConfig');
}

if (!$config) {
    $serverConfig = new Zend_Config_Ini($configIniPath, null, true);
    $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application-common.ini', null, true);
    $config->merge($serverConfig);

    if ($apcPresent) {
        $ttl = isset($config->settings->applicationConfigTtl) ? (int)$config->settings->applicationConfigTtl : 60;
        apc_store(APPLICATION_CACHE_NS . 'applicationConfig', $config, $ttl);
    }
}

if (isset($config->settings->cookie->domain)) {
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params(
        $cookieParams['lifetime'],
        $cookieParams['path'],
        $config->settings->cookie->domain,
        $cookieParams['secure'],
        $cookieParams['httponly']
    );
}

// Config-Registry setzen
Zend_Registry::set('applicationConfig', $config);

// Optional FirePHP-Logging (nur bei Bedarf)
require_once('FirePHP/Init.php');
FirePHP_Init::init();
require_once('FirePHP/Errorhandler.php');

try {
    // Zend-Anwendung initialisieren und starten
    require_once 'Zend/Application.php';
    $application = new Zend_Application(APPLICATION_ENV, $config->{APPLICATION_ENV});
    Zend_Registry::set('Zend_Application', $application);



    $application->bootstrap();

    $application->run();

} catch (Exception $e) {
    throw $e;
}
