<?php

namespace App\Console\Commands;

use App\Module;
use Illuminate\Console\Command;

class ModuleUpdate extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'module:update';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Module updating command';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $basePath = base_path();
        $moduleDataFile = $basePath . "/app/Console/Commands/ModuleData/modules.json";
        $countUpdated = 0;
        $countCreated = 0;
        if (file_exists($moduleDataFile)) {
            $modules = file_get_contents($moduleDataFile);
            if ($modules != null && $modules != "") {
                $modules = json_decode($modules, true);
                foreach ($modules as $module) {
                    $moduleItem = Module::where('name', $module['name'])->first();
                    if ($moduleItem != null && $moduleItem != "") {
                        if ($this->confirm("An {$module['name']} module already exists, do you want to update it?")) {
                            $moduleItem->name = $module['name'];
                            $moduleItem->table_name = $module['table_name'];
                            $moduleItem->table_field = $module['table_field'];
                            $moduleItem->status = $module['status'];
                            $moduleItem->save();
                            $countUpdated++;
                        }
                    } else {
                        Module::create([
                            'name'        => $module['name'],
                            'table_name'  => $module['table_name'],
                            'table_field' => $module['table_field'],
                            'status'      => $module['status'],
                            'created_at'  => $module['created_at'],
                            'updated_at'  => $module['updated_at']
                        ]);
                        $countCreated++;
                    }
                }
            } else {
                $this->error("No module data.");
            }
            $this->info("Done! Updated {$countUpdated} modules, created {$countCreated} modules.");
        }
    }
}
