<?php

namespace App\DataTables;

use App\Models\VariantePiatto;
use App\Models\Piatto;
use App\Models\Cucina;
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;

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

    public ?int $attivita_id = null;

    public ?int $cucina_id = null;

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

    protected function isDashboard(): bool
    {
        return $this->dashboard || request()->routeIs('variante-piatto.datatable');
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<VariantePiatto> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function($entity){
                return view('variante_piatto.menu', ['entity' => $entity, 'dashboard' => $this->isDashboard()]);
            })
            ->addColumn('prezzo_display', function($entity){
                return '€ ' . number_format($entity->prezzo, 2, ',', '.');
            })
            ->setRowId('id');
    }

    /**
     * Get the query source of dataTable.
     *
     * @return QueryBuilder<VariantePiatto>
     */
    public function query(VariantePiatto $model): QueryBuilder
    {
        $query = $model->newQuery()->where('attivita_id', $this->attivita_id);
        if (isset($this->cucina_id)) {
            $query->where('cucina_id', $this->cucina_id);
        }
        // if (isset($this->cucina_id)) {
        //     $query->whereHas('piatto', function ($q) {
        //         $q->where('cucina_id', $this->cucina_id);
        //     });
        // }

        return $query;
    }

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        $buttons = [];
        if (Auth::user()->can('create-variante-piatto')) {
            array_push($buttons, Button::make('create')
                ->editor('editor')
                ->formTitle('Crea nuova variante piatto')
                ->className('btn btn-sm btn-primary mb-4')
                ->text('<i class="fas fa-plus"></i> Nuova variante'));
        }
        $builder = $this->builder()
                    ->setTableId($this->dataTableVariable)
                    ->columns($this->getColumns())
                    ->orderBy(1)
                    ->responsive()
                    ->editor(Editor::make()
                        ->ajax(route('variante-piatto.store'))
                        ->fields([
                            Fields\Hidden::make('attivita_id')->label('Attività')->default($this->attivita_id),
                            Fields\Text::make('prezzo')->label('Prezzo'),
                            Fields\Text::make('label')->label('Nome'),
                            Fields\Select2::make('piatto_id')->label('Piatto')->options(Piatto::where('attivita_id', $this->attivita_id)->pluck('id', 'nome')),
                            Fields\Select2::make('cucina_id')->label('Cucina')->options(Cucina::where('attivita_id', $this->attivita_id)->pluck('id', 'nome')),
                        ])
                    )
                    ->language(asset('assets/Italian.json'))
                    ->dom(count($buttons) == 0 ? 'rtip' : 'Bfrtip')
                    ->selectStyleSingle()
                    ->buttons($buttons);

        if ($this->isDashboard()) {
            $builder->minifiedAjax(route('variante-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
    {
        return [
            Column::make('id')->visible(false),
            Column::make('label')->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),
        ];
    }

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