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

$productCategories = \Db::getInstance()->executeS(
    'SELECT'
    . ' ' . _DB_PREFIX_ . 'category.id_category as "id"'
    . ', ' . _DB_PREFIX_ . 'category_lang.name as "name"'
    . ', ' . _DB_PREFIX_ . 'category.id_parent as "id_parent"'
    . ', ' . _DB_PREFIX_ . 'category.level_depth as "level_depth"'
    . ', ' . _DB_PREFIX_ . 'category.active as "active"'
    . ' FROM ' . _DB_PREFIX_ . 'category'
    . ' INNER JOIN ' . _DB_PREFIX_ . 'category_lang ON ' . _DB_PREFIX_ . 'category_lang.id_category = ' . _DB_PREFIX_ . 'category.id_category'
    . ' INNER JOIN ' . _DB_PREFIX_ . 'lang ON ' . _DB_PREFIX_ . 'category_lang.id_lang=' . _DB_PREFIX_ . 'lang.id_lang AND ' . _DB_PREFIX_ . 'lang.iso_code="fr"'
    . ';'
);

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

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

            return $category;
        },
        $productCategories,
    )
);
