<?php

namespace App\DataTables;

use App\Models\Ordine;
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 OrdineDataTable extends DataTable
{
    public function __construct()
    {
        $this->dataTableVariable = 'dataTable_ordine';
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<Ordine> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function($entity){
                return view('ordine.menu', ['entity' => $entity]);
            })
            ->addColumn('prenotazione_id_display', function($entity){

                if(isset($entity->prenotazione)){
                    return view('prenotazione._partials.btn-link', ['prenotazione' => $entity->prenotazione]);
                } else {
                    return view('_partials.available', ['available' => false]);
                }
            })
            ->addColumn('stato_display', function($entity){
                return view('prenotazione._partials.stato-prenotazione', ['stato' => $entity->stato]);
            })
            ->addColumn('totale', function($entity){
                return $entity->totale;
            })
            ->addColumn('note', function($entity){
                return $entity->note;
            })
            ->addColumn('prezzo_display', function($entity){
                return '€ ' . number_format($entity->prezzo, 2, ',', '.');
            })
            ->addColumn('info_display', function($entity){
                if($entity->info == null){
                    return 'ND';
                }
                $info = json_encode($entity->info);
                $infoArr = json_decode($info, true);
                $cliente = $infoArr['cliente'] ?? 'ND';
                $tavolo = $infoArr['tavolo'] ?? 'ND';
                return 'Cliente: ' . $cliente . ' - Tavolo: ' . $tavolo;
            })
            ->setRowId('id');
    }

    /**
     * Get the query source of dataTable.
     *
     * @return QueryBuilder<Ordine>
     */
    public function query(Ordine $model): QueryBuilder
    {
       if(request()->has('carrelli_aperti')){
        $query = $model->newQuery()
        ->where('attivita_id' , session()->get('attivita_attuale'))
        ->where('stato', Ordine::CARRELLO)
        ->orderBy('created_at', 'desc');
    // dd($query->get());
    return $query;
       }else{
        $query = $model->newQuery()
        ->where('attivita_id' , session()->get('attivita_attuale'))
        ->where('stato', '!=', Ordine::CARRELLO)
        ->orderBy('created_at', 'desc');
    // dd($query->get());
    return $query;
    }
    }

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        $buttons = [];
        if(Auth::user()->can('create-ordine')){
            array_push($buttons, Button::make('create')
                ->editor('editor')
                ->className('btn btn-sm btn-primary mb-4')
                ->formTitle('Crea nuovo ordine')
                ->text('<i class="fas fa-plus"></i> Nuovo ordine'));
        }
        return $this->builder()
                    ->setTableId($this->dataTableVariable)
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->responsive(true)
                    ->pageLength(25)
                    ->lengthMenu([25, 50, 100])
                    ->orderBy(2, 'asc')
                    ->language(asset('assets/Italian.json'))
                    ->dom(count($buttons) == 0 ? 'rtip' : 'Bfrtip')
                    ->selectStyleSingle()
                    ->buttons($buttons)
                    ->editor(
                        Editor::make()
                            ->fields([
                                Fields\Text::make('riferimento')->label('Riferimento'),
                                Fields\Text::make('prenotazione_id')->label('Prenotazione'),
                                Fields\Select::make('tipo')->label('Tipo')->options(Ordine::getTipi()->pluck('value', 'label')),
                                Fields\Select::make('stato')->label('Stato')->options(Ordine::getStati()->pluck('value', 'label')),
                                Fields\Text::make('prezzo')->label('Prezzo'),
                                Fields\Text::make('note')->label('Note'),
                                Fields\Text::make('codice')->label('Codice'),
                                // Fields\Select::make('pagamento_id')->label('Pagamento')->options(Pagamento::all()->pluck('nome', 'id')),
                                Fields\Text::make('info')->label('Info'),
                            ])
                    )
                    ->initComplete("function(settings, json){
                        initComplete_ordine();
                    }");
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::make('id')->title('ID')->addClass('text-center w-10')->responsivePriority(1)->width('10%'),
            Column::make('stato')->data('stato_display')->title('Stato')->responsivePriority(1),
            Column::make('riferimento')->title('Riferimento')->responsivePriority(2),
            Column::make('prenotazione_id')->data('prenotazione_id_display')->title('Prenotazione')->responsivePriority(2),
            Column::make('prezzo')->title('Totale')->data('prezzo_display')->responsivePriority(2),
            Column::make('note')->title('Note')->responsivePriority(2),
            Column::make('info')->title('Info')->data('info_display')->responsivePriority(2),
            Column::computed('action')
                  ->title('')
                  ->exportable(false)
                  ->printable(false)
                  ->width(60)
                  ->addClass('text-center')
                  ->responsivePriority(1),
        ];
    }

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