<?php

namespace ModulesGarden\HostingQuotaNotifications\App\Helper\Migration\Groups;

use ModulesGarden\HostingQuotaNotifications\App\Libs\Groups\Constants;
use ModulesGarden\HostingQuotaNotifications\App\Models\GroupsConfiguration;
use ModulesGarden\HostingQuotaNotifications\App\Libs\Groups\Constants as GroupConstants;


/**
 * Class GroupConfiguration
 *
 * @author Artur Pilch <artur.pi@modulesgarden.com>
 */
class GroupConfiguration
{
    public static function migrateConfiguration($mainData, $configuration)
    {

        if($mainData['type'] == Constants::FIXED)
        {
            self::saveGroupConfiguration($mainData, $configuration);
            return;
        }

        foreach ($configuration as $config)
        {
            self::saveGroupConfiguration($mainData, $config);
        }
    }

    public static function saveGroupConfiguration($mainData, $config)
    {
        $groupConfigurationModel                = new GroupsConfiguration();
        $groupConfigurationModel->groupid       = $mainData['groupId'];
        $groupConfigurationModel->kind          = $mainData['kind'];
        $groupConfigurationModel->configuration = self::getSerializedConfiguration($mainData, $config);
        $groupConfigurationModel->save();
    }

    public static function getSerializedConfiguration($mainData, $config)
    {
        $data = [
            'value'           => $config['value'],
            'unit'            => $config['unit'] == 'p' ? GroupConstants::PERCENTAGE : strtoupper($config['unit']),
            'email_template'  => $mainData['emailTemplate'],
            'ticket_template' => 'none',
            'action'          => 'none',
        ];

        if($mainData['type'] == Constants::FIXED)
        {
            $data['countedDays'] = $config['days'];
        }
        return serialize($data);
    }
}