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

use Bitrix\Main\Data\Cache;
use intec\Core;
use intec\core\helpers\ArrayHelper;
use intec\core\helpers\StringHelper;
use intec\core\helpers\Type;
use intec\core\bitrix\iblock\ElementsQuery;

/**
 * @var array $arParams
 * @var array $arVisual
 * @var CAllMain $APPLICATION
 */

$arYears = [];
$arFilter = [];
$sVariable = 'year';
$arValues = Core::$app->request->get();

if (!empty($arValues[$sVariable])) {
    $arValues[$sVariable] = trim(strip_tags($arValues[$sVariable]));
}

$sDatePrefix = 'DATE_';
$sDateType = ArrayHelper::getValue($arParams, 'LIST_DATE_TYPE');

if (empty($sDateType))
    $sDateType = 'DATE_CREATE';

if (!empty($arValues[$sVariable])) {
    $sDateFormat = CDatabase::DateFormatToPHP(CSite::GetDateFormat('SHORT'));

    $arFilter = [
        '>='.$sDateType => date($sDateFormat, strtotime($arValues[$sVariable].'-01-01')),
        '<='.$sDateType => date($sDateFormat, strtotime($arValues[$sVariable].'-12-31')),
    ];

    unset($sDateFormat);
}

$oCache = Cache::createInstance();

if ($oCache->initCache(360000, $arParams['IBLOCK_ID'], '/iblock/lookbook')) {
    $arYears = $oCache->getVars();
} else {
    $oElements = new ElementsQuery();
    $oElements->setSort(['SORT' => 'ASC']);
    $oElements->setFilter([
        'IBLOCK_ID' => $arParams['IBLOCK_ID'],
        'ACTIVE' => 'Y',
        'ACTIVE_DATE' => 'Y',
        'CHECK_PERMISSIONS' => 'Y',
        'MIN_PERMISSION' => 'R'
    ]);
    $oElements->setWithProperties(false);
    $arItems = $oElements->execute();

    if ($arItems->isEmpty())
        return;

    if ($sDateType === 'DATE_ACTIVE_FROM' || $sDateType === 'DATE_ACTIVE_TO')
        $sDateType = StringHelper::cut($sDateType, StringHelper::length($sDatePrefix));

    $arYearsTemp = $arItems->asArray(function ($key, $arValue) use (&$sDateType) {
        if (empty($arValue[$sDateType]))
            return ['skip' => true];

        $arDate = StringHelper::explode($arValue[$sDateType], ' ');
        $arDate = ArrayHelper::getFirstValue($arDate);

        if (empty($arDate))
            return ['skip' => true];

        $arDate = StringHelper::explode($arDate, '.');
        $sYear = Type::toInteger(ArrayHelper::getValue($arDate, 2));

        if (empty($sYear))
            return ['skip' => true];

        return [
            'key' => $key,
            'value' => $sYear
        ];
    });

    unset($arItems);

    if (!empty($arYearsTemp)) {

        $arYears = array_unique($arYearsTemp);

        usort($arYears, function ($sYear1, $sYear2) {
            if ($sYear1 > $sYear2)
                return -1;

            if ($sYear1 < $sYear2)
                return 1;

            return 0;
        });
    }

    unset($arYearsTemp);

    $arYearList = [
        'FIRST' => $arValues[$sVariable] != $arYears[0] ? $arYears[0] : null,
        'PREV' => [
            'DOTS' => false,
            'VALUE' => null,
        ],
        'CURRENT' => $arValues[$sVariable],
        'NEXT' => [
            'DOTS' => false,
            'VALUE' => null
        ],
        'LAST' => $arValues[$sVariable] != $arYears[count($arYears) - 1] ? $arYears[count($arYears) - 1] : null,
        'LIST' => [
            'SHOW' => false,
            'VALUES' => $arYears
        ],
        'BUTTON' => [
            'PREV' => [
                'SHOW' => false,
                'LINK' => null
            ],
            'NEXT' => [
                'SHOW' => false,
                'LINK' => null
            ],
        ]
    ];

    $arYearTabs = [];

    if (!empty($arValues[$sVariable])) {
        foreach ($arYears as $key => $arYear) {
            if ($arValues[$sVariable] == $arYear) {
                if ($key - 1  > 0) {
                    $arYearList['PREV']['VALUE'] = $arYears[$key - 1];

                    if ($key - 1  > 1)
                        $arYearList['PREV']['DOTS'] = true;
                }

                if ($key + 1 < count($arYears) - 1) {
                    $arYearList['NEXT']['VALUE'] = $arYears[$key + 1];

                    if ($key + 1  < count($arYears) - 2)
                        $arYearList['NEXT']['DOTS'] = true;
                }

                if ($arYearList['PREV']['DOTS'] || $arYearList['NEXT']['DOTS'])
                    $arVisual['PANEL']['LIST'] = true;

                break;
            }
        }
    } else {
        if (count($arYears) > 1) {
            $arYearList['PREV']['VALUE'] = $arYears[1];
            $arYearList['BUTTON']['NEXT']['SHOW'] = true;
            $arYearList['BUTTON']['NEXT']['LINK'] = $APPLICATION->GetCurPageParam($sVariable.'='.$arYearList['FIRST'], [$sVariable]);
        }
        if (count($arYears) > 3) {
            $arVisual['PANEL']['LIST'] = true;
            $arYearList['NEXT']['DOTS'] = true;
            $arYearList['LIST']['SHOW'] = true;
        } else {
            $arYearList['LAST'] = false;
        }
    }

    $oCache->endDataCache($arYears);
}

if (!empty($arYearList['FIRST'])) {
    if (!empty($arValues[$sVariable])) {
        $arYearList['BUTTON']['PREV']['SHOW'] = true;
        $arYearList['BUTTON']['PREV']['LINK'] = $APPLICATION->GetCurPageParam($sVariable.'='.$arYearList['FIRST'], [$sVariable]);
    }

    $arYearTabs[] = [
        'VALUE' => $arYearList['FIRST'],
        'STATE' => 'none'
    ];
}

if ($arYearList['PREV']['DOTS']) {
    $arYearTabs[] = [
        'VALUE' => '...',
        'STATE' => 'disable'
    ];
}

if (!empty($arYearList['PREV']['VALUE'])) {
    if (!empty($arValues[$sVariable])) {
        $arYearList['BUTTON']['PREV']['SHOW'] = true;
        $arYearList['BUTTON']['PREV']['LINK'] = $APPLICATION->GetCurPageParam($sVariable . '=' . $arYearList['PREV']['VALUE'], [$sVariable]);
    }

    $arYearTabs[] = [
        'VALUE' => $arYearList['PREV']['VALUE'],
        'STATE' => 'none'
    ];
}

if (!empty($arYearList['CURRENT'])) {
    $arYearTabs[] = [
        'VALUE' => $arYearList['CURRENT'],
        'STATE' => 'active'
    ];
}

if (!empty($arYearList['NEXT']['VALUE'])) {
    $arYearList['BUTTON']['NEXT']['SHOW'] = true;
    $arYearList['BUTTON']['NEXT']['LINK'] = $APPLICATION->GetCurPageParam($sVariable.'='.$arYearList['NEXT']['VALUE'], [$sVariable]);

    $arYearTabs[] = [
        'VALUE' => $arYearList['NEXT']['VALUE'],
        'STATE' => 'none'
    ];
}

if ($arYearList['NEXT']['DOTS']) {
    $arYearTabs[] = [
        'VALUE' => '...',
        'STATE' => 'disable'
    ];
}

if (!empty($arYearList['LAST'])) {
    if (!$arYearList['BUTTON']['NEXT']['SHOW']) {
        $arYearList['BUTTON']['NEXT']['SHOW'] = true;
        $arYearList['BUTTON']['NEXT']['LINK'] = $APPLICATION->GetCurPageParam($sVariable.'='.$arYearList['LAST'], [$sVariable]);
    }

    $arYearTabs[] = [
        'VALUE' => $arYearList['LAST'],
        'STATE' => 'none'
    ];
}


unset($sDatePrefix, $sDateType);

if (!empty($arYears)) {
    if (!isset($GLOBALS[$arParams['FILTER_NAME']]))
        $GLOBALS[$arParams['FILTER_NAME']] = [];

    if (!empty($arValues[$sVariable])) {
        $GLOBALS[$arParams['FILTER_NAME']] = ArrayHelper::merge($GLOBALS[$arParams['FILTER_NAME']], $arFilter);
    }

    include(__DIR__.'/panel/view.1.php');
}

unset($arYears, $arFilter, $sVariable, $arValues);
