<?php

declare(strict_types=1);

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

$headers = getallheaders();

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

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

\preg_match('#([^/?]+)(:?\?.*)?$#', $_SERVER['REQUEST_URI'], $urlMatches);
if (count($urlMatches) < 2 || !is_string($urlMatches[1])) {
    header('HTTP/1.1 400 Bad Request');
    echo 'Cannot find endpoint in url';
    exit(0);
}

$bearer = \Configuration::get('MVS_REPORTING_API_' . strtoupper($urlMatches[1]) . '_KEY');
if (!$bearer) {
    header('HTTP/1.1 403 Forbidden');
    echo 'No bearer defined for this endpoint';
    exit(0);
}

\preg_match('#^Bearer (.+)$#', $headers['authorization'] ?? $headers['Authorization'] ?? '', $authMatches);
if (count($authMatches) < 2 || !is_string($authMatches[1])) {
    header('HTTP/1.1 403 Forbidden');
    echo 'Bearer is missing';
    exit(0);
}

if ($authMatches[1] != $bearer) {
    header('HTTP/1.1 403 Forbidden');
    echo 'Wrong bearer';
    exit(0);
}

// 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');
