<?php
/**
 * Livewire Component
 *
 * @version     1.0.$Revision:$
 * @version     SVN: $Id:$
 * @package     bplan-base/globals
 * @subpackage  LivewireComponents
 * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
 * @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\Livewire\Printer\Modals;


use BplanBase\Globals\Models\Printer;
use BplanBase\Globals\Repositories\LocationRepository;
use BplanBase\Globals\Repositories\PrinterTypeRepository;
use BplanBase\Globals\Services\PrinterService;
use BplanBase\Globals\Traits\InteractsWithBanner;
use BplanBase\Globals\Traits\ProcessesConfigTemplate;
use Illuminate\Database\Eloquent\Collection;
use Livewire\Attributes\On;
use Livewire\Component;


/**
 * Livewire Component
 *
 * @version     1.0.0 / 2026-05-06
 * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 */
class Edit extends Component
{


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


    use InteractsWithBanner;
    use ProcessesConfigTemplate;


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


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


    /**
     * @var     bool
     */
    public bool $active = true;


    /**
     * @var     array
     */
    public array $configSections = [];


    /**
     * @var     array
     */
    public array $configSettings = [];


    /**
     * @var     string|null
     */
    public ?string $host = null;


    /**
     * @var     string|null
     */
    public ?string $label = null;


    /**
     * @var     Collection|null
     */
    public ?Collection $Locations;


    /**
     * @var     string|null
     */
    public ?string $locationId = null;


    /**
     * @var     string|null
     */
    public ?string $name = null;


    /**
     * @var     Printer|null
     */
    public ?Printer $Printer = null;


    /**
     * @var     array|null
     */
    public ?array $printerTypeConfigTemplate = null;


    /**
     * @var     string|null
     */
    public ?string $printerTypeId = null;


    /**
     * @var     Collection|null
     */
    public ?Collection $PrinterTypes;


    /**
     * @var     PrinterService
     */
    protected PrinterService $_Service;


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


    /**
     * @var     string
     */
    private static string $_logPrefix = 'Printer/Modals/Edit';


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


    /**
     *
     * @param       PrinterService $Service
     *
     * @version     1.0.0 / 2026-05-06
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function boot(PrinterService $Service): void
    {
        $this->_Service   = $Service;
        $this->Locations  = LocationRepository::getAll();
        $this->PrinterTypes = PrinterTypeRepository::getAll();

    } // boot()


    /**
     *
     * @version     1.0.0 / 2026-05-06
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function deletePrinter(): void
    {
        try {
            $label = $this->Printer->label;

            $this->_Service->delete($this->Printer->id);

            $User = auth()->user();

            \AppLog::info('Printer ['.$label.'] deleted by ['.$User->name.' ('.$User->email.')]', self::$_logPrefix);

            $this->dispatch('init-tippyjs');
            $this->dispatch('printer-deleted');

        } catch (\Throwable $th) {
            \AppLog::error($th, self::$_logPrefix);

            $this->dangerBanner(__('globals::printers.error.delete-error'));
        }

    } // deletePrinter()


    /**
     *
     * @version     1.0.0 / 2026-05-06
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function editPrinter(): void
    {
        $this->validate();

        try {
            $this->_Service->update($this->Printer->id, [
                'active'          => $this->active,
                'config_settings' => $this->_encodeConfigSettings($this->configSettings) ?? null,
                'host'            => $this->host,
                'label'           => $this->label,
                'location_id'     => $this->locationId ?: null,
                'name'            => $this->name,
                'printer_type_id' => $this->printerTypeId,
            ]);

            $User = auth()->user();

            \AppLog::info('Printer ['.$this->label.'] edited by ['.$User->name.' ('.$User->email.')]', self::$_logPrefix);

            $this->dispatch('init-tippyjs');
            $this->dispatch('printer-edited');

        } catch (\Throwable $th) {
            \AppLog::error($th, self::$_logPrefix);

            $this->dangerBanner(__('globals::printers.error.update-error'));
        }

    } // editPrinter()


    /**
     *
     * @param       array $printer
     *
     * @version     1.0.0 / 2026-05-06
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    #[On('show-edit-printer-modal')]
    public function initPrinter(array $printer): void
    {
        $this->Printer = Printer::findOrFail($printer['id']);

        $this->active        = $this->Printer->active;
        $this->host          = $this->Printer->host;
        $this->label         = $this->Printer->label;
        $this->locationId    = $this->Printer->location_id ? (string) $this->Printer->location_id : null;
        $this->name          = $this->Printer->name;
        $this->printerTypeId = (string) $this->Printer->printer_type_id;

        $this->_loadPrinterTypeTemplate();

        $existingSettings = $this->_decodeConfigSettings(
            is_array($this->Printer->config_settings)
                ? json_encode($this->Printer->config_settings)
                : $this->Printer->config_settings
        );

        if ($existingSettings !== null) {
            foreach ((array) $existingSettings as $key => $value) {
                $this->configSettings[$key] = (string) $value;
            }
        }

        $this->resetValidation();

        $this->dispatch('init-tippyjs');

    } // initPrinter()


    /**
     *
     * @version     1.0.0 / 2026-05-06
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function render()
    {
        return view('globals::livewire.printer.modals.edit');

    } // render()


    /**
     *
     * @version     1.0.0 / 2026-05-06
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function resetModal(): void
    {
        $this->active                    = true;
        $this->configSections            = [];
        $this->configSettings            = [];
        $this->host                      = null;
        $this->label                     = null;
        $this->locationId                = null;
        $this->name                      = null;
        $this->Printer                   = null;
        $this->printerTypeConfigTemplate = null;
        $this->printerTypeId             = null;

        $this->resetValidation();

    } // resetModal()


    /**
     *
     * @return      array
     *
     * @version     1.0.0 / 2026-05-06
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function rules(): array
    {
        return [
            'active'           => ['boolean'],
            'configSettings'   => ['array'],
            'configSettings.*' => ['nullable', 'string'],
            'host'             => ['required', 'string', 'max:255'],
            'label'            => ['required', 'string', 'max:255'],
            'locationId'       => ['nullable', 'integer', 'exists:locations,id'],
            'name'             => ['required', 'string', 'max:255'],
            'printerTypeId'    => ['required', 'integer', 'exists:printer_types,id'],
        ];

    } // rules()


    /**
     *
     * @param       string $field
     * @param       mixed  $value
     *
     * @version     1.0.0 / 2026-05-06
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function updated(string $field): void
    {
        if ($field === 'printerTypeId') {
            $this->configSettings = [];
            $this->_loadPrinterTypeTemplate();
        }

    } // updated()


    /**
     *
     * @version     1.0.0 / 2026-05-06
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    private function _loadPrinterTypeTemplate(): void
    {
        if (empty($this->printerTypeId) === true) {
            $this->printerTypeConfigTemplate = null;
            $this->configSections            = [];

            return;
        }

        $PrinterType = PrinterTypeRepository::getById($this->printerTypeId, returnOrFail: false);

        if ($PrinterType === null) {
            $this->printerTypeConfigTemplate = null;
            $this->configSections            = [];

            return;
        }

        $configTemplateJson = is_string($PrinterType->config_template)
            ? $PrinterType->config_template
            : json_encode($PrinterType->config_template);

        $result = $this->_prepareConfigTemplate($configTemplateJson);

        $this->printerTypeConfigTemplate = $result['template'];
        $this->configSections            = $result['sections'];

        if ($this->printerTypeConfigTemplate !== null) {
            foreach ($this->printerTypeConfigTemplate as $section) {
                foreach ($section as $Settings) {
                    if (isset($this->configSettings[$Settings->name]) === false) {
                        $this->configSettings[$Settings->name] = isset($Settings->default) ? (string) $Settings->default : '';
                    }
                }
            }
        }

    } // _loadPrinterTypeTemplate()


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


} // class Edit extends Component {}
