<?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\LocationRepository;
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 Create 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     bool
     */
    // #[Validate('required')]
    public bool $internal = false;


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


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


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


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


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


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


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


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


    /**
     * @var     string|null
     */
    #[Validate('nullable|numeric|exists:locations,id')]
    public ?string $master_location_id = 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     string|null
     */
    // #[Validate('required')]
    public ?string $subType = 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/Create';


/* +++ 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->Locations     = LocationRepository::getAll(Query: Location::whereDoesntHave(
            'locationType',
            fn($Query) => $Query->where('identifier', '=', 'AccessPoint')

        ), withInternal: true);

        $this->LocationTypes = LocationTypeRepository::getAll();
        $this->Printers      = PrinterRepository::getAll();

        $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 createLocation()
    {
        $this->authorize('locations.create');

        $this->validate();

        try {
            $Location = $this->LocationService->create([
                '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->master_location_id != 0 ? $this->master_location_id : null,
                'phone_number'     => $this->phoneNumber,
                'street'           => $this->street,
                'sub_type'         => $this->subType,
                'zip_code'         => $this->zipCode,
            ]);

            if ($this->LocationType?->identifier === 'AccessPoint' && $this->subType === 'Kiosk' && $this->printerId !== null) {
                $Location->printers()->attach($this->printerId, [
                    'uuid'       => (string) \Illuminate\Support\Str::uuid(),
                    'created_at' => now(),
                ]);
            }
            $lc   = app()->getLocale();
            $User = auth()->user();

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

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

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

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

    } // createLocation()


    /**
     *
     * @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 == 'create') {
            $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.create');

    } // 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->phoneNumber     = null;
        $this->printerId       = null;
        $this->street          = null;
        $this->subType         = null;
        $this->zipCode         = null;

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

    } // resetModal()


    /**
     *
     * @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 updated($name, $value)
    {
        if ($name === 'locationTypeId') {
            if ($value !== '') {
                $this->LocationType = $this->LocationTypes->where('id', '=', $value)->first();

                $this->subType  = null;
                $this->subTypes = $this->LocationType->sub_types;

                sort($this->subTypes);
            }
            $this->dependencies = array_merge(
                config('globals.location-sub-type-dependencies.*'),
                config('globals.location-sub-type-dependencies.'.$this->LocationType->identifier)
            );
        } elseif ($name === 'subType') {
            //
        }

    } // updated()


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


} // class Create extends Component {}
