<?php

namespace App\DataTables;

use App\Models\ChiusuraServizio;
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 ChiusuraServizioDataTable extends DataTable
{
    public function __construct(){
        $this->dataTableVariable = 'dataTable_chiusura_servizio';
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<ChiusuraServizio> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function($query){
                return view('chiusura_servizio.menu', ['entity' => $query]);
            })
            ->addColumn('user_id_display', function($query){
                if($query->user->id == Auth::user()->id){
                    return view('_partials.badge', ['success' => 'Tu']);
                }else{
                    return view('_partials.badge', ['info' => $query->user->name]);
                }
            })
            ->addColumn('info_display', function($query){
                if (empty($query->info)) {
                    return '—';
                }
                $info = is_array($query->info) ? $query->info : json_decode($query->info ?? '[]', true);
                $incasso = (float) ($info['incasso'] ?? 0);
                return '€ ' . number_format($incasso, 2, ',', '.');
            })
            ->setRowId('id');
    }

    /**
     * Get the query source of dataTable.
     *
     * @return QueryBuilder<ChiusuraServizio>
     */
    public function query(ChiusuraServizio $model): QueryBuilder
    {
        return $model->newQuery()->where('attivita_id', $this->attivita_id)->orderBy('chiusura_at', 'desc');
    }

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        $buttons = [];            
        if(Auth::user()->can('create-chiusura-servizio')){
            array_push($buttons, Button::make('create')
                ->editor('editor')
                ->className('btn btn-sm btn-primary mb-4')
                ->formTitle('Crea nuova chiusura di servizio')
                ->text('<i class="fas fa-plus"></i> Nuova chiusura di servizio'));
        }
        return $this->builder()
                    ->setTableId($this->dataTableVariable)
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->orderBy(1)
                    ->selectStyleSingle()
                    ->language(asset('assets/Italian.json'))
                    ->dom(count($buttons) == 0 ? 'rtip' : 'Bfrtip')
                    ->responsive(true)
                    ->buttons($buttons)
                    ->initComplete("function(settings, json){
                        initComplete_chiusura_servizio();
                    }")
                    ->editor(
                        Editor::make()
                            ->fields([
                                Fields\Hidden::make('attivita_id')->label('Attività')->default($this->attivita_id),
                                Fields\Hidden::make('user_id')->label('Utente')->default(Auth::user()->id),
                                Fields\DateTime::make('chiusura_at')->label('Data e ora della chiusura')->default(now()),
                                Fields\Text::make('note')->label('Note'),
                            ])
                    );
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::make('chiusura_at')->title('Data e ora della chiusura')->addClass('text-center')->responsivePriority(1),
            Column::make('note')->title('Note')->responsivePriority(2),
            Column::make('user_id')->title('Utente')->data('user_id_display')->addClass('text-center')->responsivePriority(1),
            Column::make('info')->title('Snapshot')->data('info_display')->addClass('text-center')->responsivePriority(1),
            Column::computed('action')
                  ->addClass('text-center')
                  ->title('')
                  ->exportable(false)
                  ->printable(false)
                  ->width('10%')
                  ->responsivePriority(1),
        ];
    }

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