<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;

class ClearCachesAll extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'clear-caches-all';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Clear all caches in the application';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        Artisan::call('cache:clear');

        // Clear configuration cache
        if (file_exists(base_path('bootstrap/cache/config.php'))) {
            @unlink(base_path('bootstrap/cache/config.php'));
        }

        // Clear event cache
        if (file_exists(base_path('bootstrap/cache/events.php'))) {
            @unlink(base_path('bootstrap/cache/events.php'));
        }

        // Clear route cache
        if (file_exists(base_path('bootstrap/cache/routes.php'))) {
            @unlink(base_path('bootstrap/cache/routes.php'));
        }

        // Clear view cache
        $views = glob(storage_path('framework/views/*.php'));
        foreach ($views as $view) {
            @unlink($view);
        }

        // Clear compiled caches
        $paths = [
            base_path('bootstrap/cache/compiled.php'),
            base_path('bootstrap/cache/services.php'),
        ];
        foreach ($paths as $path) {
            if (file_exists($path)) {
                @unlink($path);
            }
        }

        // Run `composer install`
        $output = [];
        $returnVar = null;
        exec('composer install 2>&1', $output, $returnVar);

        // Output the result of the Composer command
        if ($returnVar === 0) {
            $this->info("Composer install ran successfully:\n" . implode("\n", $output));
        } else {
            $this->error("Composer install failed:\n" . implode("\n", $output));
        }
        
        // run command RestartSupervisor
        $output = [];
        $returnVar = null;
        exec('php artisan supervisor:restart 2>&1', $output, $returnVar);   
        
        // output result of command RestartSupervisor
        if ($returnVar === 0) {
            $this->info("Restart Supervisor ran successfully:\n" . implode("\n", $output));
        } else {
            $this->error("Restart Supervisor failed:\n" . implode("\n", $output));
        }   

        $this->info("All caches have been cleared.");
    }
}
