<?php

namespace App\DataTables;

use App\Models\ChampionshipGroup;
use Yajra\DataTables\Services\DataTable;

class ChampionshipGroupDataTable extends DataTable
{
    public function dataTable($query)
    {
        return datatables()
            ->eloquent($query)
            ->addColumn('checkbox', fn (ChampionshipGroup $row) =>
                '<input type="checkbox" class="row-checkbox" value="' . $row->id . '">'
            )
            ->addColumn('name', function (ChampionshipGroup $row) {
                $link = route('admin.championship-groups.show', $row->id);
                return '<a href="' . $link . '" class="fw-medium text-primary">' . e($row->name) . '</a>';
            })
            ->addColumn('championship', fn (ChampionshipGroup $row) => e($row->championship?->name ?? '-'))
            ->addColumn('action', fn (ChampionshipGroup $row) =>
                view('admin.championship-groups.partials.actions', ['row' => $row])->render()
            )
            ->rawColumns(['checkbox', 'name', 'action'])
            ->addIndexColumn();
    }

    public function query(ChampionshipGroup $model)
    {
        return $model->newQuery()
            ->forIndex()
            ->with('championship')
            ->applyFilters();
    }

    public function html()
    {
        return $this->builder()
            ->setTableId('championship-groups-table')
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->ajax([
                'url' => route('admin.championship-groups.datatable'),
                'data' => dtFilters([
                    'period' => '.report',
                    'orderBy' => '#orderBy-filter',
                    'created_at:range' => '#range-date',
                ]),
            ])
            ->orderBy(1, 'desc')
            ->language([
                'url' => asset('/dashboard_assets/js/datatable/datatables/langs/' . app()->getLocale() . '.json'),
            ])
            ->scrollX(true)
            ->dom('Blfrtip')
            ->parameters([
                'select' => ['style' => 'multi', 'selector' => 'td:first-child'],
                'buttons' => dtButtons([]),
            ] + dtLength(10));
    }

    protected function getColumns(): array
    {
        return [
            computedCol('checkbox', '<input type="checkbox" id="check-all">', 'text-center checkbox-col', false, false, 8),
            addCol('name', __('dashboard.name'), true, true, true, true),
            addCol('championship', __('Championship'), true, false, true, true),
            computedCol('action', __('dashboard.actions')),
        ];
    }
}
