<?php

declare(strict_types=1);

namespace App\Module;

use Contao\Widget;
use Isotope\Module\CumulativeFilter;
use Contao\Database;

/**
 * @property array $iso_cumulativeFields
 */
class IsoCumulativeFilter extends CumulativeFilter
{
    /**
     * Gets the used and available options for given attribute
     *
     * @param string $attribute The attribute name
     * @param string $label     Set to the label of the attribute
     *
     * @return array
     */
    protected function getOptionsForAttribute($attribute, &$label)
    {
        if ($attribute !== 'attr_monthyear')
        {
            $options = parent::getOptionsForAttribute($attribute, $label);
        } else {
            $usedValues = $this->getUsedValuesForAttribute(
                $attribute,
                $this->findCategories(),
                $this->iso_newFilter,
                $this->iso_list_where
            );

            if (empty($usedValues)) {
                return array();
            }

            // Use the default routine to initialize options data
            $arrWidget = Widget::getAttributesFromDca(
                $GLOBALS['TL_DCA']['tl_iso_product']['fields'][$attribute],
                $attribute
            );

            $label   = $arrWidget['label'];

            $result = Database::getInstance()->execute("
                    SELECT id AS 'value', month AS 'label'
                    FROM tl_iso_product_month
                    WHERE id IN (" . implode(',', $usedValues) . ")
                    ORDER BY CASE
                    WHEN label LIKE 'Januar%' THEN 1
                    WHEN label LIKE 'Februar%' THEN 2
                    WHEN label LIKE 'März%' THEN 3
                    WHEN label LIKE 'April%' THEN 4
                    WHEN label LIKE 'Mai%' THEN 5
                    WHEN label LIKE 'Juni%' THEN 6
                    WHEN label LIKE 'Juli%' THEN 7
                    WHEN label LIKE 'August%' THEN 8
                    WHEN label LIKE 'September%' THEN 9
                    WHEN label LIKE 'Oktober%' THEN 10
                    WHEN label LIKE 'November%' THEN 11
                    WHEN label LIKE 'Dezember%' THEN 12
                    ELSE 13
                    END
                ");

            $options = $result->fetchAllAssoc();
        }

        return $options;
    }
}