<?php
/**
 * Livewire Component
 *
 * @version     3.0.$Revision:$
 * @version     SVN: $Id:$
 * @version     STUB: 4.2.0
 * @generated   2026-04-14 00:28:11
 * @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\Country;


use BplanBase\Globals\DataGrid\DataGrid;
use BplanBase\Globals\Models\Country;
use BplanBase\Globals\Models\Tenant;
use BplanBase\Globals\Repositories\IndexCollectionRepository;
use BplanBase\Globals\Traits\WithDataGrid;
use Illuminate\Pagination\LengthAwarePaginator;
use Livewire\Component;
use Livewire\WithPagination;


/**
 * Livewire Component
 *
 * @version     4.0.0 / 2026-06-08
 * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 */
class Index extends Component
{


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


    use WithDataGrid;
    use WithPagination;


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


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


    /**
     * @var     array
     */
    protected array $_formatCasts = [
        'capital_names'     => 'localejson',
        'locales'           => 'json',
        'long_names'        => 'localejson',
        'nationality_names' => 'localejson',
        'short_names'       => 'localejson',
        'tenant_active'     => 'boolean',
    ];


    /**
     * Specifies the columns to use and their order
     *
     * @var     array
     */
    protected array $_gridColumns = [
        'short_names',
        'telephone_country_code',
    ];


    /**
     * @var     string
     */
    protected string $_gridLocaleFile = 'globals::countries';


    /**
     * @var     string
     */
    protected string $_modelClass = Country::class;


    /**
     * @var     array
     */
    protected array $_searchFields = [
        'short_names',
        'telephone_country_code',
    ];


    /**
     * @var     array
     */
    protected $listeners = [
        'country-created' => 'render',
        'country-edited'  => 'render',
        'country-deleted' => 'render',
    ];


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


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


    /**
     *
     * @return      LengthAwarePaginator<Country>
     *
     * @version     1.2.0 / 2026-06-08
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    private function _getData(): LengthAwarePaginator
    {
        $tenantId = Tenant::current()->id;

        $ExtendQuery = Country::where('active', true)
            ->selectRaw(
                'countries.*, EXISTS(
                    SELECT 1 FROM visit_country_tenant
                    WHERE visit_country_tenant.country_id = countries.id
                    AND visit_country_tenant.tenant_id = ?
                ) AS tenant_active',
                [$tenantId]
            );

        return IndexCollectionRepository::getCountries(
            ExtendQuery: $ExtendQuery,
            orderBy: $this->_getOrderBy(),
            paginate: ['pageName' => 'countries-page'],
            withInactive: false
        );
    } // _getData()


    /**
     *
     * @return      DataGrid
     *
     * @version     1.1.0 / 2026-06-08
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    private function _getGrid(): DataGrid
    {
        $gridData = $this->_getData();

        $locale = app()->getLocale();

        return (new DataGrid('country'))
            ->setActiveFilters($this->_hasActiveFilters())
            ->setColumnCallback(function ($Item, $property, $value) use ($locale) {
                switch ($property) {
                    case 'short_names':
                        $value = $Item->short_names->{$locale};
                        break;
                }
                return $value;
            })
            ->setColumns($this->_gridColumns)
            ->setToggleCallback('onToggle', 'tenant_active')
            ->setData($gridData)
            ->setLocaleFile($this->_gridLocaleFile)
            ->setSorting($this->sortColumns, $this->sortColumn, $this->sortDirection)
            ->useCaptions(true)
            ->useDefaultSearch(true)
            ->useDefaultCreateButton(false);

    } // _getGrid()


    /**
     *
     * @return      void
     *
     * @version     1.0.0 / 2026-06-08
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function mount(): void
    {
        $this->authorize('visit-countries.assign');

    } // mount()


    /**
     *
     * @param       string|integer $id
     *
     * @throws      \Throwable
     *
     * @return      void
     *
     * @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 onToggle(string|int $id): void
    {
        $this->authorize('visit-countries.assign');

        try {
            $tenantId = Tenant::current()->id;

            $exists = \Illuminate\Support\Facades\DB::table('visit_country_tenant')
                ->where('country_id', $id)
                ->where('tenant_id', $tenantId)
                ->exists();

            if ($exists === true) {
                \Illuminate\Support\Facades\DB::table('visit_country_tenant')
                    ->where('country_id', $id)
                    ->where('tenant_id', $tenantId)
                    ->delete();
            } else {
                \Illuminate\Support\Facades\DB::table('visit_country_tenant')->insert([
                    'country_id'  => $id,
                    'tenant_id'   => $tenantId,
                    'created_at'  => now(),
                    'updated_at'  => now(),
                ]);
            }

        } catch (\Throwable $th) {
            throw $th;
        }
    } // onToggle()


    /**
     *
     * @version     1.0.0 / 2025-04-05
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function render()
    {
        return view('globals::livewire.country.index', [
            'grid' => $this->_getGrid(),
        ]);
    } // render()


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


} // class Index extends Component {}
