<?php

namespace App\DataTables;

use App\Models\Impostazioni;
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 ImpostazioniDataTable extends DataTable
{
    public function __construct(){
        $this->dataTableVariable = 'dataTable_impostazioni';
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<Impostazioni> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function($entity){
                return view('impostazioni.menu', ['entity' => $entity]);
            })
            ->editColumn('valore', function($entity){
                if($entity->tipo == 'array'){
                    $giorni = \App\Models\Asporto::getGiorniDisponibilitaAsporto();
                    $items = array_filter(array_map('trim', explode(',', (string) $entity->valore)));
                    $nomi = [];
                    foreach($items as $item){
                        if($giorni->has($item)) {
                            $nomi[] = $giorni->get($item);
                        }
                    }
                    return implode(', ', $nomi);
               
                }else if($entity->tipo == 'boolean'){
                    return $entity->valore == 1 || $entity->valore === 1 || $entity->valore === true || $entity->valore === 'true' ? 'Attivo' : 'Disattivo';
                }
                return $entity->valore;
            })
            ->setRowId('id');
    }

    /**
     * Get the query source of dataTable.
     *
     * @return QueryBuilder<Impostazioni>
     */
    public function query(Impostazioni $model): QueryBuilder
    {
        if($this->attivita_id){
            return $model->newQuery()->where('attivita_id', $this->attivita_id)->orderBy('gruppo', 'asc');
        }else{
            return $model->newQuery()->whereRaw('1 = 0')->orderBy('gruppo', 'asc');
        }
    }

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        $buttons = [];
        if(Auth::user()->hasRole('superadmin')){
            array_push($buttons, Button::make('create')
                ->editor('editor')
                ->className('btn btn-sm btn-primary mb-4')
                ->formTitle('Crea nuova impostazione')
                ->text('<i class="fas fa-plus"></i> Nuova impostazione'));
        }

        $editorFields = [
            Fields\Hidden::make('attivita_id')->default($this->attivita_id),
            Fields\Text::make('valore')->label('Valore')->fieldInfo('Rispetta il formato del tipo di dato'),
            ];
            
            if(Auth::user()->hasRole('superadmin')){
            $editorFields[] =Fields\Text::make('label')->label('Label');
            $editorFields[] =Fields\Text::make('descrizione')->label('Descrizione');
            $editorFields[] =Fields\Text::make('opzioni')->label('Opzioni');
            $editorFields[] =Fields\Text::make('gruppo')->label('Gruppo');
            $editorFields[] = Fields\Text::make('chiave')->label('Chiave');
            $editorFields[] = Fields\Select::make('tipo')->label('Tipo')->options(Impostazioni::getTipi());
        }

        return $this->builder()
                    ->setTableId($this->dataTableVariable)
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->pageLength(20)
                    ->responsive(true)
                    ->orderBy(1)
                    ->selectStyleSingle()
                    ->buttons($buttons)
                    ->language(asset('assets/Italian.json'))
                    ->dom(count($buttons) == 0 ? 'rtip' : 'Bfrtip')
                    ->editor(
                        Editor::make()->fields($editorFields)
                    )
                    ->initComplete("function(settings, json){
                        initComplete_impostazioni();
                    }")
                    ->drawCallback("function(settings){
                        drawCallback_impostazioni(settings);
                    }");
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        $columns = [
            Column::make('id')->visible(false),
            Column::make('gruppo')->visible(false),
        ];

        if(Auth::user()->hasRole('superadmin')){
            $columns[] = Column::make('chiave');
            $columns[] = Column::make('tipo')->title('Tipo');
        }

        $columns[] = Column::make('label');
        $columns[] = Column::make('valore')->title('Valore')->width('30%');
        $columns[] = Column::make('descrizione')->title('Descrizione')->width('30%');
        $columns[] = Column::make('opzioni')->title('Opzioni')->visible(false);
        $columns[] = Column::computed('action')
                  ->title('')
                  ->exportable(false)
                  ->printable(false)
                  ->width(60)
                  ->addClass('text-center')
                  ->responsivePriority(1);

        return $columns;
    }

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