<?php

namespace App\DataTables;

use App\Models\Prenotazione;
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 App\Models\Evento;
use App\Models\Cucina;

class PrenotazioneDataTable extends DataTable
{
    public function __construct()
    {
        $this->dataTableVariable = 'dataTable_prenotazione';
 
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<Prenotazione> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function($entity){
              return view('prenotazione.menu', ['entity' => $entity]);
            })
            ->addColumn('evento_id_display', function($entity){
              return $entity->evento->nome??'';
            })
            ->addColumn('cucina_id_display', function($entity){
              return $entity->cucina->nome??'';
            })
            ->addColumn('stato_display', function($entity){
              return view('prenotazione._partials.stato-prenotazione', ['stato' => $entity->stato??'']);
            })
            ->setRowId('id');
    }

    /**
     * Get the query source of dataTable.
     *
     * @return QueryBuilder<Prenotazione>
     */
    public function query(Prenotazione $model): QueryBuilder
    {
        if(isset($this->evento_id)){
            return $model->newQuery()->where('evento_id', $this->evento_id);
        }
        return $model->newQuery();
    }

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        $titoloPrenotazioni = 'Prenotazione';
        if(isset($this->evento_id)){
            $titoloPrenotazioni = 'Prenota per ' . Evento::find($this->evento_id)->nome;
        }
        $buttons = [];
        if(Auth::user()->can('create-prenotazione')){
            array_push($buttons, Button::make('create')
                ->editor('editor')
                ->className('btn btn-sm btn-primary mb-4')
                ->formTitle('Crea nuovo prenotazione')
                ->formButtons([
                    Button::raw('Annulla')
                        ->className('btn btn-secondary ml-2')
                        ->actionClose(),
                    Button::raw('Salva')
                        ->className('btn btn-success ml-2')
                        ->actionHandler('create')
                ])
                ->text('<i class="fas fa-plus"></i> ' . $titoloPrenotazioni));
        };

        if(Auth::user()->can('edit-prenotazione') || Auth::user()->can('segna-presenza-prenotazione')){
            array_push($buttons, Button::raw('Appello')
                ->className('btn btn-sm btn-warning mb-4')
                ->action('appelloPrenotazioni')
            );
        }

        if(Auth::user()->can('report-prenotazione') || Auth::user()->can('segna-presenza-prenotazione')){
            array_push($buttons, Button::raw('Report')
                ->className('btn btn-sm btn-success mb-4')
                ->action('reportPrenotazioni()')
                ->text('<i class="fas fa-file-alt"></i> Report')
            );
        }


        //campi del form
$fields = [
    [
        Fields\Text::make('nome')->label('Nome'),
        Fields\Text::make('cognome')->label('Cognome'),
        Fields\Text::make('email')->label('Email'),
        Fields\Text::make('telefono')->label('Telefono'),
        Fields\Select2::make('evento_id')->label('Evento')
        ->options(Evento::where('is_attivo', true)->pluck('id', 'nome'))
        ->default(isset($this->evento_id) ? $this->evento_id : ''),
        Fields\Select2::make('cucina_id')->label('Cucina')->options(Cucina::all()->pluck('id', 'nome')),
        Fields\Select2::make('stato')->label('Stato')->options(Prenotazione::getStati()->pluck('value', 'label'))->default(Prenotazione::STATO_INVIATA) ,
        Fields\Text::make('note')->label('Note'),
        Fields\Text::make('codice')->label('Codice'),
        Fields\Text::make('stato_pagamento')->label('Stato pagamento'),
        Fields\Text::make('metodo_pagamento')->label('Metodo pagamento'),
    ]
];
        // if(isset($this->evento_id)){
        //     $fields[] = Fields\Select::make('evento_id')->label('Evento')->default($this->evento_id);
        // }

        return $this->builder()
                    ->setTableId($this->dataTableVariable)
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->responsive(true)
                    ->orderBy(2, 'asc')
                    ->selectStyleSingle()
                    ->language(asset('assets/Italian.json'))
                    ->dom('<"py-2"<"head-label text-center"><"dt-action-buttons"B>><"d-flex justify-content-between align-items-center row mb-2"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>t<"d-flex justify-content-between row"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>')
                    // ->dom(count($buttons) == 0?  'rtip' : 'Bfrtip')
                    ->buttons($buttons)
                    ->editor(
                        Editor::make()
                            ->fields($fields)
                    )
                    ->initComplete("function(settings, json){
                        initComplete_prenotazione();
                    }");
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::make('id')->title('ID')->width('10%')->visible(false)->responsivePriority(1)->width('10%'),
            Column::make('stato')->data('stato_display')->title('Stato')->searchable(true)->filter(true)->responsivePriority(1),
            Column::make('codice')->title('Codice')->responsivePriority(1),
            Column::make('cognome')->title('Cognome')->responsivePriority(2),
            Column::make('nome')->title('Nome'),
            Column::make('email')->title('Email'),
            Column::make('telefono')->title('Telefono'),
            Column::make('evento_id_display')->title('Evento'),
            Column::make('cucina_id_display')->title('Cucina'),
            Column::make('note')->title('Note'),
            Column::computed('action')
                  ->title('')
                  ->exportable(false)
                  ->printable(false)
                  ->width(60)
                  ->addClass('text-center')
                  ->responsivePriority(1),
        ];
    }

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