<?php

namespace App\DataTables;

use App\Models\EventoForm;
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 EventoFormDataTable extends DataTable
{
    public function __construct()
    {
        $this->dataTableVariable = 'dataTable_evento_form';
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<EventoForm> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function($entity){
                return view('evento_form.menu', ['entity' => $entity]);
            })
            ->addColumn('tipo_display', function($entity){
                return view('evento_form.tipi_campo', ['tipo' => $entity->tipo, 'id' => $entity->id]);
            })
            ->addColumn('obbligatoria', function($entity){
                return view('_partials.available', ['available' => $entity->obbligatoria]);
            })
            ->addColumn('nascosta', function($entity){
                return view('_partials.available', ['available' => $entity->nascosta]);
            })
            ->addColumn('nascondi_se_auth', function($entity){
                return view('_partials.available', ['available' => $entity->nascondi_se_auth]);
            })
            ->addColumn('costo_display', function($entity){
                return '€ ' . number_format($entity->costo, 2, ',', '.');
            })
            ->addColumn('posti_disponibili_display', function($entity){
                return ($entity->posti_disponibili-15).'/'.$entity->posti_disponibili;
            })
            ->setRowId('id');
    }

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

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        $buttons = [];
   
        if(Auth::user()->can('create-evento_form')){
            array_push($buttons, Button::make('create')
                ->editor('editor')
                ->className('btn btn-sm btn-success mb-4')
                ->formTitle('Nuova richiesta')
                ->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> Nuova richiesta'));
        }

           
        if(Auth::user()->can('create-evento_form')){
            array_push($buttons, Button::raw('Aggiungi slot orario')
                ->className('btn btn-sm btn-success mb-4')
                ->action('aggiungiSlotOrario()')
                ->text('<i class="fas fa-plus"></i> slot orario'));
        }

        return $this->builder()
                    ->setTableId($this->dataTableVariable)
                    ->columns($this->getColumns())
                    ->language(asset('assets/Italian.json'))
                    // ->ajax(route('evento-form.index', ['evento_id' => $this->evento_id]))
                    ->buttons($buttons)
                    ->minifiedAjax()
                    ->ajax(route('form-evento.index', ['evento_id' => $this->evento_id]))
                    ->editor(
                        Editor::make()
                            ->fields([
                                Fields\Hidden::make('id'),
                                Fields\Number::make('ordine_visualizzazione')->label('Ordine visualizzazione'),
                                Fields\Text::make('label')->label('Label'),
                                Fields\Text::make('descrizione')->label('Descrizione'),
                                Fields\Boolean::make('obbligatoria')->label('Obbligatoria'),
                                Fields\Boolean::make('nascosta')->label('Nascosta'),
                                Fields\Select::make('tipo')->label('Tipo')->options(EventoForm::getTipi()->pluck('value', 'label')),
                                Fields\Number::make('costo')->label('Costo'),
                                Fields\Number::make('posti_disponibili')->label('Posti disponibili'),
                                Fields\Boolean::make('nascondi_se_auth')->label('Nascondi se autenticato'),
                                // Fields\Text::make('opzioni')->label('Opzioni'),
                                // Fields\Number::make('remote_id')->label('Remote ID'),
                                // Fields\Checkbox::make('posti_definiti_opzioni')->label('Posti definiti opzioni'),
                            ])
                    
                    )
                    // ->ajax(route('evento-form.store'))
                    ->initComplete("function(settings, json){
                        initComplete_evento_form();
                    }")
                    ->dom(count($buttons) == 0 ? 'rtip' : 'Bfrtip')
                    ->responsive(true)
                    ->orderBy(1)
                    ->selectStyleSingle();
                    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::make('id')->visible(false),
            Column::make('tipo_display')->addClass('text-center')->title('#'),
            Column::make('label')->title('Richiesta'),
            Column::make('costo_display')->addClass('text-center')->title('Costo'),
            Column::make('obbligatoria')->addClass('text-center')->title('Obbligatoria'),
            Column::make('nascosta')->addClass('text-center')->title('Nascosta'),
            // Column::make('nascondi_se_auth')->addClass('text-center')->title('Nascondi se autenticato'),
            Column::make('posti_disponibili_display')->addClass('text-center')->title('Posti disponibili'),
            Column::computed('action')->addClass('text-center')->title('')
                  ->width(60)
                  ->addClass('text-center'),
        ];
    }

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