<?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\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\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 Create 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     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/Create';


/* +++ 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.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()


    /**
     *
     * @return      array<int>
     *
     * @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.1.0 / 2026-05-10
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function createPrinter(): void
    {
        $this->validate();

        try {
            $Printer = $this->_Service->create([
                '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.'] created by ['.$User->name.' ('.$User->email.')]', self::$_logPrefix);

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

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

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

    } // createPrinter()


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

    } // render()


    /**
     *
     * @version     1.0.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->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->_loadPrinterTypeTemplate();
        }

    } // updated()


    /**
     *
     * @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            = [];
            $this->configSettings            = [];

            return;
        }

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

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

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


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


} // class Create extends Component {}
