<?php

namespace App\DataTables;

use App\Models\Operatore;
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 OperatoreDataTable extends DataTable
{
    public function __construct()
    {
        $this->dataTableVariable = 'dataTable_operatore';
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<Operatore> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function($entity){
                return view('operatore.menu', ['entity' => $entity]);
            })
            ->addColumn('is_attivo_display', function($entity){
                return view('_partials.available', ['available' => $entity->is_attivo]);
            })
            ->setRowId('id');
    }

    /**
     * Get the query source of dataTable.
     *
     * @return QueryBuilder<Operatore>
     */
    public function query(Operatore $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-operatore')){
            array_push($buttons, Button::make('create')
                ->editor('editor')
                ->className('btn btn-sm btn-primary mb-4')
                ->formTitle('Crea nuovo operatore')
                ->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 operatore'));
        }
        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('attivita_id')->label('Attività')->default($this->attivita_id),
                                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\Text::make('username')->label('Username'),
                                // Fields\Text::make('password')->label('Password'),
                                Fields\Boolean::make('is_attivo')->label('Attivo')->default(true),
                            ])
                    )
                    ->initComplete("function(settings, json){
                        initComplete_operatore();
                    }");
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::make('is_attivo_display')->title('Operativo'),
            Column::make('id')->visible(false),
            Column::make('username')->responsivePriority(1),
            // Column::make('nome'),
            // Column::make('cognome'),
            Column::make('email'),
            // Column::make('telefono'),
            // Column::make('password'),
            Column::computed('action')
                  ->addClass('text-center')
                  ->title('')
                  ->exportable(false)
                  ->printable(false)
                  ->width('10%')
                  ->responsivePriority(1),
        ];
    }

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