<?php

declare(strict_types=1);

namespace App;

use Nette;
use Nette\Bootstrap\Configurator;


class Bootstrap
{
	private Configurator $configurator;
	private string $rootDir;


	public function __construct()
	{
		$this->rootDir = dirname(__DIR__);
		$this->configurator = new Configurator;
        $this->configurator->setDebugMode(false);
		$this->configurator->setTempDirectory($this->rootDir . '/temp');

	}


	public function bootWebApplication(): Nette\DI\Container
	{
		$this->initializeEnvironment();
		$this->setupContainer();
        $container = $this->configurator->createContainer();

        // ---- globální CORS -----------------------------------------------
        /** @var Nette\Http\Response $http */
        $http = $container->getByType(Nette\Http\Response::class);   // HTTP response
        /** @var Nette\Http\Request $req */
        $req  = $container->getByType(Nette\Http\Request::class);    // HTTP request
        /** @var Nette\Application\Application $app */
        $app  = $container->getByType(Nette\Application\Application::class);

        $app->onResponse[] = function (
            Nette\Application\Application $sender,
            Nette\Application\Response   $response
        ) use ($http, $req): void {
            $origin = $req->getHeader('Origin');   // klientský Origin, může být null
            try {
                if ($origin) {                         // cross‑origin jen když hlavička existuje
                    $http->setHeader('Access-Control-Allow-Origin', $origin);   // „echo‑back“
                    $http->setHeader('Access-Control-Allow-Credentials', 'true');
                    $http->setHeader('Vary', 'Origin');                         // kvůli cache
                }
                $http->setHeader('Access-Control-Allow-Methods',  'GET, POST, PUT, DELETE, OPTIONS');
                $http->setHeader('Access-Control-Allow-Headers',  'Content-Type, Authorization, X-Requested-With');
                $http->setHeader('Access-Control-Max-Age',        '86400');      // 24 h cache
            }catch (Nette\InvalidStateException) {

            }


            // odpověď na pre‑flight
            if ($req->getMethod() === 'OPTIONS') {
                $http->setCode(204); // 204
            }
        };
// -------------------------------------------------------------------


        return $container;
	}


	public function initializeEnvironment(): void
	{
		//$this->configurator->setDebugMode('secret@23.75.345.200'); // enable for your remote IP
		$this->configurator->enableTracy($this->rootDir . '/log');

		$this->configurator->createRobotLoader()
			->addDirectory(__DIR__)
			->register();
	}


	private function setupContainer(): void
	{
		$configDir = $this->rootDir . '/config';
		$this->configurator->addConfig($configDir . '/common.neon');
		$this->configurator->addConfig($configDir . '/services.neon');
	}
}
