<?php

use Bitrix\Main\Loader;
use intec\Core;
use intec\core\handling\Handler;
use intec\core\helpers\ArrayHelper;
use intec\core\helpers\Encoding;
use intec\core\helpers\Json;
use intec\core\helpers\Type;

// Проверяем необходимые переменные запроса
if (!isset($_GET['siteId']) || !isset($_GET['templateId'])) {
    http_response_code(404);

    return;
}

$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);

        return;
    }
}

const STOP_STATISTICS = true;

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

$context = \Bitrix\Main\Context::getCurrent();
$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);

    return;
}

$currentSiteId = $siteFromConstant ?? $siteFromContext;

// siteId из GET = LID текущего сайта (ядро или контекст; при обоих — без расхождений)
if ($currentSiteId === null || $currentSiteId === '' || $requestedSiteId !== $currentSiteId) {
    http_response_code(404);

    return;
}

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

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

    return;
}

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

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

    return;
}

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

        return;
    }
}

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

require_once(__DIR__.'/parts/preload.php');

$request = Core::$app->request;
$page = $request->get('page');
$page = Encoding::convert($page, null, Encoding::UTF8);

if (empty($page) && $request->getIsAjax() && $request->getIsPost()) {
    if (!check_bitrix_sessid()) {
        CHTTP::SetStatus('403 Forbidden');
        $response = Encoding::convert([
            'data' => [
                'code' => 'csrf',
                'data' => null,
                'message' => 'CSRF validation failed',
                'status' => 'error'
            ]
        ], Encoding::UTF8, Encoding::getDefault());
        $response = Json::encode($response, 320);
        echo $response;
    }

    $response = [];

    $actions = $request->post('actions');
    $actions = Encoding::convert($actions, null, Encoding::UTF8);
    $handler = new Handler(
        __DIR__.'/ajax',
        'intec\template\ajax'
    );

    if (!Type::isArray($actions))
        $actions = [];

    foreach ($actions as $action) {
        if (!Type::isArray($action)) {
            $response[] = null;
            continue;
        }

        $action = ArrayHelper::merge([
            'name' => null,
            'data' => null
        ], $action);

        if (empty($action['name']) && !Type::isNumeric($action['name'])) {
            $response[] = null;
            continue;
        }

        if (!Type::isArray($action['data']))
            $action['data'] = [];

        $response[] = $handler->handle($action['name'], $action['data']);
    }

    $response = Encoding::convert($response, Encoding::UTF8, Encoding::getDefault());
    $response = Json::encode($response, 320);

    echo $response;
} else if (!empty($page)) {
    if (!check_bitrix_sessid()) {
        CHTTP::SetStatus('403 Forbidden');
        $response = Encoding::convert([
            'data' => [
                'code' => 'csrf',
                'data' => null,
                'message' => 'CSRF validation failed',
                'status' => 'error'
            ]
        ], Encoding::UTF8, Encoding::getDefault());
        $response = Json::encode($response, 320);
        echo $response;
    }

    $data = $request->get();
    $data = Encoding::convert($data, null, Encoding::UTF8);

    unset($data['page']);
    unset($data['siteId']);
    unset($data['templateId']);

    $handler = new Handler(
        __DIR__.'/pages',
        'intec\template\pages'
    );

    $handler->handle($page, $data);
}
