<?php

use KupShop\KupShopBundle\Config;

$main_class = 'usersGroups';

class UsersGroups extends Window
{
    use DatabaseCommunication;

    protected $tableName = 'users_groups';

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

        if (findModule(Modules::USERS_GROUPS_TYPES)) {
            $cfg = Config::get();
            foreach ($cfg['Modules']['users_groups_types'] as $key => $type) {
                $vars['body']['data']['types_values'][$key] = $type['name'];
            }

            $wtf = explode(',', $vars['body']['data']['types'] ?? '');
            $vars['body']['data']['types'] = array_combine(array_values($wtf), array_values($wtf));
        }

        $this->unserializeCustomData($vars['body']['data']);

        return $vars;
    }

    public function handleUpdate()
    {
        $SQL = parent::handleUpdate();
        $ID = $this->getID();

        $data = getVal('data');
        if (!empty($data['users'])) {
            $err_msq = '';
            foreach ($data['users'] as $id => $user) {
                $user['id'] = intval($id);

                if ($id < 0) {
                    if (empty($user['id_user'])) {
                        if (filter_var($user['id_user_text'], FILTER_VALIDATE_EMAIL)) {
                            $user['id_user'] = addUserEmail($user['id_user_text']);
                        } else {
                            $err_msq = "'{$user['id_user_text']}' není validní a nebyl přidán";
                            continue;
                        }
                    }
                    $this->insertSQL('users_groups_relations', ['id_user' => $user['id_user'], 'id_group' => $ID]);
                }
            }
            if (!empty($err_msq)) {
                $this->returnError($err_msq.'.');
            }
            $this->returnOK();
        }

        return $SQL;
    }

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

        $data['types'] = join(',', $data['types'] ?? []);

        if (isset($data['id_pricelist'])) {
            $data['id_pricelist'] = $data['id_pricelist'] ?: null;
        }

        $updatedData = $data['data'] ?? [];
        $data['data'] = $this->getObject()['data'] ?? null;
        $this->unserializeCustomData($data);
        $data['data'] = array_merge($data['data'], $updatedData);
        $this->serializeCustomData($data);

        return $data;
    }
}
