<?php
/**
 * Setup 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, 2026 bplan-solutions GmbH & Co. KG <https://www.bplan-solutions.de/>
 * /Δ\
 */

namespace BplanBase\Globals\Console\Commands;


use BplanBase\Globals\Models\PrintJob;
use BplanBase\Globals\Services\PrintService;
use Illuminate\Console\Command;


/**
 * @version     1.0.0 / 2026-05-07
 *
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 */
class TriggerPrintJob extends Command
{


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


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


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


    /**
     * @var string
     */
    protected $description = 'Triggers an existing print job by its ID';

    /**
     * @var string
     */
    protected $signature = 'globals:trigger-print-job {id? : The ID of the print_jobs record}';


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


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


    /**
     * @version     1.0.0 / 2026-05-07
     *
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function handle(): int
    {
        $id = $this->argument('id');

        if (empty($id) === true) {
            $id = $this->ask('Print Job ID');
        }

        $PrintJob = PrintJob::with(['printer.printerType'])->find((int) $id);

        if ($PrintJob === null) {
            $this->error('PrintJob #'.$id.' not found.');

            return self::FAILURE;
        }

        if ($PrintJob->printer === null) {
            $this->error('PrintJob #'.$id.' has no printer assigned.');

            return self::FAILURE;
        }

        $this->info('Triggering PrintJob #'.$PrintJob->id);
        $this->info(' Printer: '.$PrintJob->printer->name.' '.$PrintJob->printer->host);
        $this->info(' Status : '.$PrintJob->status);
        $this->newLine();

        try {
            $Response = PrintService::forHost($PrintJob->printer->host)->sendJob($PrintJob);

        } catch (\Throwable $E) {
            $this->error('Failed to send print job: '.$E->getMessage());

            return self::FAILURE;
        }

        if ($Response->successful() === true) {
            $this->info('Print job sent successfully. HTTP '.$Response->status());

        } else {
            $this->warn('Print service responded with HTTP '.$Response->status());
            $this->line($Response->body());
        }
        return self::SUCCESS;

    } // handle()


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


} // class TriggerPrintJob extends Command {}
