<?php

namespace App\DataTables;

use App\Models\PrimaNota;
use App\Models\Pagamento;
use App\Models\Ordine;
use App\Models\Prenotazione;
use App\Models\Evento;
use App\Models\Fornitore;
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 Carbon\Carbon;


class PrimaNotaDataTable extends DataTable
{
    public function __construct()
    {
        $this->dataTableVariable = 'dataTable_primanota';
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<PrimaNotum> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function($entity){
                return view('prima_nota.menu', ['entity' => $entity]);
            })
            ->addColumn('attivita_id_display', function($entity){
                return $entity->attivita->nome??'N/A';
            })
            ->addColumn('pagamento_id_display', function($entity){
                if(isset($entity->pagamento)){
                    return view('prima_nota._partials.display', ['oggetto' => 'pagamento', 'entity' => $entity->pagamento]);
                } else {
                    return '-';
                }
            })
            ->addColumn('ordine_id_display', function($entity){
                if(isset($entity->ordine)){
                    return view('prima_nota._partials.display', ['oggetto' => 'ordine', 'entity' => $entity->ordine]);
                } else {
                    return '-';
                }
            })
            ->addColumn('prenotazione_id_display', function($entity){
                if(isset($entity->prenotazione)){
                    return view('prima_nota._partials.display', ['oggetto' => 'prenotazione', 'entity' => $entity->prenotazione]);
                } else {
                    return '-';
                }            })
            ->addColumn('evento_id_display', function($entity){
                if(isset($entity->evento)){
                    return view('prima_nota._partials.display', ['oggetto' => 'evento', 'entity' => $entity->evento]);
                } else {
                    return '-';
                }
            })
            ->addColumn('fornitore_id_display', function($entity){
                if(isset($entity->fornitore)){
                    return view('prima_nota._partials.display', ['oggetto' => 'fornitore', 'entity' => $entity->fornitore]);
                } else {
                    return '-';
                }
            })
            ->addColumn('importo_display', function($entity){
                return '€ ' . number_format($entity->importo, 2, ',', '.');
            })
            ->addColumn('tipo_movimento_display', function($entity){
                return PrimaNota::getTipiMovimento()->where('value', $entity->tipo_movimento)->first()['label']??'N/A';
            })
            ->addColumn('causale_display', function($entity){
                return $entity->causale??'N/A';
            })
            ->addColumn('stato_display', function($entity){
                // return PrimaNota::getStati()->where('value', $entity->stato)->first()['label']??'N/A';
            })
            ->addColumn('entrata_display', function($entity){
                if($entity->tipo_movimento == PrimaNota::ENTRATA){  
                    return view('prima_nota._partials.display', ['oggetto' => 'entrata', 'entity' => $entity]);
                } else {
                    return '-';
                }
            })
            ->addColumn('uscita_display', function($entity){
                if($entity->tipo_movimento == PrimaNota::USCITA){
                    return view('prima_nota._partials.display', ['oggetto' => 'uscita', 'entity' => $entity]);
                } else {
                    return '-';
                }
            })
            ->addColumn('data_display', function($entity){
                return Carbon::parse($entity->created_at)->format('d/m/Y H:i');
            })
            ->addColumn('categoria_contabile_id_display', function($entity){
            //   return '<span class="badge" style="background-color: '.$entity->categoria_contabile?->colore.';">'.$entity->categoria_contabile?->nome.'</span>';
            return view('_partials.badge', ['entity' => $entity]);
        })
            ->rawColumns(['categoria_contabile_id_display'])
            ->setRowId('id');
    }

    /**
     * Get the query source of dataTable.
     *
     * @return QueryBuilder<PrimaNota>
     */
    public function query(PrimaNota $model): QueryBuilder
    {
        if (!$this->attivita_id) {
            return $model->newQuery()->whereRaw('1 = 0');
        }

        return $model->newQuery()
            ->where('attivita_id', $this->attivita_id)
            ->conFiltriIndice()
            ->orderBy('created_at', 'desc');
    }

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        $buttons = [];
        if(Auth::user()->can('create-primanota')){
            array_push($buttons, Button::make('create')
                ->editor('editor')
                ->className('btn btn-sm btn-primary mb-4')
                ->formTitle('Crea nuovo movimento')
                ->formButtons([
                    // Button::raw('Annulla')
                    //     ->className('btn btn-secondary ml-2 mx-2')
                    //     ->actionClose(),
                    Button::raw('Salva')
                        ->className('btn btn-success ml-2 mx-2')
                        ->actionHandler('create')
                ])
                ->text('<i class="fas fa-plus"></i> Nuovo movimento'));
        }

        if(Auth::user()->can('edit-primanota')){
            array_push($buttons, Button::raw('Report')
                ->className('btn btn-sm btn-primary mb-4')
                ->action('function(){
                    reportPrimaNota();
                }')
                ->text('<i class="fas fa-file-alt"></i> Report'));
        }

        if(Auth::user()->can('view-bilancio')){
            array_push($buttons, Button::raw('Consulta dati')
                ->className('btn btn-sm btn-primary mb-4')
                ->action('window.location.href = "'.route('bilancio.index').'";')
                ->text('<i class="fas fa-chart-line"></i> Consulta dati'));
        }
        if(Auth::user()->can('view-categoria_contabile')){
            array_push($buttons, Button::raw('Categorie contabili')
                ->className('btn btn-sm btn-primary mb-4')
                ->action('window.location.href = "'.route('categoria-contabile.index').'";')
                ->text('<i class="fas fa-chart-line"></i> Categorie contabili'));
        }
        
        return $this->builder()
                    ->setTableId($this->dataTableVariable)
                    ->columns($this->getColumns())
                    ->minifiedAjax('', '
                        data.data_inizio = $("#filtro_data_inizio").val();
                        data.data_fine = $("#filtro_data_fine").val();
                        data.categoria_contabile_id = $("#categoria_contabile_id").val();
                        data.tipo_movimento = $("#tipo_movimento").val();
                    ')
                    ->language(asset('assets/Italian.json'))
                    // ->dom('<"py-2"<"head-label text-center"><"dt-action-buttons"B>><"d-flex justify-content-between align-items-center row mb-2"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>t<"d-flex justify-content-between row"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>')
                    ->dom(count($buttons) == 0 ? 'Prtip' : 'PBfrtip')
                    ->buttons($buttons)
                    // ->searchPanes(true)
                    ->responsive(true)
                    // ->pageLength(25)
                    ->lengthMenu([25, 50, 100])
                    ->orderBy(1)    
                    // ->selectStyleSingle()
                    ->buttons($buttons)
                    ->editor(
                        Editor::make()
                            ->fields([
                                Fields\Hidden::make('attivita_id')->default($this->attivita_id),
                                Fields\Select2::make('tipo_movimento')->label('Tipo movimento')->options(PrimaNota::getTipiMovimento()->pluck('value', 'label')),
                                Fields\Select2::make('categoria_contabile_id')->label('Categoria contabile')->options(\App\Models\Categoriacontabile::where('is_attiva', true)->pluck('id', 'nome')),
                                Fields\Text::make('importo')->label('Importo'),
                                Fields\Text::make('causale')->label('Causale'),
                                Fields\Text::make('riferimento')->label('Riferimento'),
                                Fields\Select2::make('evento_id')
                                ->label('Evento')
                                ->options(
                                    collect(['Nessun evento' => ''])->merge(Evento::all()->pluck('id', 'nome'))->toArray()
                                ),
                                Fields\Select2::make('fornitore_id')
                                ->label('Fornitore')
                                ->options(
                                    collect(['Nessun fornitore' => ''])->merge(Fornitore::all()->pluck('id', 'nome'))->toArray()
                                ),
                                
                                // Fields\Checkbox::make('tipo_movimento')->label('Tipo movimento')->options(PrimaNota::getTipiMovimento()->pluck('value', 'label')),
                                // Fields\Select2::make('stato')->label('Stato')->options(PrimaNota::getStati()->pluck('value', 'label')),
                                // Fields\Text::make('note')->label('Note'),
                                // Fields\Select2::make('pagamento_id')->label('Pagamento')->options(Pagamento::all()->pluck('id', 'nome')),
                                // 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('stato_pagamento')->label('Stato pagamento'),
                                // Fields\Text::make('metodo_pagamento')->label('Metodo pagamento'),
                                // Fields\Text::make('info')->label('Info'),
      
                            ])
                    )
                    ->initComplete("function(settings, json){
                        initComplete_primanota();
                    }");
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::make('id')->title('ID')->width('10%')->visible(false),
            Column::make('attivita_id')->title('Attività')->data('attivita_id_display')->visible(false),
            Column::computed('data_display')->title('Data')->searchable(true),
            Column::make('categoria_contabile_id')->title('Categoria contabile')->data('categoria_contabile_id_display')->searchable(true),
            Column::make('causale')->title('Causale')->data('causale_display')->searchable(true),
            Column::make('entrata')->title('Entrata')->data('entrata_display')->searchable(false),
            Column::make('uscita')->title('Uscita')->data('uscita_display')->searchable(false),
            // Column::make('pagamento_id')->title('Pagamento')->data('pagamento_id_display'),
            // Column::make('ordine_id')->title('Ordine')->data('ordine_id_display'),
            // Column::make('prenotazione_id')->title('Prenotazione')->data('prenotazione_id_display'),
            // Column::make('evento_id')->title('Evento')->data('evento_id_display'),
            // Column::make('fornitore_id')->title('Fornitore')->data('fornitore_id_display'),

            
            // Column::make('riferimento')->title('Riferimento'),
            // Column::make('importo')->title('Importo')->data('importo_display'),
            // Column::make('tipo_movimento')->title('Tipo movimento')->data('tipo_movimento_display'),
            // Column::make('stato')->title('Stato'),
            Column::computed('action')
                  ->title('')
                  ->exportable(false)
                  ->printable(false)
                  ->width(60)
                  ->addClass('text-center'),
        ];
    }

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