<?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_CLINIQUES_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) . '")';
}

// Construction de la requête
$query = 'SELECT'
    . ' ' . _DB_PREFIX_ . Clinique::TABLE . '.code_privilege as "code_privilege"'
    . ', ' . _DB_PREFIX_ . 'store_lang.name as "clinique"'
    . ', ' . _DB_PREFIX_ . 'store_lang.address1 as "address1"'
    . ', ' . _DB_PREFIX_ . 'store_lang.address2 as "address2"'
    . ', ' . _DB_PREFIX_ . 'store.postcode as "cp"'
    . ', ' . _DB_PREFIX_ . 'store.city as "city"'
    . ', ' . _DB_PREFIX_ . Clinique::TABLE . '.id_carrier as "id_carrier"'
    . ', ' . _DB_PREFIX_ . Clinique::TABLE . '.id_carrier_home as "id_carrier_home"'
    . ' 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'
    . (count($queryFilters) ? ' WHERE ' . implode(' AND ', $queryFilters) : '')
    . ';';

header('Content-Type: application/json');
echo json_encode(\Db::getInstance()->executeS($query));
