<?php

namespace App\Console\Commands;

use App\Http\Controllers\SettingsController;
use App\Models\Central\Module;
use App\Models\settings;
use Illuminate\Console\Command;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use SiteHelpers;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Load module config from DB to module config files';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $module = Module::where('module_name', $this->argument('module'))->first()->toArray();

        $module['module_config'] = SiteHelpers::CF_decode_json($module['module_config']);

        $export = var_export($module, true);
        $export = preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $export);
        $array = preg_split("/\r\n|\n|\r/", $export);
        $array = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [NULL, ']$1', ' => ['], $array);
        $export = join(PHP_EOL, array_filter(["["] + $array));
        $val = '<?php return ' . ($export) . ';';

        $filename = base_path() . '/config/modules/' . $module['module_name'] . '.php';
        $dirname = dirname($filename);
        if (!is_dir($dirname)) {
            mkdir($dirname, 0755, true);
        }
        $fp = fopen($filename, "w+");
        fwrite($fp, $val);
        fclose($fp);

        $this->info("Updated config/modules/{$module['module_name']}.php");
    }
}
