<?php

namespace App\DataTables;

use App\Models\Pagamento;
use App\Models\Ordine;
use App\Models\Prenotazione;
use App\Models\MetodoPagamento;
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;
use Illuminate\Support\Facades\Session;

class PagamentoDataTable extends DataTable
{
    public function __construct()
    {
        $this->dataTableVariable = 'dataTable_pagamento';
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<Pagamento> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function($entity){
                return view('pagamento.menu', ['entity' => $entity]);
            })
            ->addColumn('ordine_id_display', function($entity){
                return $entity->ordine->id;
            })
            ->addColumn('prenotazione_id_display', function($entity){
                return $entity->prenotazione->id ?? '-';
            })  
            ->addColumn('importo_display', function($entity){
                return '€ ' . number_format($entity->importo, 2, ',', '.');
            })
            ->addColumn('attivita_id_display', function($entity){
                return $entity->attivita->nome;
            })
            ->addColumn('metodo_pagamento_id_display', function($entity){
                return $entity->metodo_pagamento->nome;
            })
            ->addColumn('stato_display', function($entity){
                // return $entity->stato;
                return view('prenotazione._partials.stato-prenotazione', ['stato' => $entity->stato]);
            })
            ->setRowId('id');
    }

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

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        $buttons = [];
        if(Auth::user()->hasRole('superadmin')){  //Auth::user()->can('create-pagamento')
            array_push($buttons, Button::make('create')
                ->editor('editor')
                ->className('btn btn-sm btn-primary mb-4')
                ->formTitle('Crea nuovo pagamento')
                ->text('<i class="fas fa-plus"></i> Nuovo 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)
                    ->selectStyleSingle()
                    ->buttons($buttons)
                    ->editor(
                        Editor::make()
                            ->fields([
                                Fields\Text::make('attivita_id')->label('Attività')->options(Attivita::all()->pluck('nome', 'id')),
                                Fields\Select2::make('ordine_id')->label('Ordine')->options(Ordine::all()->pluck('id', 'nome')),
                                Fields\Select2::make('prenotazione_id')->label('Prenotazione')->options(Prenotazione::all()->pluck('id', 'nome')),
                                Fields\Text::make('importo')->label('Importo'),
                                Fields\Text::make('causale')->label('Causale'),
                                Fields\Select2::make('stato')->label('Stato')->options(Pagamento::getStati()->pluck('value', 'label')),
                                Fields\Select2::make('metodo_pagamento_id')->label('Metodo pagamento')->options(MetodoPagamento::all()->pluck('id', 'nome')),
                                Fields\Text::make('note')->label('Note'),
                                Fields\Text::make('info')->label('Info'),
                            ])
                    )
                    ->initComplete("function(settings, json){
                        initComplete_pagamento();
                    }");
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::make('id')->title('ID')->width('10%')->visible(false),
            Column::make('stato')->title('Stato')->data('stato_display'),
            Column::make('attivita_id')->title('Attività')->data('attivita_id_display'),
            Column::make('ordine_id')->title('Ordine')->data('ordine_id_display'),
            Column::make('prenotazione_id')->title('Prenotazione')->data('prenotazione_id_display'),
            Column::make('importo')->title('Importo')->data('importo_display'),
            Column::make('causale')->title('Causale'),
            Column::make('metodo_pagamento_id')->title('Metodo pagamento')->data('metodo_pagamento_id_display'),
            Column::make('note')->title('Note'),
            Column::computed('action')
                  ->title('')
                  ->exportable(false)
                  ->printable(false)
                  ->width(60)
                  ->addClass('text-center'),
        ];
    }

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