<?php

namespace KupShop\ContentBundle\Controller;

use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Views\AlwaysStreamedResponse;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;

class LaunchController extends AbstractController
{
    /**
     * @Route("launch.php")
     */
    public function launchAction(Request $request)
    {
        $response = new AlwaysStreamedResponse(function () use ($request) {
            global $cfg, $dbcfg, $ctrl;

            // Start session to avoid session problems
            $request->getSession()->start();

            if (isset($_GET['s']) && preg_match('/^[-_\.a-zA-Z0-9]+$/', $_GET['s'])) {
                /** @var LoggerInterface $logger */
                $logger = ServiceContainer::getService('logger');
                $logger->error('LaunchController', [
                    'REQUEST_URI' => $_SERVER['REQUEST_URI'],
                ]);

                $script = $_GET['s'].'.php';
            } else {
                throw new NotFoundHttpException();
            }

            if (file_exists($script)) {
                require_once $script;
            } else {
                $script = $cfg['Path']['shared_version'].'web/'.$script;
                if (file_exists($script)) {
                    require_once $script;
                } else {
                    throw new NotFoundHttpException();
                }
            }

            if (!empty($main_class)) {
                /** @var Page $instance */
                $instance = new $main_class();
                $instance->run();
            }
        });

        return $response;
    }
}
