<?php

namespace App\DataTables;

use Yajra\DataTables\Services\DataTable;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use App\Models\Azienda;
use Form;
use Auth;

class AziendaDataTable extends DataTable
{
  public function __construct(){
    $this->dataTableVariable = 'dataTable_azienda';
  }

  /**
  * Build DataTable class.
  *
  * @param mixed $query Results from query() method.
  * @return \Yajra\DataTables\DataTableAbstract
  */
  public function dataTable($query)
  {
    return datatables()
    ->eloquent($query)
    ->setRowId('id')
    ->addColumn('action', function($entity){
      return view('azienda.menu', ['entity' => $entity]);
    })
    ->rawColumns(['action']);
  }


  /**
  * Get query source of dataTable.
  *
  * @param \App\Azienda $model
  * @return \Illuminate\Database\Eloquent\Builder
  */
  public function query(Azienda $model)
  {
    $builder = $model->newQuery();

    return $builder;
  }

  /**
  * Optional method if you want to use html builder.
  *
  * @return \Yajra\DataTables\Html\Builder
  */
  public function html()
  {
    $buttons = [];
    array_push(
      $buttons,
      Button::make('create')
      ->editor('editor')
      ->className('btn btn-sm btn-primary')
      ->formTitle('Nuova azienda')
      ->formButtons([
        Button::raw('Annulla')
        ->className('btn btn-secondary ml-2')
        ->actionClose(),
        Button::raw('Salva')
        ->className('btn btn-success ml-2')
        ->actionHandler('create')
      ]
      )
      ->text('<i class="fas fa-plus"></i> Nuova azienda')
    );


    $builder = $this->builder()
    ->setTableId($this->dataTableVariable)
    ->columns($this->getColumns())
    ->language(asset('plugins/datatables/Italian.json'))
    ->dom(count($buttons)==0?'rtip':'Brtip')
    ->orderBy(1)
    ->buttons($buttons)
    ->editor(
      Editor::make()
      ->fields([
        Fields\Text::make('ragione_sociale', 'Ragione Sociale'),
        Fields\TextArea::make('intestazione', 'Intestazione'),
        Fields\Radio::make('is_attivo', 'Attivo?')
        ->options([['label' => 'Si', 'value' => 1], ['label' => 'No', 'value' => 0]])
        ->default(1),
        Fields\Radio::make('default', 'Azienda di default')
        ->options([['label' => 'Si', 'value' => 1], ['label' => 'No', 'value' => 0]])
        ->default(0),
        Fields\File::make('path_logo', 'Logo'),
        Fields\Text::make('redmine_url', 'Redmine Url'),
      ])
    );

    return $builder;
  }

  /**
  * Get columns.
  *
  * @return array
  */
  protected function getColumns()
  {
    return [
      Column::make('ragione_sociale')->title('Ragione Sociale'),
      Column::make('intestazione')->title('Intestazione'),
      Column::computed('action', '')
      ->exportable(false)
      ->printable(false)
      ->title(' ')
      ->addClass('text-right'),
    ];
  }

}
