<?php

namespace KupShop\AdminBundle\Admin;

use KupShop\KupShopBundle\Config;
use KupShop\KupShopBundle\Util\StringUtil;

class ProductsFilter
{
    use \KupShop\AdminBundle\Util\CategoryTree;

    protected $template = 'block.productsFilter.tpl';

    protected $params;

    public function getFilterData()
    {
        $data = [];

        // campaign
        $cfg = Config::get();
        if (isSuperuser()) {
            $flags = $cfg['Products']['Flags'];
        } else {
            $flags = array_filter($cfg['Products']['Flags'], function ($flag) { return !($flag['hidden'] ?? false); });
        }
        $flags = array_map(function ($flag) { return $flag['plural']; }, $flags);
        $data['campaigns'] = $flags;

        // figure
        $figure = [
            'Y' => translate('filterProductsFigureVisible', 'products'),
            'N' => translate('filterProductsFigureHidden', 'products'),
            'O' => translate('filterProductsFigureSaleEnd', 'products'),
        ];

        if (findModule(\Modules::PRODUCTS_VARIATIONS)) {
            $figure['V_Y'] = translate('filterVariationsFigureVisible', 'products');
            $figure['V_N'] = translate('filterVariationsFigureHidden', 'products');
        }

        $data['figure'] = $figure;

        // inStore
        $inStore = [
            'InStore' => translate('in stock', 'productsFilter'),
            'InStoreSoldOut' => translate('out of stock', 'productsFilter'),
        ];
        if (findModule(\Modules::PRODUCTS_SUPPLIERS)) {
            $inStore['InStoreSuppliers'] = translate('stock at supplier', 'productsFilter');
        }
        $data['inStore'] = $inStore;

        // delivery time
        $data['delivery_time'] = $cfg['Products']['DeliveryTime'] ?? [];

        return $data;
    }

    /**
     * @return array
     */
    public function getFilter($filter = [])
    {
        if ($filter) {
            $correctKeys = ['price', 'discount', 'in_store_range', 'stock_in_date_range', 'date_added_range'];
            foreach ($filter as $key => $item) {
                if (is_array($item) && !in_array($key, $correctKeys)) {
                    $values = array_values($item);
                    $filter[$key] = array_combine($values, $values);
                }
            }
        }

        $filter['enabled'] = static::isEnabled($filter ?? []) ? 'Y' : 'N';

        return $filter;
    }

    /**
     * @return array
     */
    public function getProducers()
    {
        if (isset($this->producers)) {
            return $this->producers;
        }

        // Producers
        $SQL = sqlQuery('SELECT id, name
                              FROM '.getTableName('producers')."
                              WHERE active='Y'
                              ORDER BY name ASC ");
        $producers = [];
        foreach ($SQL as $producer) {
            $producers[$producer['id']] = $producer['name'];
        }
        $this->producers = $producers;

        return $this->producers;
    }

    public static function isEnabled(array $filter): bool
    {
        // backward compatibility for filters without enable/disable toggle
        if (!isset($filter['enabled'])) {
            return !empty($filter);
        }

        return $filter['enabled'] === 'Y';
    }

    public static function cleanFilter($filter = []): array
    {
        foreach ($filter as $key => $value) {
            switch ($key) {
                case 'subcategories':
                    if (!array_key_exists('categories', $filter)) {
                        unset($filter[$key]);
                    }
                    break;
                case 'parametersValuesOperator':
                    if (!array_key_exists('parameters', $filter)) {
                        unset($filter[$key]);
                    }
                    break;
                case 'variationsValuesOperator':
                    if (!array_key_exists('variations', $filter)) {
                        unset($filter[$key]);
                    }
                    break;
                case StringUtil::endsWith($key, '_invert'):
                    if (!array_key_exists(substr($key, 0, -7), $filter)) {
                        unset($filter[$key]);
                    }
                    break;
                case 'title':
                    if (empty($title)) {
                        unset($filter[$key]);
                    }
                    break;
                default:
                    if (is_array($value) && empty(array_filter($value, 'strlen'))) { // 'strlen' to leave 0 (zero) values
                        unset($filter[$key]);
                    }
            }
        }

        return $filter;
    }
}
