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


use BplanBase\Globals\Enums\UserAccessLevel;
use BplanBase\Globals\Http\Requests\StoreUserRequest;
use BplanBase\Globals\Models\Tenant;
use BplanBase\Globals\Services\UserService;
use BplanBase\Globals\Traits\InteractsWithBanner;
use Illuminate\Support\Str;
use Livewire\Component;


/**
 * Livewire Component
 *
 * @version     1.0.0 / 2026-05-25
 * @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     string
     */
    public string $accessLevel = '';


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


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


    /**
     * @var     string
     */
    public string $email = '';


    /**
     * @var     bool
     */
    public bool $internal = false;


    /**
     * @var     Tenant|null
     */
    public ?Tenant $_MasterTenant = null;


    /**
     * @var     string
     */
    public string $name = '';


    /**
     * @var     string
     */
    public string $password = '';


    /**
     * @var     string
     */
    public string $passwordConfirmation = '';


    /**
     * @var     bool
     */
    public bool $restricted = false;


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


    /**
     * For displaying the tenant in a disabled select
     *
     * @var     array|null
     */
    public ?array $tenantSelect = null;


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


    /**
     * @var     string
     */
    private static string $_logPrefix = 'Core/User/Modals/Create';


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


    /**
     *
     * @param       UserService $Service
     *
     * @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(UserService $Service): void
    {
        $this->_Service = $Service;

    } // boot()


    /**
     *
     * @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 createUser(): void
    {
        $this->validate();
        /*
        **  Passwort-Bestätigung manuell prüfen (camelCase Livewire-Properties). */
        if ($this->password !== '' && $this->password !== $this->passwordConfirmation) {
            $this->addError('passwordConfirmation', __('validation.confirmed', ['attribute' => __('globals::users.label.password')]));

            return;
        }

        try {
            $password = $this->password !== '' ? $this->password : Str::password(16);

            $User = $this->_Service->create([
                'access_level' => $this->accessLevel,
                'active'       => $this->active,
                'email'        => $this->email,
                'internal'     => $this->internal,
                'name'         => $this->name,
                'password'     => $password,
                'restricted'   => $this->restricted,
            ]);

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

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

            $this->dispatch('user-created');
            $this->dispatch('show-edit-user-modal', user: ['id' => $User->id], openTab: 'user-data');

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

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

    } // createUser()


    /**
     *
     * @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 mount(): void
    {
        $this->_MasterTenant = Tenant::current();

        $this->tenantSelect = [$this->_MasterTenant->id => $this->_MasterTenant->identifier];

        $Editor            = auth()->user();
        $editorAccessLevel = $Editor->access_level;
        $validAccessLevels = UserAccessLevel::getValidAccessLevels($editorAccessLevel);

        $this->accessLevels = array_combine($validAccessLevels, $validAccessLevels);

        if (count($validAccessLevels) === 1) {
            $this->accessLevel = current($validAccessLevels);
        }

    } // mount()


    /**
     *
     * @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.user.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(): void
    {
        $this->accessLevel          = count($this->accessLevels) === 1 ? current($this->accessLevels) : '';
        $this->active               = true;
        $this->email                = '';
        $this->internal             = false;
        $this->name                 = '';
        $this->password             = '';
        $this->passwordConfirmation = '';
        $this->restricted           = false;

        $this->resetValidation();

    } // resetModal()


    /**
     *
     * @return      array
     *
     * @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 rules(): array
    {
        $rules = StoreUserRequest::getRules();

        unset($rules['current_team_id']);
        unset($rules['email_verified_at']);
        unset($rules['profile_photo_path']);

        /*
        **  Passwort ist optional — wird automatisch generiert, wenn nicht angegeben. */
        $rules['password'] = ['nullable', 'string', 'max:255'];
        /*
        **  camelCase → snake_case Remapping für Livewire-Properties. */
        $rules['accessLevel'] = $rules['access_level'];
        unset($rules['access_level']);

        return $rules;

    } // rules()


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


} // class Create extends Component {}
