<?php

namespace App\DataTables;

use App\Models\Dispositivo;
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 MonitorDataTable extends DataTable
{
    public function __construct()
    {
        $this->dataTableVariable = 'dataTable_monitor';
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<Monitor> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function($entity){
                return view('monitor.menu', ['entity' => $entity]);
            })
            ->addColumn('is_attivo_display', function($entity){
                return view('_partials.available', ['available' => $entity->is_attivo]);
            })
            ->addColumn('attivita_id_display', function($entity){
                return $entity->attivita ? $entity->attivita->nome : 'ND';
            })
            ->addColumn('contenuto_display', function($entity){
                $monitor_has_contenuto = $entity->monitor_has_contenuto;
                return $monitor_has_contenuto ? $monitor_has_contenuto->is_bacheca ? 'Bacheca: '.$monitor_has_contenuto->bacheca->nome : 'Cucina: '.$monitor_has_contenuto->cucina->nome : 'ND';
            })
            ->setRowId('id');
    }

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

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        $buttons = [];
        if(Auth::user()->can('create-monitor')){
            array_push($buttons, Button::make('create')
                ->editor('editor')
                ->formTitle('Crea nuovo monitor')
                ->className('btn btn-sm btn-primary mb-4')
                ->text('<i class="fas fa-plus"></i> Nuovo monitor'));
        }
        return $this->builder()
                    ->setTableId($this->dataTableVariable)
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->language(asset('assets/Italian.json'))
                    ->dom(count($buttons) == 0 ? 'rtip' : 'Bfrtip')
                    ->buttons($buttons)
                    ->editor(
                        Editor::make()
                            ->fields([
                                Fields\Hidden::make('attivita_id')->label('Attività')->default($this->attivita_id),
                                Fields\Text::make('nome')->label('Nome'),
                                Fields\Boolean::make('is_attivo')->label('Attivo')->default(true),
                                Fields\Hidden::make('tipo')->label('Tipo')->default(Dispositivo::MONITOR),
                                Fields\Text::make('licenza')->label('Licenza'),
                                Fields\Text::make('ubicazione')->label('Ubicazione'),
                                Fields\Text::make('note')->label('Note'),
                                // Fields\Text::make('pin_sblocco')->label('Pin di sblocco'),
                                // Fields\DateTime::make('data_apertura_dispositivo')->label('Data di apertura del dispositivo'),
                                // Fields\DateTime::make('data_chiusura_dispositivo')->label('Data di chiusura del dispositivo'),
                            ])
                    )
                    ->responsive(true)
                    ->orderBy(1)
                    ->selectStyleSingle()
                    ->initComplete("function(settings, json){
                        initComplete_monitor();
                    }");
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::make('id')->visible(false),
            Column::make('is_attivo')->data('is_attivo_display')->title('Pubblicato'),
            Column::make('attivita_id')->title('Attività')->data('attivita_id_display')->visible(false),
            Column::make('nome')->title('Titolo'),
            Column::make('licenza')->title('Licenza'),
            Column::make('ubicazione')->title('Ubicazione'),
            Column::make('contenuto_display')->title('Contenuto'),
            Column::make('note')->title('Note')->visible(false),
            Column::computed('action')->title('')->width('10%')->addClass('text-center'),
        ];
    }

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