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

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

preg_match('#^Bearer (.+)$#', $headers['authorization'] ?? $headers['Authorization'] ?? '', $matches);
if (!count($matches) || $matches[1] != \Configuration::get('MVS_REPORTING_API_CLINICS_KEY')) {
    header('HTTP/1.1 403 Forbidden');
    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');

// Récupération des paramètres de filtres (ids de transporteurs et codes privilèges)
$carrierIdsRaw = $_REQUEST['carrierIds'] ?? [];
$codesPrivileges = $_REQUEST['codesPrivileges'] ?? [];
if (!is_array($carrierIdsRaw) || !is_array($codesPrivileges)) {
    header('HTTP/1.1 400 Bad Request');
    exit(0);
}

// Les ids de transporteurs doivent être des entiers
$carrierIds = array_filter(array_map(fn ($id) => intval($id), $carrierIdsRaw));
if (count($carrierIdsRaw) != count($carrierIds)) {
    header('HTTP/1.1 400 Bad Request');
    exit(0);
}

// Préparation des filtres de requête
$queryFilters = [];

if (count($carrierIds)) {
    $queryFilters[] = '('
        . _DB_PREFIX_ . Clinique::TABLE . '.id_carrier IN (' . implode(', ', $carrierIds) . ')'
        . ' OR ' . _DB_PREFIX_ . Clinique::TABLE . '.id_carrier_home IN (' . implode(', ', $carrierIds) . ')'
        . ')';
}

if (count($codesPrivileges)) {
    $queryFilters[] = _DB_PREFIX_ . Clinique::TABLE . '.code_privilege IN ("' . implode('", "', $codesPrivileges) . '")';
}

$clinics = \Db::getInstance()->executeS(
    'SELECT'
    . ' ' . _DB_PREFIX_ . Clinique::TABLE . '.id_' . Clinique::TABLE . ' as "id"'
    . ', ' . _DB_PREFIX_ . Clinique::TABLE . '.code_privilege as "code_privilege"'
    . ', ' . _DB_PREFIX_ . 'store_lang.name as "name"'
    . ', ' . _DB_PREFIX_ . 'store_lang.address1 as "address1"'
    . ', ' . _DB_PREFIX_ . 'store_lang.address2 as "address2"'
    . ', ' . _DB_PREFIX_ . 'store.postcode as "postcode"'
    . ', ' . _DB_PREFIX_ . 'store.city as "city"'
    . ' FROM ' . _DB_PREFIX_ . Clinique::TABLE
    . ' INNER JOIN ' . _DB_PREFIX_ . 'store ON ' . _DB_PREFIX_ . 'store.id_store=' . _DB_PREFIX_ . Clinique::TABLE . '.id_store'
    . ' INNER JOIN ' . _DB_PREFIX_ . 'store_lang ON ' . _DB_PREFIX_ . 'store_lang.id_store=' . _DB_PREFIX_ . Clinique::TABLE . '.id_store'
    . ' INNER JOIN ' . _DB_PREFIX_ . 'lang ON ' . _DB_PREFIX_ . 'store_lang.id_lang=' . _DB_PREFIX_ . 'lang.id_lang AND ' . _DB_PREFIX_ . 'lang.iso_code="fr"'
    . (count($queryFilters) ? ' WHERE ' . implode(' AND ', $queryFilters) : '')
);

if (!\is_array($clinics)) {
    $clinics = [];
}

header('Content-Type: application/json');
echo \json_encode(
    \array_map(
        function ($clinic) {
            $clinic['id'] = (int) $clinic['id'];

            return $clinic;
        },
        $clinics,
    )
);
