<?php

namespace App\DataTables;

use App\Models\Categoriacontabile;
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 CategoriacontabileDataTable extends DataTable
{
    public function __construct()
    {
        $this->dataTableVariable = 'dataTable_categoriacontabile';
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<Categoriacontabile> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function($entity){
                return view('categoria_contabile.menu', ['entity' => $entity]);
            })
            ->addColumn('is_attiva_display', function($entity){
                return view('_partials.available', ['available' => $entity->is_attiva]);
            })
            // ->addColumn('colore_display', function($entity){
            //     return '<span class="badge" style="background-color: '.$entity->colore.';">'.$entity->colore.'</span>';
            // })
            ->addColumn('nome_display', function($entity){
                return '<span class="badge" style="background-color: '.$entity->colore.';">'.$entity->nome.'</span>';
            })
            ->rawColumns(['nome_display'])
            ->setRowId('id');
    }

    /**
     * Get the query source of dataTable.
     *
     * @return QueryBuilder<Categoriacontabile>
     */
    public function query(Categoriacontabile $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-categoria_contabile')){
            array_push($buttons, Button::make('create')
                ->editor('editor')
                ->className('btn btn-sm btn-primary mb-4')
                ->formTitle('Crea nuova categoria contabile')
                ->formButtons([
                    Button::raw('Salva')
                        ->className('btn btn-success ml-2 mx-2')
                        ->actionHandler('create')
                    ])
                    ->text('<i class="fas fa-plus"></i> Nuova categoria contabile'));
        }
        
        return $this->builder()
                    ->setTableId($this->dataTableVariable)
                    ->responsive(true)
                    ->pageLength(25)
                    ->lengthMenu([25, 50, 100])
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->orderBy(1)
                    ->language(asset('assets/Italian.json'))
                    ->dom(count($buttons) == 0 ? 'rtip' : 'Bfrtip')
                    ->responsive(true)
                    ->selectStyleSingle()
                    ->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('descrizione')->label('Descrizione'),
                                Fields\Text::make('colore')->label('Colore')->set('attr', ['type' => 'color']),
                                Fields\Boolean::make('is_attiva')->label('Attiva')->default(true),
                            ])
                    )
                    ->initComplete("function(settings, json){
                        initComplete_categoriacontabile();
                    }");
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::make('id'),
            Column::make('is_attiva_display')->title('Attiva'),
            // Column::make('colore')->title('Colore')->data('colore_display'),
            Column::make('nome')->title('Nome')->data('nome_display'),
            Column::make('descrizione')->title('Descrizione'),
            Column::make('action')
                  ->exportable(false)
                  ->printable(false)
                  ->width(60)
                  ->addClass('text-center'),
        ];
    }

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