<?php

namespace App\DataTables;

use App\Models\Attivita;
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 AttivitaDataTable extends DataTable
{
    public function __construct(){
        $this->dataTableVariable = 'dataTable_attivita';
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<Attivitum> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function($entity){
              return view('attivita.menu', ['entity' => $entity]);
            })
            ->addColumn('is_attiva_display', function($entity){
              return view('_partials.available', ['available' => $entity->is_attiva]);
            })
            ->addColumn('seleziona_attivita' , function($entity){
                return view('attivita._partials.parziali' , ['oggetto' => 'seleziona_attivita' ,'entity' => $entity]);
            })
            ->setRowId('id');
    }

    /**
     * Get the query source of dataTable.
     *
     * @return QueryBuilder<Attivitum>
     */
    public function query(Attivita $model): QueryBuilder
    {   
        if($this->user_id){
            return $model->newQuery()->where('user_id', $this->user_id)->orderBy('nome', 'asc');
        }else{
            return $model->newQuery()->where('user_id', Auth::user()->id);
        }
    }

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        $buttons = [];
        if(Auth::user()->can('create-attivita')){
            array_push($buttons, Button::make('create')
                ->editor('editor')
                ->className('btn btn-sm btn-primary mb-4')
                ->formTitle('Crea nuova attività')
                ->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 attività'));
        }
        return $this->builder()
                    ->setTableId($this->dataTableVariable)
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->orderBy(1)
                    ->selectStyleSingle()
                    ->responsive(true)
                    ->language(asset('assets/Italian.json'))
                    ->dom(count($buttons) == 0 ? 'rtip' : 'Bfrtip')
                    ->buttons($buttons)
                    ->editor(
                        Editor::make()
                            ->fields([
                                Fields\Hidden::make('user_id')->default(Auth::user()->id),
                                Fields\Text::make('nome')->label('Nome'),
                                Fields\Text::make('descrizione')->label('Descrizione'),
                                Fields\Image::make('path_logo')->label('Logo'),
                                Fields\Image::make('path_icon')->label('Icona'),
                                Fields\Image::make('path_image')->label('Immagine'),
                                Fields\Boolean::make('is_attiva')->label('Attiva')->default(true),
                            ])
                    )
                    ->initComplete("function(settings, json){
                        initComplete_attivita();
                    }");
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::make('id')->visible(false),
            Column::make('is_attiva_display')->title('Disponibile')->addClass('text-center')->responsivePriority(1)->width('10%'),
            Column::make('nome')->responsivePriority(1),
            Column::make('descrizione'),
            // Column::make('path_logo'),
            Column::computed('seleziona_attivita'),
            // Column::make('path_icon'),
            // Column::make('path_image'),
            Column::computed('action')->title('')->width('10%')->addClass('text-center')->responsivePriority(1),
        ];
    }

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