<?php

namespace App\DataTables;

use App\Models\Endpoint;
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 EndpointDataTable extends DataTable
{
    public function __construct()
    {
        $this->dataTableVariable = 'dataTable_endpoint';
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<Endpoint> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function($entity){
                return view('endpoint.menu', ['entity' => $entity]);
            })
            ->addColumn('stampanti_count', function($entity){
                // return print_r([count($entity->info['stampanti']) , Endpoint::find($entity->id)->stampanti->count()], true);
                return Endpoint::find($entity->id)->stampanti()->count();
            })
            ->addColumn('stampanti_display', function($entity){
                return Endpoint::find($entity->id)->stampanti->pluck('nome')->implode(', ');
            })
            ->addColumn('product_key_display', function($entity){
                return view('endpoint.nuovo_product_key', ['success' => true, 'endpoint' => $entity, 'datatable' => true]);
            })
            ->addColumn('status_display', function($entity){
                return view('endpoint._partials.status', ['status' => $entity->status]);
            })
            ->setRowId('id');
    }

    /**
     * Get the query source of dataTable.
     *
     * @return QueryBuilder<Endpoint>
     */
    public function query(Endpoint $model): QueryBuilder
    {
        return $model->newQuery()->where('attivita_id', session()->get('attivita_attuale'));
    }

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        $buttons = [];
        if(Auth::user()->can('create-endpoint')){
            // array_push($buttons, Button::make('create')
            //     ->editor('editor')
            //     ->className('btn btn-sm btn-primary mb-4')
            //     ->formTitle('Crea nuovo endpoint')
            //     ->text('<i class="fas fa-plus"></i> Nuovo endpoint'));
            array_push($buttons, Button::raw()
                ->className('btn btn-sm btn-primary mb-4')
                ->action('function(){
                    richiediNuovoProductKey();
                }')
                ->text('<i class="fas fa-plus"></i> Richiedi nuovo product key'));
        }
        if(Auth::user()->can('view-endpoint')){
            array_push($buttons, Button::raw()
                ->className('btn btn-sm btn-primary mb-4')
                ->action('istruzioni()')
                ->text('<i class="fas fa-info-circle"></i> Istruzioni'));
        }

        return $this->builder()
                    ->setTableId($this->dataTableVariable)
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->language(asset('assets/Italian.json'))
                    ->dom(count($buttons) == 0 ? 'rtip' : 'Bfrtip')
                    ->buttons($buttons)
                    ->orderBy(1)
                    ->responsive(true)
                    ->editor(
                        Editor::make()
                            ->fields([
                                Fields\Text::make('label')->label('Label'),
                                Fields\Text::make('descrizione')->label('Descrizione'),
                                Fields\Text::make('ubicazione')->label('Ubicazione'),
                                Fields\Text::make('url')->label('URL'),
                            ])
                    )
                    ->initComplete("function(settings, json){
                        initComplete_endpoint();
                    }")
                    ->selectStyleSingle()
                    ->buttons($buttons);
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::make('id')->title('ID')->addClass('text-center w-10')->responsivePriority(1),
            Column::make('status')->title('Status')->data('status_display'),
            Column::make('label')->title('Etichetta')->responsivePriority(1),
            Column::make('descrizione')->title('Descrizione'),
            Column::make('ubicazione')->title('Ubicazione'),
            Column::make('stampanti_display')->title('Stampanti'),
            Column::make('url')->title('URL')->visible(false),
            Column::make('user_id')->title('User ID')->visible(false),
            Column::make('product_key_display')->title('Product Key'),
            // Column::make('token')->title('Token'),
            // Column::make('secret')->title('Secret'),
            // Column::make('type')->title('Type'),
            // Column::make('version')->title('Version'),
            Column::make('licenza_id')->title('Licenza ID'),
            Column::make('stampanti_count')->title('Stampanti'),
            // Column::make('last_heartbeat')->title('Last Heartbeat'),
            // Column::make('last_activity')->title('Last Activity'),
            // Column::make('created_at')->title('Created At'),
            // Column::make('updated_at')->title('Updated At'),
            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 'Endpoint_' . date('YmdHis');
    }
}
