<?php
use Bitrix\Main\Loader;
use Bitrix\Main\DI\ServiceLocator;
use Mibazarow\Bxstore\Service\CatalogSortService;

if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) {
    die();
}

class CatalogSortComponent extends CBitrixComponent
{
    public function onPrepareComponentParams($arParams)
    {
        $arParams['SORT_FIELD'] = (string)($arParams['SORT_FIELD'] ?? 'id');
        $arParams['SORT_ORDER'] = (string)($arParams['SORT_ORDER'] ?? 'desc');
        $arParams['CATALOG_PARAMS'] = $arParams['CATALOG_PARAMS'] ?? [];
        $arParams['COMPONENT_TEMPLATE'] = (string)($arParams['COMPONENT_TEMPLATE'] ?? 'bulletins');

        return $arParams;
    }

    public function executeComponent()
    {
        if (!Loader::includeModule('mibazarow.bxstore')) {
            ShowError('Модуль mibazarow.bxstore не установлен');

            return;
        }

        /** @var CatalogSortService $sortService */
        $sortService = ServiceLocator::getInstance()->get(CatalogSortService::class);
        $currentSort = $sortService->getSort();

        $this->arResult = [
            'CURRENT_FIELD' => $currentSort['field'],
            'CURRENT_ORDER' => $currentSort['order'],
            'SORT_FIELD' => $this->arParams['SORT_FIELD'] ?? 'id',
            'SORT_ORDER' => $this->arParams['SORT_ORDER'] ?? 'desc',
            'CATALOG_PARAMS' => $this->arParams['CATALOG_PARAMS'] ?? [],
            'COMPONENT_PATH' => $this->arParams['COMPONENT_PATH'] ?? '',
        ];

        $this->includeComponentTemplate();
    }
}