<?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\Location;
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 BplanBase\Globals\Traits\WithComboBoxInput;
use Illuminate\Database\Eloquent\Collection;
use Livewire\Attributes\On;
use Livewire\Component;


/**
 * Livewire Component
 *
 * @version     2.1.0 / 2026-05-24
 * @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;
    use WithComboBoxInput;


/* +++ 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     Collection|null
     */
    public ?Collection $KioskLocations;


    /**
     * @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 +++ +++++++++++++++++++++++++++++++++++++++++++++++++++ */


    /**
     *
     * @return      array<int>
     *
     * @version     1.0.0 / 2026-05-10
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    private function _getSelectedLocationIds(): array
    {
        return array_values(array_map(
            fn($item) => $item['id'],
            array_filter(
                $this->comboBoxData['locations'] ?? [],
                fn($item) => ($item['isSelected'] ?? false) === true
            )
        ));
    } // _getSelectedLocationIds()


    /**
     *
     * @version     1.1.0 / 2026-05-24
     * @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'];

        $this->configSettings = $this->_applyConfigDefaults($this->printerTypeConfigTemplate, $this->configSettings);
    } // _loadPrinterTypeTemplate()


    /**
     *
     * @version     1.0.0 / 2026-05-10
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    private function _setupComboBoxes(): void
    {
        $this->comboBoxData['locations'] = ($this->KioskLocations ?? collect())->map(function ($Location) {
            return [
                'id'    => $Location->id,
                'label' => $Location->label ?? $Location->identifier,
            ];
        })->toArray();

        $this->filteredComboBoxData = $this->comboBoxData;

    } // _setupComboBoxes()


    /**
     *
     * @param       \BplanBase\Globals\Models\Printer $Printer
     *
     * @version     1.0.0 / 2026-05-10
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    private function _syncLocations(\BplanBase\Globals\Models\Printer $Printer): void
    {
        $newIds     = $this->_getSelectedLocationIds();
        $currentIds = $Printer->locations()->pluck('locations.id')->toArray();

        $toDetach = array_diff($currentIds, $newIds);
        $toAttach = array_diff($newIds, $currentIds);

        if (empty($toDetach) === false) {
            $Printer->locations()->detach($toDetach);
        }

        foreach ($toAttach as $locationId) {
            $Printer->locations()->attach($locationId, [
                'uuid'       => (string) \Illuminate\Support\Str::uuid(),
                'created_at' => now(),
            ]);
        }
    } // _syncLocations()


    /**
     *
     * @param       PrinterService $Service
     *
     * @version     1.1.0 / 2026-05-10
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function boot(PrinterService $Service): void
    {
        $this->_Service       = $Service;
        $this->KioskLocations = LocationRepository::getAll(Query: Location::whereHas(
            'locationType',
            fn($Query) => $Query->where('identifier', '=', 'AccessPoint')

        )->where('sub_type', '=', 'Kiosk'), withInternal: true);

        $this->Locations      = LocationRepository::getAll(withInternal: true);
        $this->PrinterTypes   = PrinterTypeRepository::getAll();

        if (isset($this->comboBoxData) === false) {
            $this->_setupComboBoxes();
        }
    } // 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.1.0 / 2026-05-10
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function editPrinter(): void
    {
        $this->validate();

        try {
            $Printer = $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,
            ]);

            $this->_syncLocations($Printer);

            $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.2.0 / 2026-05-10
     * @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->_setupComboBoxes();

        $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();

        $rawSettings = $this->Printer->config_settings;

        $existingSettings = $this->_decodeConfigSettings(
            (is_array($rawSettings) || is_object($rawSettings))
                ? json_encode($rawSettings)
                : $rawSettings
        );

        if ($existingSettings !== null) {
            foreach ((array) $existingSettings as $key => $value) {
                $this->configSettings[$key] = (string) $value;
            }
        }
        $assignedLocationIds = $this->Printer->locations->pluck('id')->toArray();

        foreach ($this->comboBoxData['locations'] as $index => $item) {
            if (in_array($item['id'], $assignedLocationIds, true) === true) {
                $this->comboBoxData['locations'][$index]['isSelected'] = true;
            }
        }
        $this->filteredComboBoxData = $this->comboBoxData;

        $this->resetValidation();

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

    } // 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.1.0 / 2026-05-10
     * @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->_setupComboBoxes();
        $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()


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


} // class Edit extends Component {}
