<?php

namespace App\DataTables;

use App\Models\Piatto;
use App\Models\Cucina;
use App\Models\Menu;
use App\Models\Attivita;
use App\Models\Allergene;
use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Yajra\DataTables\EloquentDataTable;
use Yajra\DataTables\Html\Builder as HtmlBuilder;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class PiattoDataTable extends DataTable
{
    public bool $dashboard = false;

    public ?int $attivita_id = null;

    public ?int $cucina_id = null;

    public function __construct()
    {
        $this->dataTableVariable = 'dataTable_piatto';
        $this->dashboard = request()->boolean('dashboard')
            || request()->routeIs('piatto.datatable');
    }

    protected function isDashboard(): bool
    {
        return $this->dashboard || request()->routeIs('piatto.datatable');
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<Piatto> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function ($entity) {
                return view('piatto.menu', ['entity' => $entity]);
            })
            ->addColumn('is_attivo_display', function ($entity) {
                return view('_partials.available', ['available' => $entity->is_attivo]);
            })
            ->addColumn('allergeni', function ($entity) {
                // Serve all'Editor per precompilare `Fields\Tags` con array di ID.
                return $entity->elencoAllergeni?->pluck('id')->values()->all() ?? [];
            })
            ->addColumn('allergeni_display', function ($entity) {
                return $entity->elencoAllergeni->pluck('nome')->implode(', ');
            })
            ->addColumn('bacheca_id_display', function ($entity) {
                return view('_partials.available', ['available' => $entity->bacheca_id]);
            })
            ->addColumn('in_evidenza_display', function ($entity) {
                return view('_partials.available', ['available' => $entity->in_evidenza]);
            })
            ->addColumn('cucina_id_display', function ($entity) {
                return $entity->cucina ? $entity->cucina->nome : '';
            })
            ->addColumn('prezzo_display', function ($entity) {
                return '€ ' . number_format($entity->prezzo, 2, ',', '.');
            })
            ->setRowId('id');
    }

    /**
     * Get the query source of dataTable.
     *
     * @return QueryBuilder<Piatto>
     */
    public function query(Piatto $model): QueryBuilder
    {
        if($this->attivita_id !== null){
            $model = $model->newQuery()->where('attivita_id', $this->attivita_id);
            
            if (isset($this->cucina_id)) {
                return $model->where('cucina_id', $this->cucina_id)
                    ->with('cucina', 'elencoAllergeni');
            }

            return $model->with('cucina', 'elencoAllergeni');

        }else{
            return $model->newQuery()->whereRaw('1 = 0');
        }
    }

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        $buttons = [];
        if (Auth::user()->can('create-piatto')) {
            array_push($buttons, Button::make('create')
                ->editor('editor')
                ->formTitle('Crea nuovo piatto')
                ->className('btn btn-sm btn-primary mb-4')
                ->text('<i class="fas fa-plus"></i> Nuovo piatto'));
        }

        if (Auth::user()->can('view-cucina') && ! $this->isDashboard()) {

            array_push($buttons, 
            Button::raw()
            ->formTitle('Visualizza tutte le cucine')
            ->className('btn btn-sm btn-primary ml-2 mb-4')
            ->action('GoToCucine()')
            ->text('<i class="bx bx-chef-hat"></i> Tutte le cucine'));
        }


        if (isset($this->cucina_id) && ! $this->isDashboard()) {
            array_push($buttons, Button::raw()
            ->formTitle('Visualizza tutti i piatti')
            ->className('btn btn-sm btn-primary ml-2 mb-4')
            ->action('GoToAllPiatti()')
            ->text('<i class="bx bx-dish"></i> Tutti i piatti'));
        }

        $builder = $this->builder()
            ->setTableId($this->dataTableVariable)
            ->columns($this->getColumns())
            // ->minifiedAjax()
            ->orderBy(1)
            ->responsive()
            // ->searchable(true)
            ->selectStyleSingle()
            ->language(asset('assets/Italian.json'))
            ->dom(count($buttons) == 0 ? 'rtip' : 'Bfrtip')
            ->buttons($buttons)
            ->searchPanes(true)
            // ->ajax(route('piatto.store'))
            ->editor(
                Editor::make()
                    ->ajax(route('piatto.store'))
                    ->fields([
                        Fields\Hidden::make('attivita_id')->label('Attività')->default($this->attivita_id),
                        Fields\Text::make('nome')->label('Nome'),
                        Fields\Text::make('descrizione')->label('Descrizione'),
                        Fields\Select2::make('cucina_id')->label('cucina')
                        ->options(Cucina::where('is_attiva', true)->where('attivita_id', $this->attivita_id)->pluck('id', 'nome'))
                        ->default(isset($this->cucina_id) ? $this->cucina_id : ''),
                        Fields\Text::make('prezzo')->label('Prezzo (€)'),
                        // Fields\Image::make('immagine')->label('Immagine'),
                        Fields\Boolean::make('is_attivo')->label('Disponibile')->default(true),
                        Fields\Select2::make('allergeni')->label('Allergeni')->multiple(true)
                            ->options(Allergene::where('disponibile', true)->pluck('id', 'nome'))
                            ->placeholder('Seleziona allergeni'),
                        Fields\Boolean::make('bacheca_id')->label('Bacheca')->default(false),
                        Fields\Boolean::make('in_evidenza')->label('In evidenza')->default(false),
                    ])
            )
            ->initComplete("function(settings, json){
                        initComplete_piatto();
                    }");

                    if ($this->isDashboard()) {
                        $builder->minifiedAjax(route('piatto.index'), null, array_filter([
                            'dashboard' => 1,
                            'cucina_id' => $this->cucina_id,
                        ]));
                    } else {
                        $builder->minifiedAjax();
                    }

                    return $builder;
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        $dashboard_columns = [
            Column::make('id')->visible(false),
            Column::make('is_attivo_display')->title('')->addClass('text-center')->responsivePriority(1),
            // Column::make('cucina_id')->data('cucina_id_display')->title('cucina')->addClass('text-center'),
            Column::make('nome')->title('Nome')->searchable()->responsivePriority(1),
            Column::make('prezzo')->data('prezzo_display')->title('Prezzo')->addClass('text-center'),
            Column::computed('action')->title('')->width('10%')->addClass('text-center')->responsivePriority(1),
        ];

        $columns = [
            Column::make('id')->title('ID')->width('10%')->visible(false),
            Column::make('is_attivo')->data('is_attivo_display')->title('Disponibile')->width('10%')->responsivePriority(1),
            // ID grezzi per Editor Select2 (stesso schema di disponibile vs disponibile_display)
            Column::make('cucina_id')->data('cucina_id_display')->title('cucina')->addClass('text-center'),
        ];


        $columns = array_merge($columns, [

            Column::make('nome')->title('Nome')->searchable()->responsivePriority(1),
            Column::make('prezzo')->data('prezzo_display')->title('Prezzo')->addClass('text-center'),
            // Column::computed('cucina_id')->data('cucina_id_display')->title('Cucina')->addClass('text-center')->responsivePriority(2), // icona in tabella
            Column::make('allergeni')->title('Allergeni')->visible(false), // valore grezzo per l'editor (array ID)
            Column::make('allergeni')->data('allergeni_display')->title('Allergeni')->visible(true),
            // Column::make('bacheca_id')->data('bacheca_id_display')->title('Bacheca')->addClass('text-center'), // icona in tabella
            // Column::make('in_evidenza')->data('in_evidenza_display')->title('In evidenza')->addClass('text-center'), // icona in tabella
            Column::computed('action')->title('')->width('10%')->addClass('text-center')->responsivePriority(1),
        ]);
        // dd($columns);

        if ($this->isDashboard()) {
            return $dashboard_columns;
        }

        return $columns;
    }

    /**
     * Get the filename for export.
     */
    protected function filename(): string
    {
        return 'Piatto_' . date('YmdHis');
    }
}
