<?php

declare(strict_types=1);

$headers = \getallheaders();

\header('Access-Control-Allow-Origin: ' . ($headers['origin'] ?? '*'));
\header('Access-Control-Allow-Methods: GET');
\header('Access-Control-Allow-Headers: X-Requested-With, Content-Type, Authorization, Origin, Accept');
\header('Access-Control-Allow-Credentials: true');

if ('OPTIONS' == $_SERVER['REQUEST_METHOD']) {
    exit(0);
}

require_once __DIR__ . '/../../../../config/config.inc.php';

// Cart is needed for some requests
$context = Context::getContext();

if (null === $context) {
    \header('HTTP/1.1 500 Internal Server Error');
    exit(0);
}

$context->cart = new Cart();
$context->currency = new Currency(1);
$context->cookie->disallowWriting();
Db::getInstance()->disableCache();

// Initialisation du container
global $kernel;
if (!$kernel) {
    require_once _PS_ROOT_DIR_ . '/app/AppKernel.php';
    $kernel = new AppKernel('prod', false);
    $kernel->boot();
}

// Chargement du module clinique
Module::getInstanceByName('myvetshopclinique');

$container = PrestaShop\PrestaShop\Adapter\SymfonyContainer::getInstance();

\assert($container !== null);

try {
    /** @var Myvetshop\Module\Clinique\Controller\Api\EventsGetAllController $controller */
    $controller = $container->get(Myvetshop\Module\Clinique\Controller\Api\EventsGetAllController::class);

    /** @var Symfony\Component\HttpFoundation\Response $response */
    $response = $controller(Symfony\Component\HttpFoundation\Request::createFromGlobals());
} catch (Symfony\Component\HttpKernel\Exception\HttpException $e) {
    $response = new Symfony\Component\HttpFoundation\Response($e->getMessage(), $e->getStatusCode());
} catch (Exception $e) {
    $response = new Symfony\Component\HttpFoundation\Response($e->getMessage(), 500);
}

$response->headers->add([
    'Access-Control-Allow-Origin' => ($headers['origin'] ?? '*'),
    'Access-Control-Allow-Methods' => 'GET',
    'Access-Control-Allow-Headers' => 'X-Requested-With, Content-Type, Authorization, Origin, Accept',
    'Access-Control-Allow-Credentials' => 'true',
]);

$response->send();
exit(0);
