<?php

namespace KupShop\PreordersBundle\Admin;

class preorders extends \Window
{
    protected $tableName = 'preorders';

    public function get_vars(): array
    {
        $vars = parent::get_vars();
        $body = &$vars['body'];
        $data = &$body['data'];

        if (!empty($data['settings'])) {
            $this->sanitiseSettings($data['settings']);
        }

        if (!empty($data['min_price'])) {
            $data['min_price'] = toDecimal($data['min_price']);
        }

        return $vars;
    }

    public function getData()
    {
        $data = parent::getData();

        if (!empty($data['settings'])) {
            $this->sanitiseSettings($data['settings']);
        }

        return $data;
    }

    protected function sanitiseSettings(&$settings): void
    {
        if (is_string($settings)) {
            $settings = json_decode($settings, true);
        }

        if (!empty($settings['dynamic_prices'])) {
            $this->sanitiseDynamicPrices($settings['dynamic_prices']);
        }

        if (!empty($settings['users_groups'])) {
            $settings['users_groups'] = array_map('intval', $settings['users_groups']);
        }

        if (getVal('Submit')) {
            $settings = json_encode($settings);
        }
    }

    protected function sanitiseDynamicPrices(&$dynamicPrices): void
    {
        $dynamicPrices = array_filter($dynamicPrices, function ($val) {
            return (empty($val['price_from']) || ctype_digit($val['price_from']))
                && (empty($val['price_to']) || ctype_digit($val['price_to']))
                && (ctype_digit($val['id_price_level'] ?? 'NaN') || ctype_digit($val['id_pricelist'] ?? 'NaN'));
        });

        usort($dynamicPrices, function ($a, $b) {
            if (empty($a['price_from'])) {
                return -1;
            }

            if (empty($b['price_from'])) {
                return 1;
            }

            if (empty($a['price_to'])) {
                return 1;
            }

            if (empty($b['price_to'])) {
                return -1;
            }

            return $a['price_from'] < $b['price_from'] ? -1 : 1;
        });
    }
}

return preorders::class;
