<?php

$main_class = 'RestrictionsAdmin';

use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\RestrictionsBundle\Utils\Restrictions;

class RestrictionsAdmin extends Window
{
    protected $tableName = 'restrictions';
    protected $template = 'window/restrictions.tpl';

    /**
     * @var Restrictions
     */
    private $restrictions;

    public function __construct()
    {
        $this->restrictions = ServiceContainer::getService(Restrictions::class);
    }

    public function get_vars()
    {
        $vars = parent::get_vars();

        $ID = $this->getID();

        $pageVars = [];
        $data = &$vars['body']['data'];

        if (findModule(Modules::PRICE_LEVELS)) {
            $pageVars['all_price_levels'] = sqlQueryBuilder()->select('*')
                ->from('price_levels')
                ->orderBy('name')
                ->execute()->fetchAllAssociative();
        }

        $pageVars['all_user_groups'] = sqlQueryBuilder()->select('*')
            ->from('users_groups')
            ->orderBy('name')
            ->execute()->fetchAllAssociative();

        if (!empty($ID)) {
            /*
             *
             * Domain loading
             */
            $domains = array_flip($this->restrictions->getDomainNames());

            $fields = sqlGetConnection()->getSchemaManager()->listTableColumns('restrictions_domains');
            $fields = join(',', array_map(function ($x) {
                return 'rdv.'.$x;
            }, array_filter(array_keys($fields), function ($x) {
                return $x != 'id' && $x != 'id_restriction';
            })));

            $sql = sqlQuery("SELECT rdv.*, COALESCE({$fields}) AS domain_value, u.name, u.surname, u.email, u.firm
            FROM restrictions_domains AS rdv
            LEFT JOIN users AS u ON u.id = rdv.id_user
            WHERE rdv.id_restriction = :id_restriction", ['id_restriction' => $ID]);

            $domain_name = $domains[$data['domain']].'_values';

            $pageVars[$domain_name] = [];

            foreach ($sql as $value) {
                $value['user'] = "{$value['firm']} {$value['name']} {$value['surname']} - {$value['email']}";
                $pageVars[$domain_name][$value['domain_value']] = $value;
            }
            /*
             * End domain loading
             *
             */

            /*
            * Object loading
            *
            */
            $objects_values = $data['object_value'];

            if (!empty($objects_values)) {
                $objects_values = json_decode($objects_values, true);
            }

            $objects = array_flip($this->restrictions->getObjectNames());

            foreach ($objects_values as $key => $object_values) {
                if (is_array($object_values)) {
                    switch ($key) {
                        // category
                        case 1:
                            $object_values = sqlFetchAll(sqlQuery('SELECT id, name FROM sections WHERE id IN (:values)',
                                ['values' => array_values($object_values)], ['values' => \Doctrine\DBAL\Connection::PARAM_INT_ARRAY]));
                            break;

                            // producer
                        case 2:
                            $object_values = sqlFetchAll(sqlQuery('SELECT id, name FROM producers WHERE id IN (:values)',
                                ['values' => array_values($object_values)], ['values' => \Doctrine\DBAL\Connection::PARAM_INT_ARRAY]));
                            break;

                            // campaign
                        case 3:
                            global $cfg;
                            $loaded_values = [];
                            foreach ($object_values as &$value) {
                                $tmp_value['id'] = $value;
                                $tmp_value['name'] = !empty($cfg['Products']['Flags'][$value]) ? $cfg['Products']['Flags'][$value] : $value;
                                $loaded_values[$value] = $tmp_value;
                            }
                            $object_values = $loaded_values;
                            break;

                            // product
                        case 4:
                            $object_values = sqlFetchAll(sqlQuery('SELECT id, title AS name FROM products WHERE id IN (:values)',
                                ['values' => array_values($object_values)], ['values' => \Doctrine\DBAL\Connection::PARAM_INT_ARRAY]));
                            break;
                            // parameters_list
                        case 5:
                            $object_values = array_values($object_values); // preloaded in js
                            break;
                        default:
                            break;
                    }

                    $data[$objects[$key].'_values'] = $object_values;
                }
            }
        }

        $vars['body']['data'] = array_merge($vars['body']['data'], $pageVars);
        $vars['body']['restrictions'] = $this->restrictions;

        return $vars;
    }

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

        $objects = array_flip($this->restrictions->getObjectNames());

        if (getVal('Submit')) {
            $data['object_values'] = [];
            foreach ($objects as $key => $object) {
                if (isset($data[$object.'_values'])) {
                    $data['object_values'][$key] = [];
                    foreach ($data[$object.'_values'] as $objects_value) {
                        $data['object_values'][$key][] = $objects_value;
                    }
                }
            }

            $data['object_value'] = json_encode($data['object_values']);

            $domain_name = array_flip($this->restrictions->getDomainNames())[$data['domain']] ?? '';
            $data['domain_invert'] = getVal($domain_name.'_invert') ? 'Y' : 'N';
        }

        return $data;
    }

    public function handleUpdate()
    {
        $SQL = parent::handleUpdate();

        $domains = array_flip($this->restrictions->getDomainNames());

        $data = parent::getData();
        $ID = $this->getID();

        $this->deleteSQL('restrictions_domains', ['id_restriction' => $ID]);

        if (!empty($data[$domains[$data['domain']].'_values'])) {
            foreach ($data[$domains[$data['domain']].'_values'] as $value) {
                switch ($data['domain']) {
                    // country
                    case 1:
                        $this->insertSQL('restrictions_domains', ['id_restriction' => $ID, 'country' => $value]);
                        break;

                        // user
                    case 2:
                        $this->insertSQL('restrictions_domains', ['id_restriction' => $ID, 'id_user' => $value]);
                        break;

                        // login
                    case 4:
                        $this->insertSQL('restrictions_domains', ['id_restriction' => $ID, 'login' => $value]);
                        break;

                        // price level
                    case 5:
                        $this->insertSQL('restrictions_domains', ['id_restriction' => $ID, 'id_price_level' => $value]);
                        break;

                        // users groups
                    case 6:
                        $this->insertSQL('restrictions_domains', ['id_restriction' => $ID, 'id_users_group' => $value]);
                        break;

                        // region
                    case 11:
                        $this->insertSQL('restrictions_domains', ['id_restriction' => $ID, 'region' => $value]);
                        break;
                }
            }
        }

        return $SQL;
    }
}
