<?php
/**
 *
 * @version     1.0.$Revision:$
 * @version     SVN: $Id:$
 * @package     bplan-base/globals
 * @subpackage  LivewireComponents
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 * @copyright   Copyright (C) 2025, 2026 Wassilios Meletiadis <https://www.bplan-solutions.de/>
 * /Δ\
 */

namespace BplanBase\Globals\Livewire\Core\Tenant;


use BplanBase\Globals\Livewire\Core\Global\BaseForm;
use BplanBase\Globals\Models\Tenant;
use BplanBase\Globals\Repositories\ExternalSystemRepository;
use BplanBase\Globals\Repositories\LinkedModuleRepository;
use BplanBase\Globals\Repositories\LinkedSystemRepository;
use BplanBase\Globals\Repositories\Core\TenantLocaleRepository;
use BplanBase\Globals\Repositories\ModuleRepository;
use BplanBase\Globals\Repositories\ModuleTenantRepository;
use BplanBase\Globals\Repositories\TenantRepository;
use BplanBase\Globals\Repositories\TenantExternalSystemRepository;
use BplanBase\Globals\Services\TenantLocaleService;
use Livewire\Component;
use Exception;


/**
 *
 * @version     1.1.0 / 2025-07-16
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 */
class Form extends BaseForm
{


/* +++ TRAITS +++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ CLASS CONSTANTS +++ ++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ OBJECT MEMBERS +++ +++++++++++++++++++++++++++++++++++++++++++++++++++ */


    /**
     * Die Liste der verfügbaren Locales
     *
     * Dabei handelt es sich entweder um die Locales des Master-Tenants oder um die System-Locales.
     *
     * @var     array
     */
    public $availableLocales;


    /**
     *
     * @var    array
     */
    public $tenantModules;


    /**
     *
     * @var    array
     */
    public $linkedSystems;


    /**
     * Die Liste der bereits gewählten Locales
     *
     * @var    array
     */
    public $locales = [];


    /**
     * @var    array
     */
    public $main = [
        'active'     => true,
        'identifier' => '',
    ];


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


    /**
     *
     * @var    array
     */
    public $modules;


    /**
     * Die Liste der noch nicht gewählten Locales
     *
     * @var     array
     */
    public $newLocales = [];


    /**
     * @var    array
     */
    public $onRedirectIdName = [
        'ABORT' => null,
        'CREATE' => 'id',
        'DELETE' => null,
        'UPDATE' => null,
    ];


    /**
     * @var    array
     */
    public $onRedirectRoutes = [
        'ABORT' => 'core-tenants.index',
        'CREATE' => 'core-tenant-record',
        'DELETE' => 'core-tenants.index',
        'UPDATE' => 'core-tenants.index',
    ];


    /**
     *
     * @var    array
     */
    public $supportedSystems;


    /**
     * @var    array
     */
    public $tabs = [
        'base',
        'locales',
        'tenant-modules',
        'tenant-external-systems',
    ];


    /**
     * Die Liste der Locales des Tenants
     *
     * @var     Collection
     */
    public $TenantLocales;


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


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


    /**
     *
     * @version     1.2.0 / 2026-02-17
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    protected function _initLocales(): void
    {
        if ($this->exists === true) {
            if ($this->MainObject->master_id !== null) {
                /*
                **  Wenn es einen Master-Tenant gibt, dann werden dessen System-Locales zur Auswahl
                **  gestellt. */
                $this->availableLocales = TenantLocaleRepository::determineTenantLocales($this->MainObject->master_id, withInactive: true);
            }
        } else {
            /*
            **  Bei einer Neuanlage wird der neue Tenant als Sub vom aktuellen Tenant angelegt. Aus
            **  dem Grund sind die beim Master verfügbaren Locales diejenigen, die hier zur Auswahl
            **  stehen. */
            $tenantId = Tenant::current()->id;

            $this->availableLocales = TenantLocaleRepository::determineTenantLocales($tenantId, withInactive: true);
        }
        if ($this->availableLocales === null) {
            $this->availableLocales = config('globals.system-locales');
        }
        sort($this->availableLocales);

        $this->TenantLocales = TenantLocaleRepository::getTenantLocales($this->mainID, withInactive: true);
// dump($this->TenantLocales, $this->availableLocales);/
        /*
        **  Liste der verfügbaren Locales abarbeiten und die Arrays für das Formular aufbauen. */
        foreach ($this->availableLocales as $locale) {
            $TenantLocale = $this->TenantLocales->where('locale', '=', $locale)
                ->first();

            if ($TenantLocale !== null) {
                $this->locales[$locale] = (bool) $TenantLocale->active;
            } else {
                $this->newLocales[$locale] = false;
            }
        }
    } // _initLocales()


    /**
     *
     * @version     1.2.0 / 2026-02-17
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    protected function _initMasterTenant(): void
    {
        if ($this->exists === true) {
            if ($this->MainObject->master_id !== null) {
                $Tenant = TenantRepository::getById($this->MainObject->master_id);

                $this->masterTenant = [$this->MainObject->master_id => $Tenant->identifier];
            }
        } else {
            $this->main['master_id'] = Tenant::current()->id;

            $Tenant = TenantRepository::getById($this->main['master_id']);

            $this->masterTenant = [$this->main['master_id'] => $Tenant->identifier];
        }
    } // _initMasterTenant()


    /**
     *
     * @version     1.0.0 / 2025-05-25
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    protected function _initModules(): void
    {
        $this->modules = ModuleRepository::getAll()
            ->pluck('label', 'id')
            ->toArray();

    } // _initModules()


    /**
     *
     * @version     1.0.0 / 2025-05-25
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    protected function _initSystems(): void
    {
        $this->supportedSystems = ExternalSystemRepository::getAll()
            ->pluck('label', 'id')
            ->toArray();

    } // _initSystems()


    /**
     *
     * @version     1.0.0 / 2025-05-25
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    protected function _initTenantModules(): void
    {
        $this->tenantModules = ModuleTenantRepository::getAll();

    } // _initTenantModules()


    /**
     *
     * @version     1.0.0 / 2025-05-25
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    protected function _initTenantSystems(): void
    {
        $this->linkedSystems = TenantExternalSystemRepository::getAll();

    } // _initTenantSystems()


    /**
     *
     * @param       bool $saveWasCreate
     *
     * @version     1.0.0 / 2025-05-25
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    protected function _onAfterSave(bool $saveWasCreate): void
    {
        parent::_onAfterSave($saveWasCreate);

        $TenantLocaleService = new TenantLocaleService();
        /*
        **  Bestehende Locales des aktuellen Tenants aktualisieren. */
        foreach ($this->locales as $locale => $active) {
            $TenantLocale = $this->TenantLocales
                ->where('locale', '=', $locale)
                ->first();

            $TenantLocaleService->updateActiveStatus($TenantLocale, $active);
        }
        /*
        **  Neue Locales zum aktuellen Tenant hinzufügen. */
        foreach ($this->newLocales as $locale => $active) {
            if ($active === false) {
                continue;
            }
            $TenantLocaleService->create([
                'active' => 1,
                'locale' => $locale,
                'tenant_id' => $this->mainID,
            ]);
        }
        $this->_initLocales();

        if ($saveWasCreate === true) {
            $this->tabs['tenant-modules'] = [
                'active' => true,
                'identifier' => 'tenant-modules',
                'label' => __('globals::core-'.$this->localeFile.'.tab-name.tenant-modules'),
                'view' => 'tenant-modules',
            ];
            $this->tabs['tenant-modules'] = [
                'active' => true,
                'identifier' => 'tenant-modules',
                'label' => __('globals::core-'.$this->localeFile.'.tab-name.tenant-modules'),
                'view' => 'tenant-modules',
            ];
        }
    } // _onAfterSave()


    /**
     *
     * @version     1.0.0 / 2025-05-25
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function mount(): void
    {
        parent::mount();

        $this->_initLocales();
        $this->_initModules();
        $this->_initTenantModules();
        $this->_initSystems();
        $this->_initTenantSystems();
        $this->_initMasterTenant();

        if ($this->exists === false) {
            $this->multiSaveButton = false;
            $this->redirectOnStandardSave = true;

            $this->tabs['tenant-modules']['active'] = false;
            $this->tabs['tenant-external-systems']['active'] = false;
        }
    } // mount()


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


} // class Form extends BaseForm {}
