<?php

namespace App\Console\Commands;

use App\Module;
use function GuzzleHttp\Psr7\str;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;

class ModuleGenerate extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'module:generate {moduleName} {--table=} {--field=}';

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

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $languages = ['en', 'ja', 'vi'];
        $digitList = ['foreignId', 'bigIncrements', 'bigInteger', 'boolean', 'decimal', 'double', 'float', 'increments', 'integer', 'mediumInteger', 'smallIncrements', 'smallInteger', 'tinyIncrements', 'tinyInteger', 'unsignedBigInteger', 'unsignedDecimal', 'unsignedInteger', 'unsignedMediumInteger', 'unsignedSmallInteger', 'unsignedTinyInteger', 'year'];
        $basePath = base_path();
        $templatePath = $basePath . '/app/Console/Commands/Template/';

        $moduleName = $this->argument('moduleName'); //Menu
        $table = $this->option('table'); //--table=menus
        $field = $this->option('field'); //--field="name:string|slug:string:nullable|description:text:nullable|is_activated:boolean::true|is_deleted:boolean::false"

        if ($moduleName == null || $moduleName == "") {
            $this->error("Module Name is not valid.");
            return false;
        }

        /*if (!$this->confirm("Is it correct, do you wish to continue?")) {
            $this->info("Cancelled Generate Module.");
            return false;
        }*/

        if ($table != null && $table != "" && ($field == null || $field == "")) {
            if ($this->confirm('Do you want to create a table?')) {
                $field = $this->ask('Please enter the fields [id:string:nullable:null|slug:text:nullable]:');
            }
        }

        //Validate
        print "\r\nValidating data....\r\n";
        $checkRsName = strtolower($moduleName);
        $checkRsNameUpper = ucfirst($checkRsName);
        $module = Module::where('name', $moduleName)->first();
        if (isset($module) && $module != null && $module != "") {
            $this->error("Module is exist.");
            return false;
        }

        if ($table != null && $table != "") {
            $checkMigrateFile = "";
            foreach(glob($basePath . '/database/migrations/*.php') as $migrateFile) {
                if (strpos($migrateFile, "create_" . strtolower($table) . "_table.php") !== false) {
                    $checkMigrateFile = basename($migrateFile);
                    break;
                }
            }

            if ($checkMigrateFile != "") {
                $this->error("Migration create_" . strtolower($table) . "_table.php is exist. File: database/migrations/{$checkMigrateFile} \r\n");
                return false;
            }
        }

        if (file_exists($basePath . "/app/{$moduleName}.php")) {
            $this->error("Model {$moduleName}.php is exist. File: app/{$moduleName}.php \r\n");
            return false;
        }
        if (file_exists($basePath . "/resources/js/router/modules/{$checkRsName}.js")) {
            $this->error("Router {$checkRsName}.js is exist. File: resources/js/router/modules/{$checkRsName}.js \r\n");
            return false;
        }
        if (file_exists($basePath . "/resources/js/api/{$checkRsName}.js")) {
            $this->error("Resources {$checkRsName}.js is exist. File: resources/js/api/{$checkRsName}.js \r\n");
            return false;
        }
        if (file_exists($basePath . "/resources/js/views/{$checkRsName}/List.vue")) {
            $this->error("View List.vue is exist. File: resources/js/views/{$checkRsName}/List.vue \r\n");
            return false;
        }
        if (file_exists($basePath . "/resources/js/views/{$checkRsName}/Create.vue")) {
            $this->error("View Create.vue is exist. File: resources/js/views/{$checkRsName}/Create.vue \r\n");
            return false;
        }
        if (file_exists($basePath . "/resources/js/views/{$checkRsName}/Edit.vue")) {
            $this->error("View Edit.vue is exist. File: resources/js/views/{$checkRsName}/Edit.vue \r\n");
            return false;
        }
        if (file_exists($basePath . "/resources/js/views/{$checkRsName}/components/{$checkRsNameUpper}Detail.vue")) {
            $this->error("View {$checkRsNameUpper}Detail.vue is exist. File: resources/js/views/{$checkRsName}/components/{$checkRsNameUpper}Detail.vue \r\n");
            return false;
        }
        if (file_exists($basePath . "/app/Http/Controllers/Admin/{$moduleName}Controller.php")) {
            $this->error("Controller {$moduleName}Controller.php is exist. File: app/Http/Controllers/Admin/{$moduleName}Controller.php \r\n");
            return false;
        }
        if (file_exists($basePath . "/app/Http/Resources/Admin/{$moduleName}Resource.php")) {
            $this->error("Web Resource {$moduleName}Resource.php is exist. File: app/Http/Resources/Admin/{$moduleName}Resource.php \r\n");
            return false;
        }

        print "\r\nStarting generate module....\r\n";
        Module::create(['name' => $moduleName, 'table_name' => $table, 'table_field' => $field, 'status' => 1, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')]);
        $message = "\r\n===========================================================================\r\n";
        $moduleName = ucfirst(strtolower($moduleName));

        //Table
        $listFieldItems = [];
        if ($table != null && $table != "") {
            $table = strtolower($table);
            $rs = shell_exec("php artisan make:migration create_{$table}_table --create={$table}");
            if (strpos($rs, "Created Migration:") !== false) {
                $message .= $rs;
                $listFieldName = "";

                if ($field != null && $field != "") {
                    $migrationFileName = str_replace("Created Migration:", "", $rs);
                    $migrationFileName = ($migrationFileName != "") ? trim($migrationFileName) : '';
                    $migrationFile = $basePath . "/database/migrations/" . $migrationFileName . ".php";
                    if (file_exists($migrationFile)) {
                        $fields = explode("|", $field);
                        $listFileDefined = "";
                        foreach ($fields as $item) {
                            $listFieldData = explode(":", $item);
                            if (count($listFieldData) <= 0 || (isset($listFieldData[0]) && $listFieldData[0] == 'id')) continue;
                            $fieldName = $listFieldData[0];
                            $fieldType = $listFieldData[1];
                            $fieldItem = ['name' => $fieldName, 'type' => $fieldType, 'rule' => 'required'];
                            $rowField = '$table->' . $fieldType . '("' . $fieldName . '")';
                            if (isset($listFieldData[2]) && $listFieldData[2] == 'nullable') {
                                $rowField .= '->nullable()';
                                $fieldItem['rule'] = '';
                            }
                            if (isset($listFieldData[3]) && $listFieldData[3] != "") {
                                if (in_array($fieldType, $digitList)) {
                                    $rowField .= '->default(' . $listFieldData[3] . ')';
                                } else {
                                    $rowField .= '->default("' . $listFieldData[3] . '")';
                                }
                                $fieldItem['rule'] = '';
                            }
                            $rowField = "\t\t\t" . $rowField . ";";
                            $listFileDefined .= "\r\n" . $rowField;
                            $listFieldName .= ($listFieldName == "") ? "'{$fieldName}'," : " '{$fieldName}',";
                            $listFieldItems[] = $fieldItem;
                        }
                        if ($listFileDefined != "") {
                            $migrationContent = file_get_contents($migrationFile); //$table->id();
                            $migrationContent = str_replace('$table->id();', '$table->id();' . $listFileDefined, $migrationContent);
                            file_put_contents($migrationFile, $migrationContent);
                        }
                    }
                    print "[OK] Generated Module Migration.\r\n";
                }

                $modelTemplateFile = $templatePath . "Model.template";
                $modelFileName = $basePath . "/app/{$moduleName}.php";
                if (file_exists($modelTemplateFile) && !file_exists($modelFileName)) {
                    $modelContent = file_get_contents($modelTemplateFile);
                    $modelContent = str_replace('{ModelName}', $moduleName, $modelContent);
                    $modelContent = str_replace('{ModelTable}', $table, $modelContent);
                    $modelContent = str_replace('{ModelField}', $listFieldName, $modelContent);
                    file_put_contents($modelFileName, $modelContent);
                    $message .= "Created Model: app/{$moduleName}.php \r\n";
                    print "[OK] Generated Module Model.\r\n";
                }
            }
        }

        //Permission
        $permissionFile = $basePath . "/app/Laravue/Acl.php";
        if (file_exists($permissionFile)) {
            $permissionName = strtoupper($moduleName);
            $permissionKey = strtolower($moduleName);
            $newPermission = "\r\n\tconst PERMISSION_VIEW_MENU_{$permissionName}             = 'view-menu-{$permissionKey}';";
            $newPermission .= "\r\n\tconst PERMISSION_{$permissionName}_MANAGE                = 'manage-{$permissionKey}';";
            $newPermission .= "\r\n\tconst PERMISSION_{$permissionName}_ONLY_MANAGE           = 'manage-{$permissionKey}-only';";
            $newPermission .= "\r\n\tconst PERMISSION_{$permissionName}_CREATE_MANAGE         = 'manage-{$permissionKey}-create';";
            $newPermission .= "\r\n\tconst PERMISSION_{$permissionName}_EDIT_MANAGE           = 'manage-{$permissionKey}-edit';";
            $newPermission .= "\r\n\tconst PERMISSION_{$permissionName}_DELETE_MANAGE         = 'manage-{$permissionKey}-delete';";
            $permissionContent = file_get_contents($permissionFile);
            $permissionContent = str_replace("/*import-permission*/", "/*import-permission*/\r\n{$newPermission}", $permissionContent);
            file_put_contents($permissionFile, $permissionContent);
            $message .= "Updated Permission: app/Laravue/Acl.php \r\n";
            print "[OK] Generated Module Permission.\r\n";
        }

        //Router
        $routerName = strtolower($moduleName);
        $routerTemplateFile = $templatePath . "Router.template";
        $routerFileName = $basePath . "/resources/js/router/modules/{$routerName}.js";
        if (file_exists($routerTemplateFile) && !file_exists($routerFileName)) {
            $routerContent = file_get_contents($routerTemplateFile);
            $routerContent = str_replace('{RouterName}', $routerName, $routerContent);
            $routerContent = str_replace('{RouterNameUpper}', $moduleName, $routerContent);
            file_put_contents($routerFileName, $routerContent);
            $message .= "Created Router: resources/js/router/modules/{$routerName}.js \r\n";

            $routerIndexFile = $basePath . "/resources/js/router/index.js";
            if (file_exists($routerIndexFile)) {
                $routerIndexContent = file_get_contents($routerIndexFile);
                $routerIndexContent = str_replace("/*import-router-lib*/", "/*import-router-lib*/\r\nimport {$routerName}Routes from './modules/{$routerName}';", $routerIndexContent);
                $routerIndexContent = str_replace("/*import-router*/", "/*import-router*/\r\n\t{$routerName}Routes,", $routerIndexContent);
                file_put_contents($routerIndexFile, $routerIndexContent);
                $message .= "Updated Index Router: resources/js/router/index.js \r\n";
            }
            print "[OK] Generated Module Router.\r\n";
        }

        //Api Resource
        $resourceName = strtolower($moduleName);
        $resourceTemplateFile = $templatePath . "Resource.template";
        $resourceFileName = $basePath . "/resources/js/api/{$resourceName}.js";
        if (file_exists($resourceTemplateFile) && !file_exists($resourceFileName)) {
            $resourceContent = file_get_contents($resourceTemplateFile);
            $resourceContent = str_replace('{ResourceName}', $resourceName, $resourceContent);
            $resourceContent = str_replace('{ResourceNameUpper}', $moduleName, $resourceContent);
            file_put_contents($resourceFileName, $resourceContent);
            $message .= "Created Resource: resources/js/api/{$resourceName}.js \r\n";
            print "[OK] Generated Module Resource.\r\n";
        }

        //Views
        $viewName = strtolower($moduleName);
        $viewFolder = $basePath . "/resources/js/views/{$viewName}";
        $viewComponentFolder = $basePath . "/resources/js/views/{$viewName}/components";
        $listName = strtolower($moduleName);
        $listNameUpper = ucfirst($listName);
        if(!is_dir($viewFolder)) {
            mkdir($viewFolder, 0777, true);
            mkdir($viewComponentFolder, 0777, true);
        }

        $listTemplateFile = $templatePath . "List.template";
        if (file_exists($listTemplateFile) && !file_exists($viewFolder . "/List.vue")) {
            $listContent = file_get_contents($listTemplateFile);
            $listContent = str_replace('{ListName}', $listName, $listContent);
            $listContent = str_replace('{ListNameUpper}', $listNameUpper, $listContent);
            $listColumns = "";
            if (count($listFieldItems) > 0) {
                foreach ($listFieldItems as $it) {
                    if ($it['name'] == 'id' || $it['name'] == 'is_deleted') continue;
                    if ($it['name'] == 'is_activated' || $it['name'] == 'status') {
                        $funcName = "";
                        $funcNameFilter = explode("_", $it['name']);
                        foreach ($funcNameFilter as $k => $itF) {
                            if ($k == 0) {
                                $funcName .= strtolower($itF);
                            } else {
                                $funcName .= ucfirst(strtolower($itF));
                            }
                        }

                        $listColumns .= "\r\n\t\t\t" . '<el-table-column prop="' . $it['name'] . '" align="center" class-name="status-col" :label="$t(\'' . $listName . '.label.' . $it['name'] . '\')" width="150" sortable>';
                        $listColumns .= "\r\n\t\t\t\t" . '<template slot-scope="{row}">';
                        $listColumns .= "\r\n\t\t\t\t\t" . '<el-tag :type="row.' . $it['name'] . ' | ' . $funcName . 'Filter">';
                        $listColumns .= "\r\n\t\t\t\t\t\t" . '{{ $t(\'' . $listName . '.label.' . $it['name'] . '_\' + row.' . $it['name'] . ') }}';
                        $listColumns .= "\r\n\t\t\t\t\t" . '</el-tag>';
                        $listColumns .= "\r\n\t\t\t\t" . '</template>';
                        $listColumns .= "\r\n\t\t\t" . '</el-table-column>';
                    } else {
                        $listColumns .= "\r\n\t\t\t" . '<el-table-column prop="' . $it['name'] . '" align="left" :label="$t(\'' . $listName . '.label.' . $it['name'] . '\')" sortable>';
                        $listColumns .= "\r\n\t\t\t\t" . '<template slot-scope="scope">';
                        $listColumns .= "\r\n\t\t\t\t\t" . '<span>{{ scope.row.' . $it['name'] . ' }}</span>';
                        $listColumns .= "\r\n\t\t\t\t" . '</template>';
                        $listColumns .= "\r\n\t\t\t" . '</el-table-column>';
                    }
                    $listColumns .= "\r\n";
                }
            }
            $listContent = str_replace('{ModuleTableColumn}', $listColumns, $listContent);
            file_put_contents($viewFolder . "/List.vue", $listContent);
            $message .= "Created View Listing: resources/js/views/{$viewName}/List.vue \r\n";
            print "[OK] Generated Module Listing.\r\n";
        }

        $createTemplateFile = $templatePath . "Create.template";
        if (file_exists($createTemplateFile) && !file_exists($viewFolder . "/Create.vue")) {
            $createContent = file_get_contents($createTemplateFile);
            $createContent = str_replace('{ModuleName}', $listName, $createContent);
            $createContent = str_replace('{ModuleNameUpper}', $listNameUpper, $createContent);
            file_put_contents($viewFolder . "/Create.vue", $createContent);
            $message .= "Created View Creating: resources/js/views/{$viewName}/Create.vue \r\n";
            print "[OK] Generated Module Creating.\r\n";
        }

        $editTemplateFile = $templatePath . "Edit.template";
        if (file_exists($editTemplateFile) && !file_exists($viewFolder . "/Edit.vue")) {
            $editContent = file_get_contents($editTemplateFile);
            $editContent = str_replace('{ModuleName}', $listName, $editContent);
            $editContent = str_replace('{ModuleNameUpper}', $listNameUpper, $editContent);
            file_put_contents($viewFolder . "/Edit.vue", $editContent);
            $message .= "Created View Editing: resources/js/views/{$viewName}/Edit.vue \r\n";
            print "[OK] Generated Module Editing.\r\n";
        }

        $formTemplateFile = $templatePath . "FormDetail.template";
        if (file_exists($formTemplateFile) && !file_exists($viewComponentFolder . "/{$listNameUpper}Detail.vue")) {
            $formContent = file_get_contents($formTemplateFile);
            $formContent = str_replace('{ModuleName}', $listName, $formContent);
            $formContent = str_replace('{ModuleNameUpper}', $listNameUpper, $formContent);
            $moduleTableFields = "";
            $moduleFormModel = "";
            $moduleFormRules = "";
            $moduleFormEdit = "";
            $moduleFormReset = "";
            if (count($listFieldItems) > 0) {
                foreach ($listFieldItems as $it) {
                    if ($it['name'] == 'id' || $it['name'] == 'is_deleted') continue;
                    if ($it['name'] == 'is_activated' || $it['name'] == 'status') {
                        $moduleTableFields .= "\r\n\t\t\t\t\t\t" . '<el-form-item label-width="120px" :label="$t(\'' . $listName . '.label.' . $it['name'] . '\')" prop="' . $it['name'] . '">';
                        $moduleTableFields .= "\r\n\t\t\t\t\t\t\t" . '<el-switch v-model="dataForm.' . $it['name'] . '"/>';
                        $moduleTableFields .= "\r\n\t\t\t\t\t\t" . '</el-form-item>';
                    } else if ($it['name'] != 'is_activated' && $it['name'] != 'status' && $it['type'] == 'text') {
                        $moduleTableFields .= "\r\n\t\t\t\t\t\t" . '<el-form-item label-width="120px" :label="$t(\'' . $listName . '.label.' . $it['name'] . '\')" prop="' . $it['name'] . '">';
                        $moduleTableFields .= "\r\n\t\t\t\t\t\t\t" . '<el-input v-model="dataForm.' . $it['name'] . '" :placeholder="$t(\'' . $listName . '.label.' . $it['name'] . '\')" type="textarea" id="txtarea' . ucfirst(strtolower($it['name'])) . '"/>';
                        $moduleTableFields .= "\r\n\t\t\t\t\t\t" . '</el-form-item>';
                    } else {
                        $moduleTableFields .= "\r\n\t\t\t\t\t\t" . '<el-form-item label-width="120px" :label="$t(\'' . $listName . '.label.' . $it['name'] . '\')" prop="' . $it['name'] . '" style="margin-top: 50px;">';
                        $moduleTableFields .= "\r\n\t\t\t\t\t\t\t" . '<el-input :placeholder="$t(\'' . $listName . '.label.' . $it['name'] . '\')" v-model="dataForm.' . $it['name'] . '"></el-input>';
                        $moduleTableFields .= "\r\n\t\t\t\t\t\t" . '</el-form-item>';
                    }
                    $moduleTableFields .= "\r\n";

                    if ($it['name'] == 'is_activated') {
                        $moduleFormModel .= "is_activated: true,";
                        $moduleFormEdit .= "this.dataForm.is_activated = (editItem.is_activated === 1) ? true : false;";
                        $moduleFormReset .= "this.dataForm.is_activated = true;";
                    } else {
                        $moduleFormModel .= "{$it['name']}: '',\r\n\t\t";
                        $moduleFormEdit .= "this.dataForm.{$it['name']} = editItem.{$it['name']};\r\n\t\t\t\t\t\t";
                        $moduleFormReset .= "this.dataForm.{$it['name']} = '';\r\n\t\t\t\t";
                    }

                    if ($it['rule'] == 'required') {
                        $moduleFormRules .= $it['name'] . ': [{ required: true, message: this.$t(\'' . $listName . '.message.required_' . $it['name'] . '\'), trigger: \'blur\' }],' . "\r\n\t\t\t\t\t";
                    }
                }
            }
            $formContent = str_replace('{ModuleFormFields}', $moduleTableFields, $formContent);
            $formContent = str_replace('{ModuleFormModel}', $moduleFormModel, $formContent);
            $formContent = str_replace('{ModuleFormRules}', $moduleFormRules, $formContent);
            $formContent = str_replace('{ModuleFormEdit}', $moduleFormEdit, $formContent);
            $formContent = str_replace('{ModuleFormReset}', $moduleFormReset, $formContent);
            file_put_contents($viewComponentFolder . "/{$listNameUpper}Detail.vue", $formContent);
            $message .= "Created Form Detail: resources/js/views/{$viewName}/components/{$listNameUpper}Detail.vue \r\n";
            print "[OK] Generated Module Form.\r\n";
        }

        //Language
        $langModuleName = strtolower($moduleName);
        foreach ($languages as $langItem) {
            $langFile = $basePath . "/resources/js/lang/{$langItem}.js";
            if (file_exists($langFile)) {
                $routerLang = "{$langModuleName}: '{$moduleName}',\r\n\t\t";
                $routerLang .= "{$langModuleName}List: 'All {$moduleName}',\r\n\t\t";
                $routerLang .= "{$langModuleName}Create: 'Create {$moduleName}',\r\n\t\t";
                $routerLang .= "{$langModuleName}Edit: 'Edit {$moduleName}',\r\n\t\t";
                $routerLang .= "/*{importRouterLang}*/";
                $langContent = file_get_contents($langFile);
                $langContent = str_replace("/*{importRouterLang}*/", $routerLang, $langContent);

                $moduleLangTemplate = $templatePath . "Language.template";
                if (file_exists($moduleLangTemplate)) {
                    $langTemplateContent = file_get_contents($moduleLangTemplate);
                    $langTemplateContent = str_replace('{ModuleName}', $listName, $langTemplateContent);
                    $langTemplateContent = str_replace('{ModuleNameUpper}', $listNameUpper, $langTemplateContent);
                    $listFieldLabel = "";
                    $listFieldRules = "";
                    if (count($listFieldItems) > 0) {
                        foreach ($listFieldItems as $it) {
                            if ($it['name'] == 'id' || $it['name'] == 'is_deleted') continue;
                            $fLabel = str_replace("_", " ", $it['name']);
                            $fLabel = ucfirst(strtolower($fLabel));

                            if ($it['name'] != 'status' && $it['name'] != 'is_activated') {
                                $listFieldLabel .= "{$it['name']}: '{$fLabel}',\r\n\t\t\t";
                                /*$listFieldLabel .= "status: 'Status',\r\n\t\t\t";
                                $listFieldLabel .= "status_0: 'Not activated',\r\n\t\t\t";
                                $listFieldLabel .= "status_1: 'Activated',\r\n\t\t\t";*/
                            }

                            if ($it['rule'] == 'required') {
                                $listFieldRules .= "required_{$it['name']}: '{$fLabel} is required',\r\n\t\t\t";
                            }
                        }
                    }
                    $langTemplateContent = str_replace('{ModuleFields}', $listFieldLabel, $langTemplateContent);
                    $langTemplateContent = str_replace('{ModuleFieldRule}', $listFieldRules, $langTemplateContent);
                    $langTemplateContent .= "\r\n\t/*{importModuleLang}*/";
                    $langContent = str_replace("/*{importModuleLang}*/", $langTemplateContent, $langContent);
                }
                file_put_contents($langFile, $langContent);
                $message .= "Updated Lang {$langItem}: resources/js/lang/{$langItem}.js \r\n";
                print "[OK] Generated Module Language " . strtoupper($langItem) . ".\r\n";
            }
        }

        //Api Routes
        $apiName = strtolower($moduleName);
        $apiNameUpper = ucfirst($apiName);
        $apiNameUpperAll = strtoupper($apiName);
        $apiTemplateFile = $templatePath . "Api.template";
        $apiFileName = $basePath . "/routes/api.php";
        if (file_exists($apiTemplateFile) && file_exists($apiFileName)) {
            $apiContent = file_get_contents($apiTemplateFile);
            $apiContent = str_replace('{ModuleName}', $apiName, $apiContent);
            $apiContent = str_replace('{ModuleNameUpper}', $apiNameUpper, $apiContent);
            $apiContent = str_replace('{ModuleNameUpperAll}', $apiNameUpperAll, $apiContent);
            $apiContentAll = file_get_contents($apiFileName);
            $apiContentAll = str_replace('/*{importModuleApi}*/', $apiContent . "\r\n\r\n\t\t/*{importModuleApi}*/", $apiContentAll);
            file_put_contents($apiFileName, $apiContentAll);
            $message .= "Updated Web API: routes/api.php \r\n";
            print "[OK] Generated Module Web API.\r\n";
        }

        //Controller
        $controllerName = strtolower($moduleName);
        $controllerNameUpper = ucfirst($controllerName);
        $controllerTemplateFile = $templatePath . "Controller.template";
        $controllerFileName = $basePath . "/app/Http/Controllers/Admin/{$moduleName}Controller.php";
        if (file_exists($controllerTemplateFile) && !file_exists($controllerFileName)) {
            $controllerContent = file_get_contents($controllerTemplateFile);
            $controllerContent = str_replace('{ModuleName}', $controllerName, $controllerContent);
            $controllerContent = str_replace('{ModuleNameUpper}', $controllerNameUpper, $controllerContent);
            $controllerContent = str_replace('{ModuleNameList}', $controllerName . 'List', $controllerContent);

            file_put_contents($controllerFileName, $controllerContent);
            $message .= "Creating Web Controller: app/Http/Controllers/Admin/{$moduleName}Controller.php \r\n";
            print "[OK] Generated Module Web Controller.\r\n";
        }

        //Web Resource
        $webResourceNameUpper = ucfirst(strtolower($moduleName));
        $webResourceTemplateFile = $templatePath . "WebResource.template";
        $webResourceFileName = $basePath . "/app/Http/Resources/Admin/{$moduleName}Resource.php";
        if (file_exists($webResourceTemplateFile) && !file_exists($webResourceFileName)) {
            $webResourceContent = file_get_contents($webResourceTemplateFile);
            $webResourceContent = str_replace('{ModuleNameUpper}', $webResourceNameUpper, $webResourceContent);
            file_put_contents($webResourceFileName, $webResourceContent);
            $message .= "Creating Web Resource: app/Http/Resources/Admin/{$moduleName}Resource.php \r\n";
            print "[OK] Generated Module Web Resource.\r\n";
        }

        $message .= "===========================================================================\r\n";
        $message .= "\r\nModule [{$moduleName}] created successfully.\r\n";
        $this->info($message);

        if ($this->confirm('Do you want to run migrate and reload permission now?')) {
            shell_exec("php artisan migrate && php artisan db:seed --class=ReloadPermission && composer dump-autoload");
        } else {
            $this->info("=> Please run command: php artisan migrate && php artisan db:seed --class=ReloadPermission && composer dump-autoload\r\n");
        }

        //Save Module for other systems
        $moduleDataFile = $basePath . "/app/Console/Commands/ModuleData/modules.json";
        if (file_exists($moduleDataFile)) {
            $allModule = Module::all();
            if ($allModule->count() > 0) file_put_contents($moduleDataFile, json_encode($allModule->toArray()));
            $this->info("=> Note! Please run this command to apply modules for other systems: composer dump-autoload && php artisan module:update");
        }
    }
}
