<?php

use Bitrix\Main\Security\Sign\BadSignatureException;
use Bitrix\Main\Security\Sign\Signer;
use intec\Core;

const STOP_STATISTICS = true;
const NO_KEEP_STATISTIC = 'Y';
const NO_AGENT_STATISTIC = 'Y';
const DisableEventsCheck = true;
const BX_SECURITY_SHOW_MESSAGE = true;
const NOT_CHECK_PERMISSIONS = true;

if (!isset($_GET['siteId']) || !isset($_GET['templateId'])) {
    http_response_code(404);

    die();
}

$requestedSiteId = trim((string)$_GET['siteId']);
$requestedTemplateId = trim((string)$_GET['templateId']);

foreach ([$requestedSiteId, $requestedTemplateId] as $requestedSegment) {
    if ($requestedSegment === ''
        || mb_strlen($requestedSegment) > 64
        || !preg_match('/^[a-zA-Z0-9_.-]+$/', $requestedSegment)) {
        http_response_code(404);

        die();
    }
}

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

$context = \Bitrix\Main\Context::getCurrent();

if (!check_bitrix_sessid() || !$context?->getRequest()?->isAjaxRequest()) {
    http_response_code(403);

    die();
}

$ctxLid = $context?->getSite();
$siteFromContext = ($ctxLid !== null && $ctxLid !== '') ? $ctxLid : null;
$siteFromConstant = (defined('SITE_ID') && (string)SITE_ID !== '') ? (string)SITE_ID : null;

if ($siteFromContext !== null && $siteFromConstant !== null && $siteFromContext !== $siteFromConstant) {
    http_response_code(404);

    die();
}

$currentSiteId = $siteFromConstant ?? $siteFromContext;

if ($currentSiteId === null || $currentSiteId === '' || $requestedSiteId !== $currentSiteId) {
    http_response_code(404);

    die();
}

$siteRow = \Bitrix\Main\SiteTable::getRow([
    'filter' => [
        '=LID' => $requestedSiteId,
        '=ACTIVE' => 'Y',
    ],
    'select' => ['LID'],
]);

if ($siteRow === null) {
    http_response_code(404);

    die();
}

$templateRow = \Bitrix\Main\SiteTemplateTable::getRow([
    'filter' => [
        '=SITE_ID' => $requestedSiteId,
        '=TEMPLATE' => $requestedTemplateId,
    ],
    'select' => ['ID'],
]);

if ($templateRow === null) {
    http_response_code(404);

    die();
}

foreach (['SITE_ID' => $requestedSiteId, 'SITE_TEMPLATE_ID' => $requestedTemplateId] as $name => $value) {
    if (!defined($name)) {
        define($name, $value);
    } elseif ((string)constant($name) !== $value) {
        http_response_code(404);

        die();
    }
}

CModule::IncludeModule('intec.core');

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

$signer = new Signer();

try {
    $params = unserialize(
        base64_decode($signer->unsign((string)$_REQUEST['parameters'], 'catalog.delivery')),
        ['allowed_classes' => false]
    );
    $componentTemplate = $signer->unsign((string)$_REQUEST['template'], 'catalog.delivery');
} catch (BadSignatureException $e) {
    http_response_code(403);

    die();
}

if (!is_array($params))
    $params = [];

if (!empty($_REQUEST['cityID'])) {
    $params['CITY_ID'] = (string)$_REQUEST['cityID'];
    $_SESSION['CATALOG_DELIVERY_CITY_ID'] = (string)$_REQUEST['cityID'];
}

if ((int)$_REQUEST['quantity'] > 0)
    $params['PRODUCT_QUANTITY_VALUE'] = (int)$_REQUEST['quantity'];

$params['USE_BASKET'] = ($_REQUEST['useBasket'] == 'y') ? 'Y' : 'N';

global $APPLICATION;

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