<?php

declare(strict_types=1);

namespace KupShop\UserBundle\Resources\upgrade;

use KupShop\KupShopBundle\Config;

class UserGroupsUpgrade extends \UpgradeNew
{
    public function check_userGroupsPriceLevel(): bool
    {
        return findModule(\Modules::PRICE_LEVELS) && $this->checkColumnExists('users_groups', 'id_price_level');
    }

    /** Add 'id_price_level' column into 'users_groups' table */
    public function upgrade_userGroupsPriceLevel(): void
    {
        sqlQuery('ALTER TABLE users_groups ADD COLUMN id_price_level INT(10) UNSIGNED DEFAULT NULL AFTER id');
        sqlQuery('ALTER TABLE users_groups ADD CONSTRAINT FK_users_groups_id_price_level FOREIGN KEY (id_price_level) REFERENCES price_levels(id) ON UPDATE CASCADE ON DELETE SET NULL ');

        $this->upgradeOK();
    }

    public function check_userGroupsTypes(): bool
    {
        $cfg = Config::get();
        $types = array_keys($cfg['Modules']['users_groups_types'] ?? []);

        if (empty($types)) {
            return false;
        }

        if ($this->checkColumnExists('users_groups', 'types')) {
            sqlQuery("ALTER TABLE users_groups ADD types SET('') DEFAULT NULL;");
        }

        return $this->checkSetOptions('users_groups', 'types', $types);
    }

    /** Update users groups types */
    public function upgrade_userGroupsTypes(): void
    {
        $cfg = Config::get();
        $types = array_keys($cfg['Modules']['users_groups_types']);
        $this->updateSetOptions('users_groups', 'types', $types);
    }

    public function check_UserGroupsDataColumn(): bool
    {
        return $this->checkColumnExists('users_groups', 'data');
    }

    /** users_groups: add `data` column */
    public function upgrade_UserGroupsDataColumn(): void
    {
        sqlQuery('ALTER TABLE users_groups ADD COLUMN data MEDIUMTEXT NULL');

        $this->upgradeOK();
    }
}
