<?php

namespace ModulesGarden\HostingQuotaNotifications\App\Libs\Migration\Tables;

use \Illuminate\Database\Capsule\Manager;
use ModulesGarden\HostingQuotaNotifications\App\Helper\Migration\DBManager;

use ModulesGarden\HostingQuotaNotifications\App\Helper\Migration\Groups\ProductGroup;
use ModulesGarden\HostingQuotaNotifications\App\Libs\GroupConfiguration\Constants;
use ModulesGarden\HostingQuotaNotifications\App\Libs\Migration\Migrator;
use ModulesGarden\HostingQuotaNotifications\App\Helper\Models\EmailTemplates;
use ModulesGarden\HostingQuotaNotifications\App\Libs\Migration\MigratorBase;

use ModulesGarden\HostingQuotaNotifications\App\Helper\Migration\Groups\Group;
use ModulesGarden\HostingQuotaNotifications\App\Helper\Migration\Groups\GroupConfiguration;


/**
 * Class Groups
 *
 * @author Artur Pilch <artur.pi@modulesgarden.com>
 */
class Groups extends MigratorBase implements Migrator
{
    CONST PRODUCT_GROUP_TABLE = 'mg_hq_productgroup';

    public function migrate()
    {
        foreach ($this->data as $oldGroup)
        {
            $emailTemplate = EmailTemplates::getTemplateIdFromName($oldGroup->tplname);
            $groupId       = Group::migrateGroupAndReturnGroupId($oldGroup, $emailTemplate);
            $this->migrateConfiguration($groupId, unserialize($oldGroup->conf), $emailTemplate, $oldGroup->type);
            ProductGroup::migrateProductToGroup($groupId, $this->getProducts($oldGroup->id));
        }
    }

    protected function migrateConfiguration($groupId, $configuration, $emailTemplate, $type)
    {

        foreach ($configuration as $kind => $config)
        {
            GroupConfiguration::migrateConfiguration([
                'groupId'       => $groupId,
                'kind'          => Constants::getFullKindFromShort($kind),
                'emailTemplate' => $emailTemplate,
                'type'          => $type
            ], $config);
        }
    }

    protected function getProducts($groupId)
    {
        return DBManager::fetchFromTableWhereRaw(SELF::PRODUCT_GROUP_TABLE, ['pid'], 'gid = ?', [$groupId]);
    }


}