<?php
namespace ModulesGarden\Servers\ZimbraEmail\App\Cron;

use ModulesGarden\Servers\ZimbraEmail\App\Models\ProductConfiguration;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use \Illuminate\Database\Capsule\Manager as DB;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Migrations\Drivers\Version1To2;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 13.11.19
 * Time: 09:49
 * Class Migration
 */
class Migration extends \ModulesGarden\Servers\ZimbraEmail\Core\CommandLine\AbstractCommand
{
    /**
     * Command name
     * @var string
     */
    protected $name = 'migration:v1_v2';

    /**
     * Command description
     * @var string
     */
    protected $description = 'Migrate product settings from version 1.x to version 2.x';

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @param SymfonyStyle $io
     */
    protected function process(InputInterface $input, OutputInterface $output, SymfonyStyle $io)
    {

        $migration = new Version1To2\Settings();

        $exists = DB::schema()->hasTable($migration->getFromTable());
        if(!$exists)
        {
            $io->warning("Previous version of module can not be found.");
        }

        $previous = DB::table($migration->getFromTable())->get();

        /**
         *
         */
        $prodManager = new ProductConfiguration();

        /**
         *
         * storage all params per product id
         */
        foreach($previous as $setting)
        {
            $settings[$setting->product_id][$setting->setting] = $setting->value;
            $products[] = $setting->product_id;
        }

        /**
         *
         * update setting data & save
         */
        foreach($settings as $prodId => $settingsArray)
        {
            $attrs = $migration->updateValues($settingsArray, $prodId);

            foreach($attrs as $key => $value)
            {
                $prodManager->updateOrCreate(['product_id' => $prodId, 'setting' => $key],['value' => $value]);
            }
        }


        /**
         *
         * set new fields
         */
        foreach($migration->getNewFields() as $key => $value)
        {
            foreach($products as $id)
            {
                $prodManager->updateOrCreate(['product_id' => $id, 'setting' => $key],['value' => $value]);
            }
        }

        /**
         *
         */
        $io->success("Migration has been finished successfully.");
    }
}