<?php

namespace App\DataTables;

use App\Models\Evento;
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\DataTables\EventoDataTableEditor;
use Carbon\Carbon;

class EventoDataTable extends DataTable
{
    public function __construct(){
        $this->dataTableVariable = 'dataTable_evento';
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<Evento> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function($entity){
              return view('evento.menu', ['entity' => $entity]);
            })
            ->addColumn('stato_display', function($entity){
              return view('_partials.available', ['available' => $entity->is_attivo]);
            })
            ->addColumn('data_inizio_display', function($entity){
              return Carbon::parse($entity->data_inizio)->format('d/m/Y');
            })
            ->addColumn('data_fine_display', function($entity){
              return Carbon::parse($entity->data_fine)->format('d/m/Y');
            })
            ->addColumn('prezzo_display', function($entity){
              return '€ ' . number_format($entity->prezzo, 2, ',', '.');
            })
            ->addColumn('apertura_prenotazione_display', function($entity){
              return Carbon::parse($entity->apertura_prenotazione)->format('d/m/Y H:i');
            })
            ->addColumn('chiusura_prenotazione_display', function($entity){
              return Carbon::parse($entity->chiusura_prenotazione)->format('d/m/Y H:i');
            })
            ->addColumn('periodo_evento_display', function($entity){
              return Carbon::parse($entity->data_inizio)->format('d/m/Y') . ' - ' . Carbon::parse($entity->data_fine)->format('d/m/Y');
            })
            ->addColumn('periodo_prenotazioni_display', function($entity){
              return Carbon::parse($entity->apertura_prenotazione)->format('d/m/Y') . ' - ' . Carbon::parse($entity->chiusura_prenotazione)->format('d/m/Y');
            })
            ->addColumn('prezzo_fisso_display', function($entity){
              return view('_partials.available', ['available' => $entity->prezzo_fisso]);
            })
            ->setRowId('id');
    }

    /**
     * Get the query source of dataTable.
     *
     * @return QueryBuilder<Evento>
     */
    public function query(Evento $model): QueryBuilder
    {
        return $model->newQuery();
    }

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        $buttons = [];
        if(Auth::user()->can('create-evento')){
            array_push($buttons, Button::make('create')
                ->editor('editor')
                ->className('btn btn-sm btn-primary mb-4')
                ->formTitle('Crea nuovo evento')
                ->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> Nuovo evento'));
        }
        return $this->builder()
                    ->setTableId($this->dataTableVariable)
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->orderBy(1)
                    ->selectStyleSingle()
                    ->language(asset('assets/Italian.json'))
                    ->dom(count($buttons) == 0 ? 'rtip' : 'Bfrtip')
                    ->buttons($buttons)
                    ->searchPanes(true)
                    ->responsive(true)
                    ->editor(
                        Editor::make()
                            ->fields([
                                Fields\File::make('immagine')->label('Locandina'),
                                Fields\File::make('copertina')->label('Copertina'),
                                Fields\Text::make('nome')->label('Nome'),
                                Fields\TextArea::make('descrizione')->label('Descrizione'),
                                Fields\Number::make('posti')->label('Posti'),
                                Fields\DateTime::make('data_inizio')->label('Data inizio'),
                                Fields\DateTime::make('data_fine')->label('Data fine'),
                                Fields\DateTime::make('apertura_prenotazione')->label('Apertura prenotazione'),
                                Fields\DateTime::make('chiusura_prenotazione')->label('Chiusura prenotazione'),
                                Fields\Boolean::make('prezzo_fisso')->label('Prezzo fisso'),
                                Fields\Number::make('prezzo')->label('Prezzo'),
                                Fields\Select::make('stato')->label('Stato'),
                                // ->options(Evento::STATI),
                                Fields\Text::make('note')->label('Note'),
                            ])
                    )
                    ->initComplete("function(settings, json){
                        initComplete_evento();
                    }");
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::make('id')->title('ID')->width('10%')->visible(false),
            Column::make('stato')->data('stato_display')->title('Stato')->addClass('text-center')->responsivePriority(1)->width('10%'),
            Column::make('nome')->title('Nome')->responsivePriority(1),
            // Column::make('descrizione')->title('Descrizione'),
            Column::computed('periodo_evento_display')->title('Periodo evento')->responsivePriority(2),
            Column::computed('periodo_prenotazioni_display')->title('Periodo prenotazioni')->responsivePriority(2),
            Column::make('data_inizio')->title('Data inizio')->data('data_inizio_display')->visible(false)->responsivePriority(2),
            Column::make('data_fine')->title('Data fine')->data('data_fine_display')->visible(false)->responsivePriority(2),
            Column::make('apertura_prenotazione')->title('Apertura prenotazione')->data('apertura_prenotazione_display')->visible(false)->responsivePriority(2),
            Column::make('chiusura_prenotazione')->title('Chiusura prenotazione')->data('chiusura_prenotazione_display')->visible(false)->responsivePriority(2),
            Column::make('prezzo_fisso')->title('Prezzo fisso')->data('prezzo_fisso_display')->addClass('text-center')->responsivePriority(2),
            Column::make('prezzo')->title('Prezzo')->data('prezzo_display')->addClass('text-center')->responsivePriority(2),
            Column::make('note')->title('Note')->visible(false)->responsivePriority(2),
            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 'Evento_' . date('YmdHis');
    }
}
