<?php

namespace App\Datatables\Botanic;

use App\Datatables\ParentDataTable as DataTable;
use App\Models\Botanic\Specie;
use App\Repositories\Botanic\Species;
use App\Repositories\Shop\Tags;
use Yajra\DataTables\Html\Column;

class SpeciesDataTable extends DataTable
{
    public $model_name = 'species';

    public function query(Specie $model)
    {
        $model = $model::withCount(['images', 'varieties', 'tags'])->with(['genre', 'image', 'tags']);

        return $this->buildQuery($model);
    }

    public function modifier($datatables)
    {
        $datatables
            ->editColumn('thumb', function (Specie $specie) {
                return Species::getThumb($specie->image, false);
            })
            ->editColumn('genre_name', function (Specie $specie) {
                return $specie->genre ? $specie->genre->name : '';
            })
            ->editColumn('tags2', function (Specie $specie) {
                $html = '';
                foreach ($specie->tags as $tag) {
                    $html .= Tags::getTagHtml($tag);
                }

                return $html;
            })
            ->rawColumns(['thumb', 'tags2', 'genre_name', 'action']);

        return parent::modifier($datatables);
    }

    protected function getColumns()
    {
        return [
            Column::make('name')->title('Nom'),
            Column::make('thumb')->title('')->searchable(false)->orderable(false)->width(40)->class('text-center'),
            Column::make('alias'),
            Column::make('genre.name')->data('genre_name')->title('Genre'),
            Column::make('latin'),
            Column::make('tags2')->title('Tags')->searchable(false)->orderable(false),
            Column::make('varieties_count')->title('#Var')->searchable(false)->addClass('text-right'),
            Column::make('tags_count')->title('#Tag')->searchable(false)->addClass('text-right'),
            Column::make('images_count')->title('#Pho')->searchable(false)->addClass('text-right'),
            $this->makeColumnButtons(),
        ];
    }
}
