<?php if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) die();

use Bitrix\Iblock\InheritedProperty\ElementValues;
use Bitrix\Iblock\InheritedProperty\SectionValues;
use Bitrix\Main\Loader;
use intec\template\Template;
use Bitrix\Main\Localization\Loc;
use Bitrix\Main\UI\PageNavigation;
use intec\core\helpers\ArrayHelper;
use intec\core\helpers\StringHelper;
use intec\core\helpers\Type;
use intec\core\platform\iblock\Elements;
use intec\core\platform\iblock\ElementsQuery;
use intec\core\platform\iblock\Sections;
use intec\core\platform\iblock\SectionsQuery;
use intec\core\platform\main\File;
use intec\kosmos\enum\settings\{SettingsSystem, SettingsMobile, SettingsMain};
use intec\kosmos\module\settings\{System, Mobile, Main};

if (!Loader::includeModule('iblock')) {
    ShowError(Loc::getMessage('BANNERS_ERROR_MODULE_IBLOCK'));

    return;
}

if (!Loader::includeModule('intec.core')) {
    ShowError(Loc::getMessage('BANNERS_ERROR_MODULE_INTEC_CORE'));

    return;
}

/**
 * Компонент списка баннеров
 * @author Intec
 * @version 1.0.0
 */
class IntecBannersComponent extends CBitrixComponent
{
    /**
     * @inheritdoc
     */
    public function onPrepareComponentParams($arParams)
    {
        if (!Type::isArray($arParams))
            $arParams = [];

        $arParams = ArrayHelper::merge([
            'IBLOCK_TYPE' => null,
            'IBLOCK_ID' => null,
            'MAIN_MODE' => null,
            'IBLOCK_SECTIONS' => [],
            'IBLOCK_LIMIT_ELEMENTS' => null,
            'MOBILE_ITEMS_VIEW' => 'together',
            'ITEM_PICTURE_MODE' => null,
            'PROPERTY_FILTER' => null,
            'PROPERTY_ITEM_PICTURE' => null,
            'URL_LIST' => null,
            'URL_SECTION' => null,
            'URL_DETAIL' => null,
            'SORT_BY' => null,
            'ORDER_BY' => null,
            'CACHE_TYPE' => 'A',
            'CACHE_TIME' => 0,
            'FILTER' => [],
            'NAVIGATION_USE' => 'N',
            'NAVIGATION_ID' => null,
            'NAVIGATION_MODE' => 'DEFAULT',
            'NAVIGATION_ALL' => 'N',
            'NAVIGATION_TEMPLATE' => '.default'
        ], $arParams);

        global $APPLICATION;
        $site = defined('SITE_ID') && SITE_ID ? SITE_ID : ($APPLICATION ? $APPLICATION->GetCurSite() : false);

        if (!Type::isArray($arParams['IBLOCK_SECTIONS']))
            $arParams['IBLOCK_SECTIONS'] = [];
        else
            $arParams['IBLOCK_SECTIONS'] = array_filter($arParams['IBLOCK_SECTIONS']);

        if (!Type::isArray($arParams['FILTER']))
            $arParams['FILTER'] = [];
        else
            $arParams['FILTER'] = array_filter($arParams['FILTER']);

        $arParams['MAIN_MODE'] = ArrayHelper::fromRange([
            'ID',
            'CODE'
        ], $arParams['MAIN_MODE']);
        $arParams['ITEM_PICTURE_MODE'] = ArrayHelper::fromRange([
            'PREVIEW',
            'DETAIL',
            'PROPERTY'
        ], $arParams['ITEM_PICTURE_MODE']);
        $arParams['ORDER_BY'] = ArrayHelper::fromRange([
            'ASC',
            'DESC'
        ], $arParams['ORDER_BY']);

        if ($arParams['ITEM_PICTURE_MODE'] === 'PROPERTY' && empty($arParams['PROPERTY_ITEM_PICTURE']))
            $arParams['ITEM_PICTURE_MODE'] = 'PREVIEW';

        if (empty($arParams['SORT_BY']))
            $arParams['SORT_BY'] = 'SORT';

        if (Loader::includeModule('intec.digital2')) {
            if (($arParams['LAZYLOAD_USE'] ?? null) === 'GLOBAL' && class_exists(System::class) && class_exists(SettingsSystem::class)) {
                $lazyLoad = System::getOption(SettingsSystem::ImageLazyLoad, $site);
                $arParams['LAZYLOAD_USE'] = $lazyLoad ? 'Y' : 'N';
            } else {
                $arParams['LAZYLOAD_USE'] = 'N';
            }
            if (($arParams['USER_CONSENT'] ?? null) === 'GLOBAL') {
                $arParams['USER_CONSENT'] = System::getOption(SettingsSystem::Consent, $site) ? 'Y' : 'N';
            } else {
                $arParams['USER_CONSENT'] = $arParams['USER_CONSENT'] ?: 'N';
            }
            if (($arParams['USER_MAILING'] ?? null) === 'GLOBAL') {
                $arParams['USER_MAILING'] = System::getOption(SettingsSystem::Mailing, $site) ? 'Y' : 'N';
            } else {
                $arParams['USER_MAILING'] = $arParams['USER_MAILING'] ?: 'N';
            }
            if (($arParams['MOBILE_ITEMS_VIEW'] ?? null) === 'global' && class_exists(Mobile::class) && class_exists(SettingsMobile::class)) {
                $mobileView = Mobile::getOption(SettingsMobile::BannerContentLayout, $site);
                $arParams['MOBILE_ITEMS_VIEW'] = $mobileView;
            } else {
                $arParams['MOBILE_ITEMS_VIEW'] = 'together';
            }
            if (class_exists(Main::class) && class_exists(SettingsMain::class)) {
                // Миграция настройки баннера
                $bannerView = Main::getOption(SettingsMain::BannerView, $site);

                if (!empty($bannerView) && preg_match('/^template\.(\d+)$/', $bannerView, $matches)) {
                    $bannerView = 'standard_' . $matches[1];
                    $arParams['ITEMS_VIEW_GLOBAL'] = $bannerView;
                }

                if (($arParams['MAIN_HEIGHT'] ?? null) === 'GLOBAL') {
                    $bannerHeight = Main::getOption(SettingsMain::BannerHeight, $site);
                    if (!empty($bannerHeight)) {
                        $arParams['MAIN_HEIGHT'] = $bannerHeight;
                    }
                } else {
                    $arParams['MAIN_HEIGHT'] = 600;
                }

                if (($arParams['ADDITIONAL_BANNERS_BOTTOM_SHOW'] ?? null) === 'GLOBAL') {
                    // Миграция настройки нижних баннеров
                    if (!empty($bannerView) && preg_match('/^standard_(\d+)$/', $bannerView, $matches)) {
                        $templateNumber = (int)$matches[1];

                        // Маппинг номеров шаблонов на enum cases
                        $bottomBannersSetting = match($templateNumber) {
                            1 => SettingsMain::BannerTemplate1BottomBannersUse,
                            2 => SettingsMain::BannerTemplate2BottomBannersUse,
                            3 => SettingsMain::BannerTemplate3BottomBannersUse,
                            4 => SettingsMain::BannerTemplate4BottomBannersUse,
                            5 => SettingsMain::BannerTemplate5BottomBannersUse,
                            default => null
                        };

                        if ($bottomBannersSetting !== null) {
                            $bottomBannersUse = Main::getOption($bottomBannersSetting, $site);
                            $arParams['ADDITIONAL_BANNERS_BOTTOM_SHOW'] = $bottomBannersUse ? 'Y' : 'N';
                        }
                    }
                } else {
                    $arParams['ADDITIONAL_BANNERS_BOTTOM_SHOW'] = 'N';
                }


                if (($arParams['ADDITIONAL_BANNERS_LEFT_SHOW'] ?? null) === 'GLOBAL') {
                    // Миграция настройки левых баннеров
                    if (!empty($bannerView) && preg_match('/^standard_(\d+)$/', $bannerView, $matches)) {
                        $templateNumber = (int)$matches[1];

                        // Маппинг номеров шаблонов на enum cases
                        $leftBannersSetting = match ($templateNumber) {
                            2 => SettingsMain::BannerTemplate2LeftBannersUse,
                            default => null
                        };

                        if ($leftBannersSetting !== null) {
                            $leftBannersUse = Main::getOption($leftBannersSetting, $site);
                            $arParams['ADDITIONAL_BANNERS_LEFT_SHOW'] = $leftBannersUse ? 'Y' : 'N';
                        }
                    }
                } else {
                    $arParams['ADDITIONAL_BANNERS_LEFT_SHOW'] = 'N';
                }

                if (($arParams['ADDITIONAL_BANNERS_RIGHT_SHOW'] ?? null) === 'GLOBAL') {
                    // Миграция настройки левых баннеров
                    if (!empty($bannerView) && preg_match('/^standard_(\d+)$/', $bannerView, $matches)) {
                        $templateNumber = (int)$matches[1];

                        // Маппинг номеров шаблонов на enum cases
                        $rightBannersSetting = match ($templateNumber) {
                            2 => SettingsMain::BannerTemplate2RightBannersUse,
                            default => null
                        };

                        if ($rightBannersSetting !== null) {
                            $rightBannersUse = Main::getOption($rightBannersSetting, $site);
                            $arParams['ADDITIONAL_BANNERS_RIGHT_SHOW'] = $rightBannersUse ? 'Y' : 'N';
                        }
                    }
                } else {
                    $arParams['ADDITIONAL_BANNERS_RIGHT_SHOW'] = 'N';
                }

                // Миграция настройки правых баннеров
                if (!empty($bannerView) && preg_match('/^standard_(\d+)$/', $bannerView, $matches)) {
                    $templateNumber = (int)$matches[1];

                    // Маппинг номеров шаблонов на enum cases
                    $paddingSetting = match($templateNumber) {
                        1 => SettingsMain::BannerTemplate1PaddingUse,
                        2 => SettingsMain::BannerTemplate2PaddingUse,
                        3 => SettingsMain::BannerTemplate3PaddingUse,
                        4 => SettingsMain::BannerTemplate4PaddingUse,
                        default => null
                    };

                    if (
                        $arParams['ADDITIONAL_BANNERS_LEFT_SHOW'] === 'Y' ||
                        $arParams['ADDITIONAL_BANNERS_RIGHT_SHOW'] === 'Y' ||
                        $arParams['ADDITIONAL_BANNERS_BOTTOM_SHOW'] === 'Y'
                    ) {
                        if ($paddingSetting !== null && ($arParams['ADDITIONAL_BANNERS_PADDING'] ?? null) === 'GLOBAL') {
                            $arParams['ADDITIONAL_BANNERS_PADDING'] = Main::getOption($paddingSetting, $site) ? 'Y' : 'N';
                        } else {
                            $arParams['ADDITIONAL_BANNERS_PADDING'] = 'N';
                        }
                    }
                    if (($arParams['BANNER_PADDING'] ?? null) === 'GLOBAL') {
                        if ($paddingSetting !== null) {
                            $arParams['BANNER_PADDING'] = Main::getOption($paddingSetting, $site) ? 'Y' : 'N';
                        }
                    } else {
                        $arParams['BANNER_PADDING'] = 'N';
                    }
                }
            }
        }

        return $arParams;
    }

    /**
     * @inheritdoc
     */
    public function executeComponent()
    {
        if (empty($this->arParams['IBLOCK_ID'])) {
            echo $this->generateErrorMessage(Loc::getMessage('BANNERS_ERROR_IBLOCK_NULL'));

            return null;
        }
        
        $this->arResult = [
            'ITEMS' => new Elements(),
            'SECTIONS' => new Sections(),
            'NAVIGATION' => $this->setNavigation()
        ];
        
        if ($this->startResultCache(false, $this->generateCacheId())) {
            $itemsQuery = (new ElementsQuery())
                ->setUseTilda(false)
                ->setWithProperties(true)
                ->setIBlockType($this->arParams['IBLOCK_TYPE'])
                ->setIBlockId($this->arParams['IBLOCK_ID'])
                ->setLimit($this->arResult['NAVIGATION']['PAGE']['SIZE'])
                ->setOffset($this->arResult['NAVIGATION']['PAGE']['CURRENT'])
                ->setFilter([
                    'ACTIVE' => 'Y',
                    'ACTIVE_DATE' => 'Y',
                    'CHECK_PERMISSIONS' => 'Y',
                    'MIN_PERMISSION' => 'R'
                ])
                ->setSort([
                    $this->arParams['SORT_BY'] => $this->arParams['ORDER_BY']
                ])
                ->setIBlockUrlTemplates(
                    $this->arParams['URL_LIST'],
                    $this->arParams['URL_SECTION'],
                    $this->arParams['URL_DETAIL']
                );

            if (!empty($this->arParams['IBLOCK_SECTIONS']))
                $itemsQuery->extendFilter([
                    'SECTION_GLOBAL_ACTIVE' => 'Y'
                ]);

            if ($this->arParams['MAIN_MODE'] === 'CODE')
                $itemsQuery->setSectionsCode($this->arParams['IBLOCK_SECTIONS']);
            else
                $itemsQuery->setSectionsId($this->arParams['IBLOCK_SECTIONS']);

            if (!empty($this->arParams['PROPERTY_FILTER']))
                $itemsQuery->extendFilter([
                    '!PROPERTY_' . $this->arParams['PROPERTY_FILTER'] => false
                ]);

            $itemsQuery->extendFilter($this->arParams['FILTER']);
            $itemsQuery = $itemsQuery->execute();

            if (!$itemsQuery->isEmpty()) {
                $itemsPictures = $itemsQuery->getFiles([
                    'PREVIEW_PICTURE',
                    'DETAIL_PICTURE'
                ], [
                    $this->arParams['PROPERTY_ITEM_PICTURE']
                ]);

                foreach ($itemsQuery as $item) {
                    $item['PICTURE'] = new File();
                    $itemSeo = new ElementValues($this->arParams['IBLOCK_ID'], $item['ID']);

                    if ($itemsPictures->exists($item['PREVIEW_PICTURE'])) {
                        $picture = $itemsPictures->get($item['PREVIEW_PICTURE']);
                        $picture['ALT'] = $itemSeo->getValue('ELEMENT_PREVIEW_PICTURE_FILE_ALT');
                        $picture['TITLE'] = $itemSeo->getValue('ELEMENT_PREVIEW_PICTURE_FILE_TITLE');
                        $item['PREVIEW_PICTURE'] = $picture;

                        if ($this->arParams['ITEM_PICTURE_MODE'] === 'PREVIEW')
                            $item['PICTURE'] = $item['PREVIEW_PICTURE'];

                        unset($picture);
                    } else {
                        $item['PREVIEW_PICTURE'] = new File();
                    }

                    if ($itemsPictures->exists($item['DETAIL_PICTURE'])) {
                        $picture = $itemsPictures->get($item['DETAIL_PICTURE']);
                        $picture['ALT'] = $itemSeo->getValue('ELEMENT_DETAIL_PICTURE_FILE_ALT');
                        $picture['TITLE'] = $itemSeo->getValue('ELEMENT_DETAIL_PICTURE_FILE_TITLE');
                        $item['DETAIL_PICTURE'] = $picture;

                        if ($this->arParams['ITEM_PICTURE_MODE'] === 'DETAIL')
                            $item['PICTURE'] = $item['DETAIL_PICTURE'];

                        unset($picture);
                    } else {
                        $item['DETAIL_PICTURE'] = new File();
                    }

                    if ($this->arParams['ITEM_PICTURE_MODE'] === 'PROPERTY') {
                        if ($item->getProperties()->exists($this->arParams['PROPERTY_ITEM_PICTURE'])) {
                            $propertyPicture = $item->getProperties()->get($this->arParams['PROPERTY_ITEM_PICTURE']);

                            if (!empty($propertyPicture['VALUE']) && $itemsPictures->exists($propertyPicture['VALUE'])) {
                                $picture = $itemsPictures->get($propertyPicture['VALUE']);
                                $picture['ALT'] = $item->getName();
                                $picture['TITLE'] = $item->getName();
                                $propertyPicture['VALUE'] = $picture;
                                $item['PICTURE'] = $propertyPicture['VALUE'];

                                unset($picture);
                            }

                            unset($propertyPicture);
                        }
                    }

                    unset($item, $itemSeo);
                }

                unset($itemsPictures);

                if (!empty($this->arParams['IBLOCK_SECTIONS'])) {
                    $sectionsQuery = (new SectionsQuery())
                        ->setUseTilda(false)
                        ->setIBlockType($this->arParams['IBLOCK_TYPE'])
                        ->setIBlockType($this->arParams['IBLOCK_TYPE'])
                        ->setIBlockId($this->arParams['IBLOCK_ID'])
                        ->setFilter([
                            'ACTIVE' => 'Y',
                            'GLOBAL_ACTIVE' => 'Y',
                            'CHECK_PERMISSIONS' => 'Y',
                            'MIN_PERMISSION' => 'R'
                        ])
                        ->setSort([
                            $this->arParams['SORT_BY'] => $this->arParams['ORDER_BY']
                        ])
                        ->setIBlockUrlTemplates(
                            $this->arParams['URL_LIST'],
                            $this->arParams['URL_SECTION']
                        );

                    if ($this->arParams['MAIN_MODE'] === 'CODE')
                        $sectionsQuery->setSectionsCode($this->arParams['IBLOCK_SECTIONS']);
                    else
                        $sectionsQuery->setSectionsId($this->arParams['IBLOCK_SECTIONS']);

                    $sectionsQuery = $sectionsQuery->execute();

                    if (!$sectionsQuery->isEmpty()) {
                        $sectionsPictures = $sectionsQuery->getFiles();

                        foreach ($sectionsQuery as $section) {
                            $section['ITEMS'] = new Elements();
                            $sectionSeo = new SectionValues($this->arParams['IBLOCK_ID'], $section['ID']);

                            if ($sectionsPictures->exists($section['PICTURE'])) {
                                $picture = $sectionsPictures->get($section['PICTURE']);
                                $picture['ALT'] = $sectionSeo->getValue('SECTION_PICTURE_FILE_ALT');
                                $picture['TITLE'] = $sectionSeo->getValue('SECTION_PICTURE_FILE_TITLE');
                                $section['PICTURE'] = $picture->asArray();

                                unset($picture);
                            } else {
                                $section['PICTURE'] = new File();
                            }

                            if ($sectionsPictures->exists($section['DETAIL_PICTURE'])) {
                                $picture = $sectionsPictures->get($section['DETAIL_PICTURE']);
                                $picture['ALT'] = $sectionSeo->getValue('SECTION_DETAIL_PICTURE_FILE_ALT');
                                $picture['TITLE'] = $sectionSeo->getValue('SECTION_DETAIL_PICTURE_FILE_TITLE');
                                $section['DETAIL_PICTURE'] = $picture->asArray();

                                unset($picture);
                            } else {
                                $section['DETAIL_PICTURE'] = new File();
                            }

                            unset($section, $sectionSeo);
                        }

                        unset($sectionPictures);

                        foreach ($itemsQuery as $item) {
                            /** @var Elements $sectionItems */

                            if (!$sectionsQuery->exists($item['IBLOCK_SECTION_ID']))
                                continue;

                            $section = $sectionsQuery->get($item['IBLOCK_SECTION_ID']);
                            $sectionItems = $section['ITEMS'];
                            $sectionItems->set($item['ID'], $item);

                            unset($item, $section, $sectionItems);
                        }
                    }

                    $this->arResult['SECTIONS'] = $sectionsQuery;

                    unset($sectionsQuery);
                }
            }

            $this->arResult['ITEMS'] = $itemsQuery;

            if ($this->arResult['ITEMS']->isEmpty()) {
                echo $this->generateErrorMessage(Loc::getMessage('BANNERS_ERROR_ITEMS_NULL'));
            }

            unset($itemsQuery);

            $this->includeComponentTemplate();
        }

        return null;
    }

    /**
     * Распечатывает переданные данные на странице в удобном формате
     * @param mixed $data Данные для печати
     * @param bool $dump Печатать с указанием типов данных
     */
    public function print($data, $dump = false)
    {
        echo '<pre>';
        $dump ? var_dump($data) : print_r($data);
        echo '</pre>';
    }

    /**
     * Возвращает уникальный массив-идентификатор для кеширования
     * @return array Идентификатор для кеширования
     */
    protected function generateCacheId()
    {
        global $USER;

        $result = [
            $USER->GetGroups(),
            $this->arResult['NAVIGATION'],
            $this->arParams['MOBILE_ITEMS_VIEW'],
            $this->arParams['ITEMS_VIEW_GLOBAL'],
            $this->arParams['HEIGHT'],
            $this->arParams['LAZYLOAD_USE'],
            $this->arParams['WIDE'],
            $this->arParams['ADDITIONAL_BANNERS_BOTTOM_SHOW'],
            $this->arParams['ADDITIONAL_BANNERS_LEFT_SHOW'],
            $this->arParams['ADDITIONAL_BANNERS_RIGHT_SHOW'],
            $this->arParams['ADDITIONAL_BANNERS_PADDING'],
            $this->arParams['BANNER_PADDING'],
        ];

        return $result;
    }

    /**
     * Генератор сообщений об ошибках
     * @param string $message Текст сообщения
     * @return string Сообщение
     */
    protected function generateErrorMessage($message)
    {
        return StringHelper::replaceMacros(Loc::getMessage('BANNERS_ERROR_TEMPLATE'), [
            'COMPONENT' => $this->getName(),
            'TEMPLATE' => $this->getTemplateName(),
            'MESSAGE' => $message
        ]);
    }
    
    /**
     * Возвращает постраничную навигацию
     * @return array Навигация
     */
    protected function setNavigation()
    {
        $navigation = [
            'USE' => $this->arParams['NAVIGATION_USE'] === 'Y',
            'ID' => $this->arParams['NAVIGATION_ID'],
            'MODE' => ArrayHelper::fromRange([
                'DEFAULT',
                'AJAX'
            ], $this->arParams['NAVIGATION_MODE']),
            'ALL' => $this->arParams['NAVIGATION_ALL'] !== 'Y',
            'TEMPLATE' => $this->arParams['NAVIGATION_TEMPLATE'],
            'PAGE' => [
                'SIZE' => Type::toInteger($this->arParams['IBLOCK_LIMIT_ELEMENTS']),
                'CURRENT' => 0,
                'COUNT' => 0
            ],
            'ITEMS' => 0,
            'PRINT' => null
        ];

        if ($navigation['USE'] && empty($navigation['ID']))
            $navigation['USE'] = false;

        if ($navigation['PAGE']['SIZE'] < 1)
            $navigation['USE'] = false;

        if ($navigation['USE']) {
            global $APPLICATION;

            $object = new PageNavigation($navigation['ID']);
            $object->setPageSize($navigation['PAGE']['SIZE'])
                ->setRecordCount($this->getNavigationCount())
                ->allowAllRecords($navigation['ALL'])
                ->initFromUri();

            if ($object->getCurrentPage() > $object->getPageCount())
                $object->setCurrentPage($object->getPageCount());

            $navigation['PAGE']['CURRENT'] = $object->getCurrentPage();
            $navigation['PAGE']['COUNT'] = $object->getPageCount();

            if ($object->allRecordsShown())
                $navigation['PAGE']['SIZE'] = $object->getRecordCount();
            else
                $navigation['PAGE']['SIZE'] = $object->getPageSize();

            $navigation['ITEMS'] = $object->getRecordCount();

            if ($object->getPageCount() < 2 && !$object->allRecordsShown())
                $navigation['USE'] = false;

            if ($navigation['PAGE']['COUNT'] > 1 || $object->allRecordsShown()) {
                ob_start();

                $APPLICATION->IncludeComponent(
                    'bitrix:main.pagenavigation',
                    $navigation['TEMPLATE'],
                    [
                        'NAV_OBJECT' => $object,
                        'SEF_MODE' => 'N'
                    ],
                    $this
                );

                $navigation['PRINT'] = ob_get_contents();

                ob_end_clean();
            }

            unset($object);
        }

        return $navigation;
    }

    /**
     * Возвращает общее количество элементов выборки для постраничной навигации
     * @return int Количество элементов выборки
     */
    protected function getNavigationCount()
    {
        $navigationFilter = [
            'IBLOCK_TYPE' => $this->arParams['IBLOCK_TYPE'],
            'IBLOCK_ID' => $this->arParams['IBLOCK_ID'],
            'ACTIVE' => 'Y',
            'ACTIVE_DATE' => 'Y',
            'CHECK_PERMISSIONS' => 'Y',
            'MIN_PERMISSION' => 'R'
        ];

        if (!empty($this->arParams['IBLOCK_SECTIONS'])) {
            $navigationFilter['SECTION_GLOBAL_ACTIVE'] = 'Y';

            if ($this->arParams['MAIN_MODE'] === 'CODE')
                $navigationFilter['SECTION_CODE'] = $this->arParams['IBLOCK_SECTIONS'];
            else
                $navigationFilter['SECTION_ID'] = $this->arParams['IBLOCK_SECTIONS'];
        }

        if (!empty($this->arParams['PROPERTY_FILTER']))
            $navigationFilter['!=PROPERTY_' . $this->arParams['PROPERTY_FILTER']] = false;

        $navigationFilter = ArrayHelper::merge($navigationFilter, $this->arParams['FILTER']);

        return Type::toInteger(CIBlockElement::GetList(
            [$this->arParams['SORT_BY'] => $this->arParams['ORDER_BY']],
            $navigationFilter,
            [],
            false,
            ['ID']
        ));
    }
}