<?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\Traits;


/**
 * Sort functionality for Livewire components that use a DataGrid
 *
 * Columns for sorting must be defined in the component's locale files under
 * "grid-locales.sort-fields".
 * Example:
 *
 *      return [
 *          ...
 *          'grid-locales' => [
 *              ...
 *              'sort-fields' => [
 *                  'email'        => 'E-Mail',
 *                  'labels->%lc%' => 'Label',
 *                  'name'         => 'Name',
 *              ],
 *          ],
 *      ];
 *
 * All fields listed there are automatically included in the selection, in the order in
 * which they are specified in the locale file.
 *
 * The notation "labels->%lc%" applies to JSON fields in which multilingual values are
 * stored with country codes as keys:
 *      {"de": "Allgemein", "en": "General"}
 *
 * The placeholder "%lc%" is replaced at runtime by the country code of the currently
 * selected language.
 *
 * @todo        Die Sortierung könnte optional in der Session abgelegt werden, um sie
 *              dauerhaft zu machen.
 *
 * @version     2.0.0 / 2026-04-09
 * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 */
trait WithSorting
{


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


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


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


    /**
     * @var     null|string
     */
    public null|string $sortColumn = null;


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


    /**
     * @var     string
     */
    public string $sortDirection = 'asc';


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


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


    /**
     *
     * @version     1.0.0 / 2026-04-09
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    protected function _getOrderBy(): array|null
    {
        $orderBy = null;

        if (!empty($this->sortColumn)) {
            $orderBy = [
                [
                    'column'    => str_replace('%lc%', app()->getLocale(), $this->sortColumn),
                    'direction' => $this->sortDirection,
                ],
            ];
        }
        return $orderBy;

    } // _getOrderBy()


    /**
     * Automatically adds the listener for "sortingChanged"
     *
     * Existing listeners in the class will not be overwritten.
     *
     * @version     1.0.0 / 2025-09-20
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function getListeners()
    {
        /*
        **  Retrieve and update the parent's listeners. */
        $parentListeners = property_exists($this, 'listeners') ? $this->listeners : [];

        $traitListener = [
            'sortingChanged' => 'updateSorting',
        ];
        return array_merge($parentListeners, $traitListener);

    } // getListeners()


    /**
     *
     * @return      void
     *
     * @version     1.0.0 / 2026-04-06
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function mountWithSorting(): void
    {
        $sortColumns = __($this->_gridLocaleFile.'.grid-locales.sort-fields');

        $this->sortColumns = is_array($sortColumns) ?  $sortColumns : [];

    } // mountWithSorting()


    /**
     * Default method called by SortSelect
     *
     * @param       string $column
     *
     * @param       string $direction
     *
     * @return      void
     *
     * @version     2.1.0 / 2026-04-09
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function updateSorting(null|string $column, null|string $direction): void
    {
        if ($column === '') {
            $this->sortColumn = null;

        } elseif (!array_key_exists($column, $this->sortColumns)) {
            return;
        }
        $this->sortColumn    = $column;
        $this->sortDirection = $direction;

    } // updateSorting()


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


} // trait WithSorting {}
