<?php

namespace App\DataTables;

use App\Models\MetodoPagamento;
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\Models\Attivita;


class MetodoPagamentoDataTable extends DataTable
{
    public function __construct()
    {
        $this->dataTableVariable = 'dataTable_metodo_pagamento';
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<MetodoPagamento> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function($entity){
                return view('metodo_pagamento.menu', ['entity' => $entity]);
            })
            ->addColumn('is_attivo_display', function($entity){
                return view('_partials.available', ['available' => $entity->is_attivo]);
            })
            ->addColumn('is_pubblico_display', function($entity){
                return view('_partials.available', ['available' => $entity->is_pubblico]);
            })
            ->addColumn('escludi_contabilita_display', function($entity){
                if($entity->escludi_contabilita){
                    return view('_partials.badge', ['error' => 'Si']);
                }else{
                    return view('_partials.badge', ['success' => 'No']);
                }
            })
            ->setRowId('id');
    }

    /**
     * Get the query source of dataTable.
     *
     * @return QueryBuilder<MetodoPagamento>
     */
    public function query(MetodoPagamento $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-metodo_pagamento')){
            array_push($buttons, Button::make('create')
                ->editor('editor')
                ->className('btn btn-sm btn-primary mb-4')
                ->formTitle('Crea nuovo metodo di pagamento')
                ->text('<i class="fas fa-plus"></i> Nuovo metodo di pagamento'));
        }
        return $this->builder()
                    ->setTableId($this->dataTableVariable)
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->language(asset('assets/Italian.json'))
                    ->dom(count($buttons) == 0 ? 'rtip' : 'Bfrtip')
                    ->buttons($buttons)
                    ->orderBy(1)
                    ->responsive(true)
                    ->selectStyleSingle()
                    ->editor(
                        Editor::make()
                            ->fields([
                                Fields\Hidden::make('attivita_id')->label('Attività')->default($this->attivita_id),
                                Fields\Boolean::make('is_attivo')->label('Attivo')->default(true),
                                Fields\Select2::make('tipo')->label('Tipo')->options(MetodoPagamento::getTipiPagamento()->sortBy('label')->pluck('value' ,'label')),
                                Fields\Text::make('nome')->label('Nome'),
                                Fields\Text::make('descrizione')->label('Descrizione'),
                                Fields\Boolean::make('escludi_contabilita')->label('Escludi dalla contabilità')->default(false),
                                Fields\Boolean::make('is_pubblico')->label('Pubblico')->default(false),
                                Fields\Text::make('key')->label('Key'),
                                Fields\Text::make('secret')->label('Secret'),
                                Fields\Text::make('path_img')->label('Path immagine'),
                                Fields\Text::make('info')->label('Info'),
                            ])
                    )
                    ->initComplete("function(settings, json){
                        initComplete_metodo_pagamento();
                    }");
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::make('id')->title('ID')->width('10%')->visible(false),
            Column::make('is_attivo')->data('is_attivo_display')->title('Attivo')->addClass('text-center w-10')->responsivePriority(1)->width('10%'),
            Column::make('is_pubblico')->data('is_pubblico_display')->title('Pubblico')->addClass('text-center w-10')->responsivePriority(2)->width('10%'),
            Column::make('nome')->title('Nome')->responsivePriority(1),
            Column::make('escludi_contabilita')->data('escludi_contabilita_display')->title('Escludi dalla contabilità')->addClass('text-center')->responsivePriority(3),
            Column::make('descrizione')->title('Descrizione')->responsivePriority(2),
            Column::computed('action')->title('')->width('10%')->addClass('text-center')->responsivePriority(1),   
        ];
    }

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