<?php

namespace App\DataTables;

use App\Models\Fattura;
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 FatturaDataTable extends DataTable
{
    public function __construct()
    {
        $this->dataTableVariable = 'dataTable_fattura';
    }
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder<Fattura> $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('action', function ($entity) {
                return view('fattura.menu', ['entity' => $entity]);
            })
            ->addColumn('data_fattura', function ($entity) {
                return $entity->data_fattura->format('d/m/Y');
            })
            ->addColumn('totale_imponibile', function ($entity) {
                return '€ '.number_format($entity->totale_imponibile, 2, ',', '.');
            })
            ->addColumn('totale_netto', function ($entity) {
                return '€ '.number_format($entity->totale_netto, 2, ',', '.');
            })
            ->addColumn('stato', function ($entity) {
                return view('fattura.stato', ['entity' => $entity]);
            })
            ->setRowId('id');
    }

    /**
     * Get the query source of dataTable.
     *
     * @return QueryBuilder<Fattura>
     */
    public function query(Fattura $model): QueryBuilder
    {
        return $model->newQuery();
    }

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        $buttons = [];
        if(Auth::user()->can('create-fattura') || Auth::user()->hasRole('superadmin')){
            array_push($buttons, Button::make('create')
                ->text('<i class="bx bx-plus"></i> Crea fattura')
                ->className('btn btn-primary')
                ->editor('editor')
                ->formTitle('Crea nuova fattura'));

                array_push($buttons, Button::raw('')
                ->text('<i class="bx bx-plus"></i> Genera fattura mensile')
                ->className('btn btn-primary')
                ->action('function () {
                    window.location.href = "'.route("fattura.need_fatturazione_mensile").'";
                }')
            );
        }
        return $this->builder()
                    ->setTableId($this->dataTableVariable)
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->orderBy(1)
                    ->pageLength(25)
                    ->lengthMenu([25, 50, 100, 200])
                    ->responsive(true)
                    ->language(asset('assets/Italian.json'))
                    ->dom('Bfrtipl')
                    ->editor(Editor::make())
                    ->selectStyleSingle()
                    ->buttons($buttons)
                    ->initComplete('function ($query) {
                        initComplete_fattura();
                    }');
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::make('id'),
            Column::make('numero_fattura'),
            Column::make('data_fattura'),
            Column::make('stato'),
            Column::make('note'),
            Column::make('path_pdf'),
            Column::make('path_xml'),
            Column::make('metadata'),
            Column::make('totale_imponibile'),
            Column::make('totale_netto'),
            Column::make('action')
                  ->exportable(false)
                  ->printable(false)
                  ->width(60)
                  ->addClass('text-center'),
        ];
    }

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