<?php

use Bitrix\Main\Loader;
use intec\Core;

define('STOP_STATISTICS', true);
define('NO_KEEP_STATISTIC', 'Y');
define('NO_AGENT_STATISTIC', 'Y');
define('DisableEventsCheck', true);
define('BX_SECURITY_SHOW_MESSAGE', true);
define('NOT_CHECK_PERMISSIONS', true);

require_once $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/main/include/prolog_before.php';

if (!Loader::includeModule('intec.core'))
    return;

if (!check_bitrix_sessid())
    return;

Core::setAlias('@intec/template', $_SERVER['DOCUMENT_ROOT'] . SITE_TEMPLATE_PATH . '/classes');

$req = $_REQUEST;
$requestParams = is_array($req['params'] ?? null) ? $req['params'] : [];

$params = [
    'PRODUCT_ID' => (int)($requestParams['PRODUCT_ID'] ?? 0),
    'PRODUCT_QUANTITY_VALUE' => max(1, (int)($req['quantity'] ?? 1)),
    'CITY_ID' => preg_replace('/[^A-Za-z0-9_\-.]/', '', (string)($req['cityID'] ?? '')),
    'USE_BASKET' => ($req['useBasket'] ?? '') === 'y' ? 'Y' : 'N'
];

if ((int)($req['quantity'] ?? 0) > 0)
    $params['PRODUCT_QUANTITY_VALUE'] = max(1, (int)$req['quantity']);

if (!empty($req['cityID'])) {
    $params['CITY_ID'] = preg_replace('/[^A-Za-z0-9_\-.]/', '', (string)$req['cityID']);
    $_SESSION['CATALOG_DELIVERY_CITY_ID'] = $params['CITY_ID'];
}

$allowedTemplates = ['', '.default'];
$componentTemplate = in_array($req['template'] ?? '', $allowedTemplates, true) ? ($req['template'] ?? '') : '';

global $APPLICATION;

$APPLICATION->IncludeComponent(
    'intec.kosmos:catalog.delivery',
    $componentTemplate,
    $params
);
