<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class GenerateCCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'generatec
                            {path: /path/to/controller.json}';

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

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //

        global $argv;
        $controllers = json_decode(file_get_contents($argv[2]));

//        Route::get('/my-payments-schedule', 'MyPaymentScheduleController@index');
//        Route::get('/my-teams', 'MyTeamsController@index');
//        Route::get('/my-clients', 'MyClientsController@index');
//        Route::get('/notes', 'NotesController@index');
//        Route::get('/erx', 'ERXController@index');
//        Route::get('/action-items', 'ActionItemsController@index');
//        Route::get('/care-months', 'CareMonthsController@index');
//        Route::get('/bills', 'BillsController@index');
//        Route::get('/transactions', 'TransactionsController@index');
//        Route::get('/med-profile-lines', 'MedProfileLinesController@index');
//        Route::get('/mcp-updates', 'McpUpdatesController@index');
//        Route::get('/ally-updates', 'AllyUpdatesController@index');
//        Route::get('/audit-log', 'AuditLogController@index');

        $routesText = ["/* __SCAFFOLD_ROUTES__ */"];
        $linksText = ["<!-- __SCAFFOLD_LINKS__ -->"];



        foreach ($controllers as $name => $object) {

            if(isset($object->todo)) continue;

            // routes
            $routesText[] = "/* SCAF */// $object->slug CRUD";
            $routesText[] = "/* SCAF */Route::get ('/$object->slug', '{$name}Controller@index')->name('{$object->slug}-index');";
            $routesText[] = "/* SCAF */Route::get ('/$object->slug/{id}', '{$name}Controller@show')->name('{$object->slug}-view');";
            $routesText[] = "/* SCAF */Route::get ('/$object->slug/create', '{$name}Controller@create')->name('{$object->slug}-create');";
            $routesText[] = "/* SCAF */Route::get ('/$object->slug/update/{id}', '{$name}Controller@update')->name('{$object->slug}-update');";

            // left nav links
            $linksText[] =
'<!-- SCAF --><li class="nav-item"><a href="/' . $object->slug . '" class="nav-link"><i class="nav-icon ' . $object->icon . '"></i><p>' . $object->text . '</p></a></li>';

            // controller
            $template = file_get_contents(base_path('generatecv/controller.template.php'));
            $text = str_replace("_NAME_", $name, $template);
            $text = str_replace("_MODEL_", $object->model, $text);
            $text = str_replace("_SLUG_", $object->slug, $text);
//            if(!file_exists(app_path("Http/Controllers/{$name}Controller.php"))) {
                file_put_contents(app_path("Http/Controllers/{$name}Controller.php"), $text);
                echo "Generated " . app_path("Http/Controllers/{$name}Controller.php") . "\n";
//            }

            // views - index
            if(isset($object->list)) {
                $template = file_get_contents(base_path('generatecv/listing.template.blade.php'));
                $text = str_replace("_NAME_", $object->text, $template);
                $text = str_replace("_SLUG_", $object->slug, $text);
                $ths = [];
                foreach ($object->list as $field => $display) {
                    $ths[] = "<th>{$display}</th>";
                }
                $ths = implode("\n", $ths);
                $text = str_replace("<!-- __SCAFFOLD_THS__ -->", $ths, $text);
                $tds = [];
                foreach ($object->list as $field => $display) {
                    if($field === 'id') {
                        $tds[] = '<td><a href="/' . $object->slug . '/<?= $row->uid ?>"><?= $row->' . $field . ' ?></a></td>';
                    }
                    else {
                        $tds[] = '<td><?= $row->' . $field . ' ?></td>';
                    }
                }
                $tds = implode("\n", $tds);
                $text = str_replace("<!-- __SCAFFOLD_TDS__ -->", $tds, $text);
//                if(!file_exists(resource_path("views/{$object->slug}/index.blade.php"))) {
                    $this->file_force_contents(resource_path("views/{$object->slug}/index.blade.php"), $text);
                    echo "Generated " . resource_path("views/{$object->slug}/index.blade.php") . "\n";
//                }
            }

            if(isset($object->show)) {
                $template = file_get_contents(base_path('generatecv/show.template.blade.php'));
                $dts = [];
                foreach ($object->show as $field => $display) {
                    $dts[] = "<dt class='col-md-2'>{$display}</dt>" .
                        '<dd class="col-md-10"><?= $row->' . $field . ' ?></dd>';
                }
                $dts = implode("\n", $dts);
                $text = str_replace("<!-- __SCAFFOLD_DTS__  -->", $dts, $template);
//                if(!file_exists(resource_path("views/{$object->slug}/show.blade.php"))) {
                    $this->file_force_contents(resource_path("views/{$object->slug}/show.blade.php"), $text);
                    echo "Generated " . resource_path("views/{$object->slug}/show.blade.php") . "\n";
//                }
            }

        }

        // write routes
        $text = [];
        $file = fopen(base_path("routes/web.php"), "r");
        while (!feof($file)) {
            $line = rtrim(fgets($file));
            if(strpos($line, "/* SCAF */") === FALSE) {
                $text[] = $line;
            }
        }
        $text = implode("\n", $text);
        fclose($file);
        $text = str_replace("/* __SCAFFOLD_ROUTES__ */", implode("\n", $routesText), $text);
        file_put_contents(base_path("routes/web.php"), $text);
        echo "Updated " . base_path("routes/web.php") . "\n";

        // write left nav links
        $text = [];
        $file = fopen(resource_path("views/layouts/pro-logged-in.blade.php"), "r");
        while (!feof($file)) {
            $line = rtrim(fgets($file));
            if(strpos($line, "<!-- SCAF -->") === FALSE) {
                $text[] = $line;
            }
        }
        $text = implode("\n", $text);
        fclose($file);
        $text = str_replace("<!-- __SCAFFOLD_LINKS__ -->", implode("\n", $linksText), $text);
        file_put_contents(resource_path("views/layouts/pro-logged-in.blade.php"), $text);
        echo "Updated " . resource_path("views/layouts/pro-logged-in.blade.php") . "\n";

    }

    private function file_force_contents($dir, $contents){
        $parts = explode('/', $dir);
        $file = array_pop($parts);
        $dir = '';
        foreach($parts as $part)
            if(!is_dir($dir .= "/$part")) mkdir($dir);
        file_put_contents("$dir/$file", $contents);
    }
}
