<?php

declare(strict_types=1);
/*
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <contact@prestashop.com>
*  @copyright  2007-2017 PrestaShop SA
*  @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

\header('Access-Control-Allow-Origin: ' . ($headers['origin'] ?? '*'));
\header('Access-Control-Allow-Methods: GET, POST, DELETE, PUT');
\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);
}

\ob_start();

require_once __DIR__ . '/../../../config/config.inc.php';
require_once __DIR__ . '/../classes/OAuthAccessToken.php';
require_once __DIR__ . '/../classes/AppWebserviceRequest.php';

// Cart is needed for some requests
$context = \Context::getContext();
\assert(null !== $context);
$context->cart = new Cart();
$context->currency = new Currency(1);
// TODO : Trouver un moyen pour réactiver le cache
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();
}

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

// set http auth headers for apache+php-cgi work around
if (isset($_SERVER['HTTP_AUTHORIZATION']) && preg_match('/Basic\s+(.*)$/i', $_SERVER['HTTP_AUTHORIZATION'], $matches)) {
    [$name, $password] = explode(':', base64_decode($matches[1]));
    $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
}

// set http auth headers for apache+php-cgi work around if variable gets renamed by apache
if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && preg_match('/Basic\s+(.*)$/i', $_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $matches)) {
    [$name, $password] = explode(':', base64_decode($matches[1]));
    $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
}

// Use for image management (using the POST method of the browser to simulate the PUT method)
$method = $_REQUEST['ps_method'] ?? $_SERVER['REQUEST_METHOD'];

if (isset($_SERVER['PHP_AUTH_USER'])) {
    $key = $_SERVER['PHP_AUTH_USER'];
} elseif (isset($_GET['access_token'])) {
    $key = $_GET['access_token'];
} else {
    header($_SERVER['SERVER_PROTOCOL'] . ' 401 Unauthorized');
    header('WWW-Authenticate: Basic realm="Welcome to PrestaShop Webservice, please enter the authentication key as the login. No password required."');
    exit('401 Unauthorized');
}

// On met un display "full" si on est dans un listing
if (!str_contains($_GET['url'], '/')) {
    $_GET['display'] = 'full';
}

// Par défaut : limite à 10 résultats
if (!isset($_GET['limit'])) {
    $_GET['limit'] = '0,10';
}

$input_xml = null;

// if a XML is in PUT or in POST
if (('PUT' == $_SERVER['REQUEST_METHOD']) || ('POST' == $_SERVER['REQUEST_METHOD'])) {
    $putresource = fopen('php://input', 'r');
    if ($putresource) {
        while ($putData = fread($putresource, 1024)) {
            $input_xml .= $putData;
        }
        fclose($putresource);
    }
}
if (isset($input_xml) && 0 == strncmp($input_xml, 'xml=', 4)) {
    $input_xml = substr($input_xml, 4);
}

$params = $_GET;
unset($params['url']);

$class_name = AppWebserviceRequest::class;
AppWebserviceRequest::$shopIDs = [1];
// fetch the request
WebserviceRequest::$ws_current_classname = $class_name;
$request = call_user_func([$class_name, 'getInstance']);
\assert($request instanceof AppWebserviceRequest);
$bad_class_name = false;

// @phpstan-ignore-next-line
$result = $request->fetch($key, $method, $_GET['url'], $params, $bad_class_name, $input_xml);

// display result
if (0 != ob_get_length()) {
    header('Content-Type: application/javascript');
} // Useful for debug...

// Manage cache
if (isset($_SERVER['HTTP_LOCAL_CONTENT_SHA1']) && $_SERVER['HTTP_LOCAL_CONTENT_SHA1'] == $result['content_sha1']) {
    $result['status'] = $_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified';
}

if (is_array($result['headers'])) {
    foreach ($result['headers'] as $param_value) {
        header($param_value);
    }
}
if (isset($result['type'])) {
    // header($result['content_sha1']);
    if (!isset($_SERVER['HTTP_LOCAL_CONTENT_SHA1']) || $_SERVER['HTTP_LOCAL_CONTENT_SHA1'] != $result['content_sha1']) {
        echo $result['content'];
    }
}
ob_end_flush();
