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


use BplanBase\Globals\Models\Location;
use BplanBase\Globals\Models\LocationType;
use BplanBase\Globals\Repositories\LocationTypeRepository;
use BplanBase\Globals\Repositories\PrinterRepository;
use BplanBase\Globals\Services\LocationService;
use BplanBase\Globals\Traits\InteractsWithBanner;
use Illuminate\Database\Eloquent\Collection;
use Livewire\Attributes\On;
use Livewire\Attributes\Validate;
use Livewire\Component;


/**
 * Livewire Component
 *
 * @version     1.1.0 / 2026-06-08
 * @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     boolean
     */
    // #[Validate('required')]
    public bool $active = true;


    /**
     * @var     string|null
     */
    // #[Validate('required')]
    public ?string $addressAddition = null;


    /**
     * @var     string|null
     */
    // #[Validate('required')]
    public ?string $city = null;


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


    /**
     * @var     string|null
     */
    // #[Validate('required')]
    public ?string $email = null;


    /**
     * @var     string|null
     */
    // #[Validate('required')]
    public ?string $houseNumber = null;


    /**
     * @var     boolean
     */
    // #[Validate('required')]
    public bool $isBookable = false;


    /**
     * @var     bool
     */
    // #[Validate('required')]
    public bool $internal = false;


    /**
     * @var     array|null
     */
    #[Validate('required')]
    public ?array $labelsJson;


    /**
     * @var     string|null
     */
    public string $locale;


    /**
     * @var     Location|null
     */
    public ?Location $Location;


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


    /**
     * @var     LocationService
     */
    protected LocationService $LocationService;


    /**
     * @var     string|null
     */
    public ?string $locationTypeLabel;


    /**
     * @var     LocationType|null
     */
    public ?LocationType $LocationType;


    /**
     * @var     string|null
     */
    // #[Validate('nullable|required|numeric|exists:location_types,id')]
    public ?string $locationTypeId = null;


    /**
     * @var     Location|null
     */
    public ?Location $ParentLocation;


    /**
     * @var     string|null
     */
    #[Validate('nullable|required|numeric|exists:locations,id')]
    public ?string $parentLocationId = null;


    /**
     * @var     string|null
     */
    // #[Validate('required')]
    public ?string $phoneNumber = null;


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


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


    /**
     * @var     string|null
     */
    // #[Validate('required')]
    public ?string $street = null;


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


    /**
     * @var     string|null
     */
    // #[Validate('required')]
    public ?string $subType = null;


    /**
     * @var     string|null
     */
    // #[Validate('required')]
    public ?string $subTypeLabel = null;


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


    /**
     * @var     string|null
     */
    // #[Validate('required')]
    public ?string $zipCode = null;


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


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


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


    /**
     *
     * @version     1.0.0 / 2026-05-25
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function boot(LocationService $LocationService)
    {
        $this->LocationService = $LocationService;

        $this->locale       = app()->getLocale();
        $this->Printers     = PrinterRepository::getAll();
        $this->SubLocations = new Collection();

        $this->dependencies = config('globals.location-sub-type-dependencies.*');

    } // boot()


    /**
     *
     * @version     1.1.0 / 2026-06-08
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function editLocation()
    {
        $this->authorize('locations.update');

        $this->validate();

        try {
            $this->LocationService->update($this->Location->id, [
                'active'           => $this->active,
                'address_addition' => $this->addressAddition,
                'city'             => $this->city,
                'email'            => $this->email,
                'house_number'     => $this->houseNumber,
                'internal'         => $this->internal,
                'is_bookable'      => $this->isBookable,
                'labels'           => $this->labelsJson,
                'location_type_id' => $this->locationTypeId != 0 ? $this->locationTypeId : null,
                // 'master_id'        => $this->parentLocationId != 0 ? $this->parentLocationId : null ,
                'phone_number'     => $this->phoneNumber,
                'street'           => $this->street,
                'sub_type'         => $this->subType,
                'zip_code'         => $this->zipCode,
            ]);
            $lc   = app()->getLocale();
            $User = auth()->user();

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

            if ($this->LocationType?->identifier === 'AccessPoint' && $this->subType === 'Kiosk') {
                $this->Location->printers()->detach();

                if ($this->printerId !== null) {
                    $this->Location->printers()->attach($this->printerId, [
                        'uuid'       => (string) \Illuminate\Support\Str::uuid(),
                        'created_at' => now(),
                    ]);
                }
            }
            $this->dispatch('init-tippyjs');
            $this->dispatch('location-saved');

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

            $this->dangerBanner('Error when editing location. Check the logs for more information.');
        }

    } // editLocation()


    /**
     *
     * @version     1.0.0 / 2026-05-25
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    #[On('show-edit-location-modal')]
    public function initLocation(array $location)
    {
        $this->Location = Location::find($location['id']);

        $this->SubLocations   = $this->Location->SubLocations ?? new Collection();
        $this->ParentLocation = $this->Location->master;

        $this->active           = $this->Location->active;
        $this->addressAddition  = $this->Location->address_addition;
        $this->isBookable       = $this->Location->is_bookable;
        $this->city             = $this->Location->city;
        $this->email            = $this->Location->email;
        $this->houseNumber      = $this->Location->house_number;
        $this->internal         = $this->Location->internal;
        $this->labelsJson       = (array) $this->Location->labels;
        $this->locationTypeId   = $this->Location->location_type_id;
        $this->parentLocationId = $this->Location->master_id;
        $this->phoneNumber      = $this->Location->phone_number;
        $this->street           = $this->Location->street;
        $this->subType          = $this->Location->sub_type;
        $this->zipCode          = $this->Location->zip_code;

        $this->LocationType = LocationTypeRepository::getById($this->locationTypeId);

        $this->locationTypeLabel = __('globals::location-type-registry.labels.'.$this->LocationType->identifier);

        if ($this->LocationType->identifier === 'AccessPoint' && $this->subType === 'Kiosk') {
            $assignedPrinter = $this->Location->printers()->first();
            $this->printerId = $assignedPrinter !== null ? (string) $assignedPrinter->id : null;
        }

        if (empty($this->subType)) {
            $this->subTypes = $this->LocationType->sub_types;

            sort($this->subTypes);

        } else {
            $this->subTypeLabel = __('globals::location-type-registry.sub-types.'.$this->LocationType->identifier.'.'.$this->subType);
        }
        $this->dependencies = array_merge(
            config('globals.location-sub-type-dependencies.*'),
            config('globals.location-sub-type-dependencies.'.$this->LocationType->identifier)
        );
        $this->dispatch('init-tippyjs');

    } // initLocation()


    /**
     *
     * @version     1.0.0 / 2026-05-25
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    #[On('multi-language-json-created')]
    public function onMultiLanguageJsonCreated(?array $json, string $target)
    {
        if ($target == 'edit') {
            $this->labelsJson = $json;
        }

    } // onMultiLanguageJsonCreated()


    /**
     *
     * @version     1.0.0 / 2026-05-25
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function render()
    {
        return view('globals::livewire.core.location.modals.edit');

    } // render()


    /**
     *
     * @version     1.0.0 / 2026-05-25
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function resetModal()
    {
        $this->active          = true;
        $this->addressAddition = null;
        $this->city            = null;
        $this->email           = null;
        $this->houseNumber     = null;
        $this->internal        = false;
        $this->isBookable      = false;
        $this->labelsJson      = null;
        $this->Location        = null;
        $this->phoneNumber     = null;
        $this->street          = null;
        $this->subType         = null;
        $this->zipCode         = null;

        $this->locationTypeLabel = null;
        $this->printerId         = null;
        $this->subTypeLabel      = null;

        $this->dependencies = config('globals.location-sub-type-dependencies.*');

    } // resetModal()


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


} // class Edit extends Component {}
