<?php

namespace App\DataTables;

use App\Models\ContenutoBacheca;
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;
use Illuminate\Support\Facades\Storage;

class ContenutoBachecaDataTable extends DataTable
{
    public function __construct()
    {
        $this->dataTableVariable = 'dataTable_contenuto_bacheca';
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<ContenutoBacheca> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function($query){
                return view('contenuto_bacheca.menu', ['entity' => $query]);
            })
            ->addColumn('immagine', function($query){
                return '<img src="'.Storage::disk('contenuti_bacheca')->url($query->immagine).'" alt="Immagine" class="img-fluid rounded-5 w-50">';
            })
            ->rawColumns(['immagine'])
            ->setRowId('id');
    }

    /**
     * Get the query source of dataTable.
     *
     * @return QueryBuilder<ContenutoBacheca>
     */
    public function query(ContenutoBacheca $model): QueryBuilder
    {
        $model = $model->newQuery()->where('attivita_id', $this->attivita_id);
        if($this->bacheca_id){
            return $model->join('bacheca_has_contenuto', 'contenuto_bacheca.id', '=', 'bacheca_has_contenuto.contenuto_id')->where('bacheca_has_contenuto.bacheca_id', $this->bacheca_id);
        }
        return $model;
    }

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        $buttons = [];
        if(Auth::user()->can('create-contenuto_bacheca')){
            array_push($buttons, Button::make('create')
                ->editor('editor')
                ->className('btn btn-sm btn-primary mb-4')
                ->formTitle('Crea nuovo contenuto bacheca')
                ->text('<i class="fas fa-plus"></i> Nuovo contenuto bacheca'));
        }
        return $this->builder()
                    ->setTableId($this->dataTableVariable)
                    ->columns($this->getColumns())
                    ->language(asset('assets/Italian.json'))
                    ->dom(count($buttons) == 0 ? 'rtip' : 'Bfrtip')
                    ->buttons($buttons)
                    ->ajax(route('contenuto-bacheca.index'))
                    ->initComplete("function(settings, json){
                        initComplete_contenuto_bacheca();
                    }")
                    ->editor(
                        Editor::make()
                            ->fields([
                                Fields\Hidden::make('attivita_id')->label('Attività')
                                ->default($this->attivita_id?? Session::get('attivita_attuale')),
                                Fields\Text::make('nome')->label('Nome'),
                                Fields\Text::make('descrizione')->label('Descrizione'),
                                Fields\File::make('immagine')->label('Immagine'),
                            ])
                    );
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::make('id')->visible(false),
            Column::make('immagine')->title('Immagine'),
            Column::make('nome')->title('Nome'),
            Column::make('descrizione')->title('Descrizione'),
            Column::computed('action')
                  ->title('')
                  ->exportable(false)
                  ->printable(false)
                  ->width(60)
                  ->addClass('text-center'),
        ];
    }

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