<?php

namespace App\DataTables;

use App\Models\Cucina;
use App\Models\Dispositivo;
use App\Models\Attivita;
use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Illuminate\Support\Facades\Auth;
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 App\DataTables\CucinaDataTableEditor;
use Illuminate\Support\Facades\Session;

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

    public ?int $attivita_id = null;

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

    protected function isDashboard(): bool
    {
        return $this->dashboard || request()->routeIs('cucina.dashboard');
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<Cucina> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function($entity){
                return view('cucina.menu', ['entity' => $entity, 'dashboard' => $this->isDashboard()]);
            })
            ->addColumn('is_attiva_display', function($entity){
              return view('_partials.available', ['available' => $entity->is_attiva]);
            })
            ->addColumn('piatti_count', function($entity){
              return $entity->piatti->count();
            })
            ->addColumn('attivita_id_display', function($entity){
              return $entity->attivita->nome;
            })
            ->addColumn('stampante_display', function($entity){
              return $entity->stampante ? $entity->stampante->nome : '';
            })
            // ->addColumn('cucina_id_display', function($entity){
            //   return $entity->cucina->nome;
            // })
            ->addColumn('stampante_id_display', function($entity){
              return $entity->stampante ? $entity->stampante->nome : '';
            })
            ->addColumn('badge_colore', function($entity){
              // dd($entity->info['colore']);
              $colore = $entity->info['colore'] ?? '#808080';
              return '<span class="badge" style="background-color: '.$colore.';">'.$entity->nome.'</span>';
            })
            ->rawColumns(['badge_colore'])
            ->setRowId('id');
    }

    /**
     * Get the query source of dataTable.
     *
     * @return QueryBuilder<Cucina>
     */
    public function query(Cucina $model): QueryBuilder
    {
        if($this->attivita_id){
            return $model->newQuery()->where('attivita_id', $this->attivita_id)->orderBy('nome', 'asc');
        }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-cucina')){
            array_push($buttons, Button::make('create')
            ->editor('editor')
            ->formTitle('Crea nuovo cucina')
            ->className('btn btn-sm btn-primary mb-4')
            ->text('<i class="fas fa-plus"></i> Nuova cucina'));
        }

        $builder = $this->builder()
                    ->setTableId($this->dataTableVariable)
                    ->columns($this->getColumns())
                    ->initComplete("function(settings, json){
                        initComplete_cucina();
                    }")
                    ->language(asset('assets/Italian.json'))
                    ->dom(count($buttons)==0?'rtip':'Bfrtip')
                    ->responsive()
                    ->orderBy(1)
                    ->selectStyleSingle()
                    ->buttons($buttons)
                    ->editor(
                        Editor::make()
                        ->ajax(route('cucina.store'))
                        ->fields([
                          Fields\Hidden::make('attivita_id')->label('Attività')->default($this->attivita_id),
                          Fields\Boolean::make('is_attiva')->label('Attiva')->default(true),  
                          Fields\Text::make('nome')->label('Nome'),
                          Fields\Text::make('descrizione')->label('Descrizione'),
                          Fields\Select2::make('stampante_id')->label('Stampante')->options(Dispositivo::where('tipo', Dispositivo::STAMPANTE)->pluck('id', 'nome')),
                          Fields\Text::make('colore')->label('Colore')->set('attr', ['type' => 'color']),
                          Fields\Boolean::make('coperto_come_piatto')->label('Ogni piatto ordinato corrisponde ad un coperto'),  
                            // Fields\Image::make('immagine')->label('Immagine'),
                            // Fields\Select2::make('cucina_id')->label('Cucina')->options(Cucina::where('is_attiva', true)->pluck('id', 'nome')),
                        ])
                    )
                    ->buttons($buttons)
                    ->orderBy(1);

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

                    return $builder;
                    
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {

      $dashboard_columns = [
        Column::make('id')->visible(false),
        Column::make('is_attiva_display')->title('')->addClass('text-center')->responsivePriority(1),
        Column::make('badge_colore')->title('Cucina')->addClass('text-left')->responsivePriority(1),
        Column::computed('piatti_count')->title('Piatti')->addClass('text-center'),
        Column::make('coperto_come_piatto')->visible(false),
        Column::computed('action')
        ->title('')
        ->exportable(false)
        ->printable(false)
        ->width(60)
        ->addClass('text-center')
        ->responsivePriority(1),
      ];

      $columns = [
            Column::make('id')->visible(false),
            Column::make('is_attiva_display')->title('Disponibile')->addClass('text-center')->responsivePriority(1),
            // Column::make('nome'),
            Column::make('badge_colore')->title('Nome')->addClass('text-left')->responsivePriority(1),
            Column::make('descrizione'),
            Column::computed('piatti_count')->title('Piatti')->addClass('text-center'),
            // Column::make('immagine'),
            Column::make('attivita_id')->data('attivita_id_display')->title('Attività')->addClass('text-center')->visible(false),
            Column::make('stampante_id')->data('stampante_display')->title('Stampante')->addClass('text-center'),
            // Column::make('cucina_id')->data('cucina_id_display')->title('Cucina')->addClass('text-center'),
            Column::make('coperto_come_piatto')->visible(false),
            Column::make('action')
            ->title('')
            ->exportable(false)
            ->printable(false)
            ->width(60)
            ->addClass('text-center')
            ->responsivePriority(1),
        ];
        return $this->isDashboard() ? $dashboard_columns : $columns;
    }

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