<?php
/**
 * WarmUp Command Class
 *
 * @version     1.0.$Revision:$
 * @version     SVN: $Id:$
 * @package     bplan-base/globals
 * @subpackage  Commands
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 * @copyright   Copyright (C) 2025 bplan-solutions GmbH & Co. KG <https://www.bplan-solutions.de/>
 * /Δ\
 */

namespace BplanBase\Globals\Console\Commands;


use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\View;


/**
 * WarmUp Command Class
 *
 * @version     1.1.0 / 2025-09-01
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 */
class WarmUpApp extends Command
{


/* +++ TRAITS +++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ CLASS CONSTANTS +++ ++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ OBJECT MEMBERS +++ +++++++++++++++++++++++++++++++++++++++++++++++++++ */


    /**
     * The name and signature of the console command.
     *
     * php artisan app:warmup
     */
    protected $signature = 'globals:app-warmup';

    /**
     * The console command description.
     */
    protected $description = 'Pre-build Laravel caches and warm up important routes';


/* +++ CLASS MEMBERS +++ ++++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ OBJECT METHODS +++ +++++++++++++++++++++++++++++++++++++++++++++++++++ */


    /**
     *
     * @version     1.1.0 / 2025-09-01
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    protected function _rebuildCaches(): void
    {
        $this->info("\n".'  Clearing and rebuilding caches …');

        $cmds = [
            'config:clear',
            'config:cache',
            'route:clear',
            'route:cache',
            'view:clear',
            'view:cache',
            'event:clear',
            'event:cache',
        ];
        $php = 'php';

        foreach ($cmds as $cmd) {
            exec($php.' artisan '.$cmd.' >> '.storage_path('logs/demo-reset.log').' 2>&1');
        }
        $this->info('  Laravel caches rebuilt.');

    } // _rebuildCaches()


    /**
     *
     * @version     1.1.0 / 2025-09-01
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    protected function _warmUpUrls(): void
    {
        // Optional: wichtige URLs zum Vorwärmen definieren
        $urls = [];

        $urls = array_merge($urls, config('globals.warm-up-urls', []), config('project.warm-up-urls', []));

        $this->info("\n".'  Warming up important URLs …');

        foreach ($urls as $url) {
            try {
                Http::timeout(10)->get(url($url));

                $this->line('  ✔ Warmed up ['.$url.']');

            } catch (\Throwable $E) {
                $this->warn('  ⚠ Could not warm up ['.$url.']: '.$E->getMessage());
            }
        }

    }

    /**
     * Rendert alle Views im resource_path('views'), um Blade-Templates vorzukompilieren.
     * Übergibt Dummy-Daten, falls die View Variablen benötigt.
     *
     * @version     1.0.0 / 2025-08-28
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    protected function _warmUpViews(): void
    {
        $viewsPath = resource_path('views');

        $e = $s = 0;

        $this->info("\n".'  Warming up views …');

        foreach (File::allFiles($viewsPath) as $file) {
            $path = $file->getRelativePathname();

            // z. B. "admin/index.blade.php" → "admin.index"
            $name = str_replace(['/', '\\'], '.', $path);
            $name = preg_replace('/\.blade\.php$/', '', $name);

            try {
                // Dummy-Daten für gängige Variablen
                $vars = [
                    'attributes' => collect([]),
                    'AuthUser' => \App\Models\User::first() ?? new \App\Models\User(),
                    'content' => '',
                    'countries' => [],
                    'data' => [],
                    'description' => '',
                    'footer' => '',
                    'items' => collect([]),
                    'labelsJson' => [],
                    'lang' => 'en',
                    'languages' => [],
                    'locations' => [],
                    'logo' => '',
                    'request' => request(),
                    'slot' => '',
                    'state' => true,
                    'tenantId' => 1,
                    'title' => '',
                    'url' => '',
                    'user' => \App\Models\User::first() ?? new \App\Models\User(),
                ];
                $vars = array_merge($vars, config('project.warm-up-vars', []));

                // View mit Dummy-Daten rendern
                View::make($name, $vars)->render();

                $this->line('  ✔ Warmed up view ['.$name.']');
                $s++;

            } catch (\Throwable $E) {
                $this->warn('  ⚠ Could not warm up view ['.$name.']: '.str_replace(' (', "\n".'    (', $E->getMessage())."\n");
                $e++;
            }
        }
        $this->info($s.' / '.$e);

    } // _warmUpViews()


    /**
     * Execute the console command.
     *
     * @version     1.0.0 / 2025-08-28
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function handle(): int
    {
        $this->_rebuildCaches();
        $this->_warmUpUrls();
        $this->_warmUpViews();

        $this->info("\n".'  Warm-up finished!');

        return self::SUCCESS;

    } // handle()


/* +++ CLASS METHODS +++ ++++++++++++++++++++++++++++++++++++++++++++++++++++ */


} // class WarmUpApp extends Command {}
