<?php
/**
 * Livewire Trait
 *
 * @version     1.0.0
 * @package     bplan-base/globals
 * @subpackage  Traits
 * @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;


use BplanBase\Globals\Traits\WithSorting;


/**
 * Common functionality for Livewire components that use a DataGrid
 *
 * This trait handles recurring tasks after each render cycle that would otherwise have
 * to be called manually in each index component.
 *
 * @version     1.3.0 / 2026-04-14
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 */
trait WithDataGrid
{


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


    use WithSorting;


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


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


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


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


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


    /**
     * Indicates whether the current data is filtered.
     *
     * Copy this method into your component and customize it to suit your needs if
     * additional filters are used in the grid alongside the standard search.
     *
     * @return      bool
     *
     * @version     1.0.0 / 2026-04-06
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    private function _hasActiveFilters(): bool
    {
        return !empty($this->search);

    } // _hasActiveFilters()


    /**
     * Prepares an extended Query
     *
     * Implement this method in your component if the default search does not meet
     * your requirements.
     *
     * @return 	    Builder|null
     *
     * @version     1.1.0 / 2026-04-14
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    protected function _getQuery()
    {
        $ExtendQuery = null;

        $this->search = trim($this->search);

        if (!empty($this->search)) {
            /*
            **  Create a QueryBuilder with filter parameters. */
            $ExtendQuery = $this->_modelClass::query();

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

            foreach ($this->_searchFields as $field) {
                $fieldType = $this->_formatCasts[$field] ?? null;

                switch ($fieldType) {
                    case 'json':
                        if ($c === 0) {
                            $ExtendQuery->whereRaw('LOWER(CAST('.$field.' AS CHAR)) LIKE ?', ['%'.strtolower($this->search).'%']);
                        } else {
                            $ExtendQuery->orWhereRaw('LOWER(CAST('.$field.' AS CHAR)) LIKE ?', ['%'.strtolower($this->search).'%']);
                        }
                        break;

                    case 'localejson':
                        if ($c === 0) {
                            $ExtendQuery->whereRaw('LOWER(JSON_UNQUOTE(JSON_EXTRACT('.$field.', \'$.'.$locale.'\'))) LIKE ?', ['%'.strtolower($this->search).'%']);
                        } else {
                            $ExtendQuery->orWhereRaw('LOWER(JSON_UNQUOTE(JSON_EXTRACT('.$field.', \'$.'.$locale.'\'))) LIKE ?', ['%'.strtolower($this->search).'%']);
                        }
                        break;

                    default:
                        if ($c === 0) {
                            $ExtendQuery->whereLike($field, '%'.$this->search.'%');
                        } else {
                            $ExtendQuery->orWhereLike($field, '%'.$this->search.'%');
                        }
                }
                $c++;
            }
        }
        return $ExtendQuery;

    } // _getQuery()


    /**
     *
     * @return      void
     *
     * @version     1.1.0 / 2026-04-07
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function init(): void
    {
        $this->skipRender();

    } // init()


    /**
     *
     * @return      void
     *
     * @version     1.0.0 / 2026-04-06
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function mountWithDataGrid(): void
    {
        \Registry::put('env.page-title', __($this->_gridLocaleFile.'.page.title'));

    } // mountWithDataGrid()


    /**
     * Called automatically by Livewire after each render cycle
     *
     * Reinitializes TippyJS, as new DOM elements with tooltip attributes may be present
     * after a re-render.
     *
     * @return      void
     *
     * @version     1.0.0 / 2026-04-06
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function rendered(): void
    {
        $this->dispatch('init-tippyjs');

    } // rendered()


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


} // trait WithDataGrid {}
