<?php

namespace App\DataTables;

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

class AcademyDataTable extends DataTable
{
    public function dataTable($query)
    {
        return datatables()
            ->eloquent($query)
            ->addColumn('checkbox', fn (Academy $row) =>
                '<input type="checkbox" class="row-checkbox" value="' . $row->id . '">'
            )
            ->addColumn('name', function (Academy $row) {
                $link = route('admin.academies.show', $row->id);
                return '<a href="' . $link . '" class="fw-medium text-primary">' . e($row->name) . '</a>';
            })
            ->addColumn('is_active', fn (Academy $row) =>
                $row->is_active
                    ? '<span class="badge bg-success">' . __('dashboard.active') . '</span>'
                    : '<span class="badge bg-danger">' . __('dashboard.inactive') . '</span>'
            )
            ->addColumn('action', fn (Academy $row) =>
                view('admin.academies.partials.actions', ['row' => $row])->render()
            )
            ->rawColumns(['checkbox', 'name', 'is_active', 'action'])
            ->addIndexColumn();
    }

    public function query(Academy $model)
    {
        return $model->newQuery()->forIndex()->applyFilters();
    }

    public function html()
    {
        $data = $this->getExportData();
        return $this->builder()
            ->setTableId('academies-table')
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->ajax([
                'url'  => route('admin.academies.datatable'),
                'data' => dtFilters($data['exportFilters'] ?? []),
            ])
            ->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('is_active', __('dashboard.status'), true, false, true, true),
            computedCol('action', __('dashboard.actions')),
        ];
    }

    protected function filename(): string
    {
        return 'Academy_' . date('YmdHis');
    }

    private function getExportData(): array
    {
        return [
            'exportFilters' => [
                'period' => '.report',
                'is_active' => 'input[name="is_active"]',
                'orderBy' => '#orderBy-filter',
                'created_at:range' => '#range-date',
            ],
        ];
    }
}
