<?php

namespace KupShop\KupShopBundle\Admin\Tabs;

use KupShop\AdminBundle\Admin\ProductsFilter;
use KupShop\AdminBundle\Admin\WindowTab;
use Query\Operator;

class DeliveryRestrictions extends WindowTab
{
    protected $title = 'flapRestrictions';

    protected $template = 'window/deliveryTypesDelivery.restrictions.tpl';

    public static function getTypes(): array
    {
        return [
            'deliveryDelivery' => 1,
            'returnDelivery' => 1,
        ];
    }

    public function getVars($smarty_tpl_vars)
    {
        $data = [];
        if (empty($this->getID())) {
            return $data;
        }
        $deliveryRow = $this->getDeliveryRow();
        $deliveryRow['custom_data'] = json_decode($deliveryRow['data'] ?? '', true);
        $defaultRestrictions = $this->getDefaultRestrictions($deliveryRow['class']);
        $data['defaultRestrictions'] = $defaultRestrictions;
        foreach ($defaultRestrictions as $key => $value) {
            if (!array_key_exists($key, $deliveryRow['custom_data']['restrictions'] ?? [])) {
                $deliveryRow['custom_data']['restrictions'][$key] = $value;
            }
        }
        $data['restrictions'] = $deliveryRow['custom_data']['restrictions'] ?? [];

        return $data;
    }

    public function handleUpdate()
    {
        if (getVal('Submit')) {
            $data = getVal('data', null, []);
            $rawRestrictions = getVal('restrictions');
            if (!isset($rawRestrictions)) {
                return;
            }
            $defaultRestrictions = $this->getDefaultRestrictions($data['class']);
            $restrictions = array_diff_key($rawRestrictions, $defaultRestrictions);
            $restrictions['productsFilter'] = ProductsFilter::cleanFilter($restrictions['productsFilter'] ?? []);
            $restrictions = array_filter($restrictions);
            // přepravní omezení
            $restrictions['enabled'] = $rawRestrictions['enabled'] ?? 'N';
            foreach ($defaultRestrictions as $key => $default) {
                if (!array_key_exists($key, $rawRestrictions)) {
                    continue;
                }
                if ($key === 'maxDimensions') {
                    $this->checkMaxDimensions($restrictions, $rawRestrictions[$key], $default);
                    continue;
                } elseif (($rawRestrictions[$key] ?? false) === '') {
                    if (is_null($default)) {
                        continue; // use default
                    } else {
                        $restrictions[$key] = null; // override default -> disable restriction
                        continue;
                    }
                } elseif (isset($rawRestrictions[$key], $default)
                    && floatval($default) === floatval($rawRestrictions[$key])
                ) {
                    continue; // use default
                }
                if (array_key_exists($key, $rawRestrictions)) {
                    $restrictions[$key] = floatval($rawRestrictions[$key]);
                }
            }

            $customData = $this->window->getCustomData();
            $customData['restrictions'] = $restrictions;
            $this->window->setCustomData($customData);
        }
    }

    protected function checkMaxDimensions(array &$restrictions, $toCheck, $default): void
    {
        if (($toCheck[0] ?? false) === ''
            && ($toCheck[1] ?? false) === ''
            && ($toCheck[2] ?? false) === ''
        ) {
            if (is_null($default)) {
                return; // use default
            } else {
                $restrictions['maxDimensions'] = null; // override default -> disable restriction

                return;
            }
        } elseif (is_array($default)
            && isset($toCheck[0]) && floatval($toCheck[0]) === floatval($default[0])
            && isset($toCheck[1]) && floatval($toCheck[1]) === floatval($default[1])
            && isset($toCheck[2]) && floatval($toCheck[2]) === floatval($default[2])
        ) {
            return; // use default
        } else {
            $restrictions['maxDimensions'][0] = $toCheck[0] === '' ? null : floatval($toCheck[0]);
            $restrictions['maxDimensions'][1] = $toCheck[1] === '' ? null : floatval($toCheck[1]);
            $restrictions['maxDimensions'][2] = $toCheck[2] === '' ? null : floatval($toCheck[2]);
        }
    }

    protected function getDeliveryRow(): array
    {
        return $deliveryClassName = sqlQueryBuilder()->select('*')->from($this->window->getTableName())
            ->where(Operator::equals(['id' => $this->getID()]))->setMaxResults(1)->execute()->fetch();
    }

    protected function getDefaultRestrictions($deliveryClassName): array
    {
        $delivery = \Delivery::getClass($deliveryClassName);

        return [
            'maxPrice' => $delivery->config['maxPrice'] ?? null,
            'minPrice' => $delivery->config['minPrice'] ?? null,
            'maxCOD' => $delivery->config['maxCOD'] ?? null,
            'maxWeight' => $delivery->config['maxWeight'] ?? null,
            'minWeight' => $delivery->config['minWeight'] ?? null,
            'maxLength' => $delivery->config['maxLength'] ?? null,
            'maxSumOfDimensions' => $delivery->config['maxSumOfDimensions'] ?? null,
            'maxDimensions' => $delivery->config['maxDimensions'] ?? null,
            'maxVolume' => $delivery->config['maxVolume'] ?? null,
            'percentageReserve' => array_key_exists('percentageReserve', $delivery->config) ? $delivery->config['percentageReserve'] : 5.0,
        ];
    }
}
