<?php

namespace App\Datatables\Admin\Shop;

use App\Datatables\ParentDataTable as DataTable;
use App\Models\Shop\Category;
use Yajra\DataTables\Html\Column;

class CategoriesDataTable extends DataTable
{
    public $model_name = 'categories';

    public function query(Category $model)
    {
        $model = $model::notRoot()->with(['tags.articles'])->withCount(['articles', 'tags']);

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

    public function modifier($datatables)
    {
        $datatables
            ->editColumn('name', function (Category $category) {
                return $category->name;
            })
            ->editColumn('visible', function (Category $category) {
                return view('components.form.toggle', [
                    'name' => 'visible',
                    'value' => $category->visible,
                    'on' => __('oui'),
                    'off' => __('non'),
                    'meta' => 'data-id='.$category->id,
                    'size' => 'sm',
                    'class' => 'visible',
                ]);
            })
            ->editColumn('homepage', function (Category $category) {
                return view('components.form.toggle', [
                    'name' => 'homepage',
                    'value' => $category->homepage,
                    'on' => __('oui'),
                    'off' => __('non'),
                    'meta' => 'data-id='.$category->id,
                    'size' => 'sm',
                    'class' => 'homepage',
                ]);
            })
            ->editColumn('articles_tagged_count', function (Category $category) {
                $count = 0;
                foreach ($category->tags as $tag) {
                    $nb = collect($tag->articles)->count();
                    $count += $nb;
                }

                return $count;
            })
            ->rawColumns(['visible', 'action']);

        return parent::modifier($datatables);
    }

    protected function getColumns()
    {
        return [
            Column::make('visible')->title('visible')->width(60),
            Column::make('homepage')->title('homepage')->width(60),
            Column::make('name')->title('Nom'),
            Column::make('articles_count')->title('#Art')->class('text-right')->orderable(false)->searchable(false)->width(60),
            Column::make('tags_count')->title('#Tags')->class('text-right')->searchable(false)->width(60),
            Column::make('articles_tagged_count')->title('#ArtTag')->class('text-right')->searchable(false)->orderable(false)->width(60),
            $this->makeColumnButtons(),
        ];
    }
}
