<?php

namespace App\DataTables;

use App\Models\User;
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 App\Models\Role;
use Illuminate\Support\Str;

class UserDataTable extends DataTable
{
  public function __construct(){
    $this->dataTableVariable = 'dataTable_user';
  }
  /**
  * Build the DataTable class.
  *
  * @param QueryBuilder<User> $query Results from query() method.
  */
  public function dataTable(QueryBuilder $query): EloquentDataTable
  {
    return (new EloquentDataTable($query))
    ->addColumn('action', function($entity){
      return view('user.menu', ['entity' => $entity]);
    })
    ->addColumn('ruolo_display', function($entity){
      return $entity->roles->pluck('display_name')->implode(', ');
    })
    ->addColumn('ruolo_id', function($entity){
      $ruolo = $entity->roles->first();
      return $ruolo ? $ruolo->id : 'Ruolo non assegnato';
    })
    ->addColumn('azienda_display', function($entity){
      return $entity->azienda ? $entity->azienda : '';
    })
    ->setRowId('id');
  }

  /**
  * Get the query source of dataTable.
  *
  * @return QueryBuilder<User>
  */
  public function query(User $model): QueryBuilder
  {
    if(Auth::user()->hasRole('superadmin')){
      return $model->newQuery();
    }else{
      return $model->newQuery()->where('1 = 0');
    }

  }

  /**
  * Optional method if you want to use the html builder.
  */
  public function html(): HtmlBuilder
  {
    $buttons = [];
    if(Auth::user()->can('create-user')){
      array_push($buttons, Button::make('create')
      ->editor('editor')
      ->formTitle('Crea nuova organizzazione')
      ->className('btn btn-sm btn-primary mb-4')
      ->text('<i class="fas fa-plus"></i> Nuova organizzazione'));
    }

    if(Auth::user()->hasRole('superadmin')){
      $roles = Role::orderBy('display_name', 'asc')->pluck('id', 'display_name');

    }else{
      $roles = Role::whereNotIn('name', ['superadmin'])->orderBy('display_name', 'asc')->pluck('id', 'display_name');
    }

    $fields = [
      Fields\Text::make('nome')->label('Nome'),
      Fields\Text::make('cognome')->label('Cognome'),
      Fields\Text::make('telefono')->label('Telefono'),
      Fields\Text::make('email')->label('Email'),
      // Fields\Text::make('password')->label('Password')->default(Str::random(8)),
      Fields\Select::make('ruolo_id')->label('Ruolo')->options($roles)->default(Role::where('name', 'amministratore')->first()->id),
      Fields\Text::make('azienda')->label('Azienda')
    ];

    return $this->builder()
    ->setTableId($this->dataTableVariable)
    ->initComplete("function(settings, json){
        initComplete_user();
                    }")
    ->language(asset('assets/Italian.json'))
    ->columns($this->getColumns())
    ->dom('<"py-2"<"head-label text-center"><"dt-action-buttons"B>><"d-flex justify-content-between align-items-center row mb-2"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>t<"d-flex justify-content-between row"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>')
    ->responsive()
    ->minifiedAjax()
    ->editor(
      Editor::make()
      ->fields($fields)
      )
      ->buttons($buttons)
      ->orderBy(0, 'asc');
    }

    /**
    * Get the dataTable columns definition.
    */
    public function getColumns(): array
    {
      $columns = [
        Column::make('id')->visible(false),
        Column::make('nome')->title('Nome'),
        Column::make('cognome')->title('Cognome'),
        Column::make('telefono')->title('Telefono'),
        Column::make('email')->title('Email'),
        Column::make('ruolo_id')->title('Ruolo')->searchable(false)->name('ruolo_id')->data('ruolo_display'),
        Column::make('azienda')->title('Azienda')->data('azienda_display')->searchable(false),
        Column::computed('action')
        ->exportable(false)
        ->printable(false)
        ->width('10%')
        ->title(' ')
        ->addClass('text-end')
      ];

      return $columns;
    }
  }
