<?php

namespace App\Console\Commands;

use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class RestartSupervisor extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'supervisor:restart';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Restart all Supervisor services';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        try {
            // Check if supervisorctl is installed
            $isSupervisorctlInstalled = shell_exec('command -v supervisorctl');

            if (!$isSupervisorctlInstalled) {
                $errorMessage = 'Error: supervisorctl is not installed.';
                $this->error($errorMessage);
                Log::error($errorMessage);
                return 1;
            }

            // Restart all Supervisor services
            $output = shell_exec('supervisorctl restart all 2>&1');

            // Log and display the output
            Log::info("supervisorctl restart all executed with output: {$output}");
            $this->info("Supervisor services restarted. Output: {$output}");

            return 0;
        } catch (Exception $e) {
            $this->error("An error occurred: " . $e->getMessage());
            Log::error("Error in RestartSupervisor command: " . $e->getMessage());
            return 1;
        }
    }
}
