<?php

namespace App\DataTables;

use App\Models\RigaFatturazione;
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 RigaFatturazioneDataTable extends DataTable
{
    public function __construct()
    {
        $this->dataTableVariable = 'dataTable_riga_fatturazione';
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<Fatturazione> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function ($entity) {
                return view('fatturazione.menu',['entity' => $entity]);
            })
            ->addColumn('attivita_id', function ($entity) {
                return $entity->attivita->nome??'ND';
            })
            ->addColumn('dispositivo_id', function ($entity) {
                return $entity->dispositivo->nome??'ND';
            })
            ->addColumn('prezzo', function ($entity) {
                return number_format($entity->prezzo, 2, ',', '.') . ' €';
            })
            ->addColumn('stato_display', function ($entity) {
                return view('fatturazione.stato',['entity' => $entity]);
            })
            ->addColumn('listino_prezzi_display', function ($entity) {
                return optional($entity->listinoPrezzi)->label;
            })
            ->rawColumns(['note'])
            ->setRowId('id');
    }

    /**
     * Get the query source of dataTable.
     *
     * @return QueryBuilder<Fatturazione>
     */
    public function query(RigaFatturazione $model): QueryBuilder
    {
        $query = $model->newQuery()->orderBy('created_at', 'desc');

        if(!$this->tutti_i_consumi){
            $query->whereIn('stato', [RigaFatturazione::GRATUITO, RigaFatturazione::REGISTRATO]);
        }
        if($this->superadmin){
            return $query;
            }
            
            if($this->user_id){
                $query->where('user_id', $this->user_id);
            }
            if($this->attivita_id){
                $query->where('attivita_id', $this->attivita_id);
            }

        return $query;
    }

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        $buttons = [];

            if(Auth::user()->hasRole('amministratore')){
                if(!$this->tutti_i_consumi){
                array_push($buttons,
                Button::raw('')
                ->addClass('btn-primary')
                ->text('<i class="bx bx-abacus me-1"></i> Mostra tutti i consumi')
                ->className('btn btn-primary btn-sm')
                ->action('mostra_tutti_i_consumi(true)')
                );
            }else{
                array_push($buttons,
                Button::raw('')
                ->addClass('btn-primary')
                ->text('<i class="bx bx-abacus me-1"></i> Mostra solo consumi non fatturati')
                ->className('btn btn-primary btn-sm')
                ->action('mostra_tutti_i_consumi(false)')
                );
            }

        }

        if(Auth::user()->hasRole('superadmin')){
            array_push($buttons,
            Button::make('create')
            ->addClass('btn-primary')
            ->text('<i class="bx bx-plus"></i> Consumo')
            ->className('btn btn-primary')
            ->editor('editor')
            ->formTitle('Aggiungi consumo')
            );

        }

        return $this->builder()
                    ->setTableId($this->dataTableVariable)
                    ->columns($this->getColumns())
                    ->dom('PBfrtip')
                    ->language(asset('assets/Italian.json'))
                    ->minifiedAjax()
                    ->responsive(true)
                    ->orderBy(1)
                    ->searchPanes([
                        'layout' => 'columns-3',
                        'cascadePanes' => true,
                    ])
                    ->editor(
                        Editor::make()->fields([
                            Fields\Select2::make('listino_prezzi_id')->label('Listino prezzi')->options(\App\Models\ListinoPrezzi::all()->pluck('id','descrizione')),
                            Fields\Select2::make('attivita_id')->label('Attività')->options(\App\Models\Attivita::all()->pluck('id','nome')),
                            Fields\Select2::make('dispositivo_id')->label('Dispositivo')->options(\App\Models\Dispositivo::all()->pluck('id','nome')),
                            // Fields\Number::make('prezzo')->label('Prezzo'),
                            Fields\Number::make('qta')->label('Qta'),
                            // Fields\Text::make('tipo')->label('Tipo'),
                        ])
                    )
                    ->selectStyleSingle()
                    ->buttons($buttons)
                    ->initComplete('function ($query) {
                        initComplete_riga_fatturazione();
                    }');
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::make('id'),
            Column::make('fattura_id')->title('Fattura'),
            Column::make('attivita_id')->title('Attività')->searchable(true)->searchPanes(['show' => true]),
            Column::make('dispositivo_id')->title('Dispositivo')->searchPanes(['show' => true]),
            Column::make('tipo')->title('Tipo'),
            Column::make('qta')->title('Qta'),
            Column::make('ordini')->title('Ordini'),
            Column::make('listino_prezzi_id')->title('Listino prezzi')->data('listino_prezzi_display'),
            Column::make('prezzo'),
            Column::make('stato')->data('stato_display'),
            Column::make('note'),
        ];

        if(Auth::user()->hasRole('superadmin')){
            array_push($columns,
            Column::make('action')
                  ->title('')
                  ->addClass('text-center')
                  ->exportable(false)
                  ->printable(false)
                  ->width(60)
                  ->addClass('text-center'),
            );
        }
        return $columns;
    }

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