<?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\PrinterType\Modals;


use BplanBase\Globals\Models\PrinterType;
use BplanBase\Globals\Services\PrinterTypeService;
use BplanBase\Globals\Traits\InteractsWithBanner;
use Livewire\Attributes\On;
use Livewire\Component;


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


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


    use InteractsWithBanner;


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


    /**
     * Konvertiert einen config_template- oder payload_template-Wert für die
     * Textarea-Darstellung in einen formatierten JSON-String.
     *
     * Behandelt drei Fälle:
     * - null       → null (leeres Feld)
     * - string     → direkt übernehmen (Legacy-Daten, die bereits als String
     *                in der DB liegen)
     * - object/array → json_encode mit Pretty-Print
     *
     * @param       mixed $value
     *
     * @return      string|null
     *
     * @version     1.0.0 / 2026-05-10
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    private function _templateToString(mixed $value): ?string
    {
        if ($value === null) {
            return null;
        }

        if (is_string($value) === true) {
            return $value;
        }
        return json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

    } // _templateToString()


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

    } // boot()


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

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

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

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

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

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

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

    } // deletePrinterType()


    /**
     *
     * @version     1.1.0 / 2026-05-10
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function editPrinterType(): void
    {
        $this->configTemplate  = empty($this->configTemplate)  ? '{}' : $this->configTemplate;
        $this->payloadTemplate = empty($this->payloadTemplate) ? '{}' : $this->payloadTemplate;

        $this->validate();

        try {
            $this->_Service->update($this->PrinterType->id, [
                'active'           => $this->active,
                'brand'            => $this->brand,
                'config_template'  => json_decode($this->configTemplate),
                'description'      => $this->description,
                'identifier'       => $this->identifier,
                'label'            => $this->label,
                'model'            => $this->model,
                'payload_template' => json_decode($this->payloadTemplate),
            ]);

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

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

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

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

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

    } // editPrinterType()


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

        $this->active          = $this->PrinterType->active;
        $this->brand           = $this->PrinterType->brand;
        $this->configTemplate  = $this->_templateToString($this->PrinterType->config_template);
        $this->description     = $this->PrinterType->description;
        $this->identifier      = $this->PrinterType->identifier;
        $this->label           = $this->PrinterType->label;
        $this->model           = $this->PrinterType->model;
        $this->payloadTemplate = $this->_templateToString($this->PrinterType->payload_template);

        $this->resetValidation();

        $this->dispatch('init-tippyjs');
        $this->dispatch('printer-type-data-loaded');

    } // initPrinterType()


    /**
     *
     * @version     1.0.0 / 2026-05-06
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function render()
    {
        return view('globals::livewire.printer-type.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->brand           = null;
        $this->configTemplate  = null;
        $this->description     = null;
        $this->identifier      = null;
        $this->label           = null;
        $this->model           = null;
        $this->payloadTemplate = null;
        $this->PrinterType     = 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'],
            'brand'           => ['required', 'string', 'max:255'],
            'configTemplate'  => ['nullable', 'string', 'json'],
            'description'     => ['nullable', 'string', 'max:255'],
            'identifier'      => ['required', 'string', 'max:255', 'unique:printer_types,identifier,'.$this->PrinterType?->id],
            'label'           => ['required', 'string', 'max:255'],
            'model'           => ['required', 'string', 'max:255'],
            'payloadTemplate' => ['nullable', 'string', 'json'],
        ];

    } // rules()


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


} // class Edit extends Component {}
