<?php

namespace App\DataTables;

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

class CountryCitiesDataTable extends DataTable
{
    protected int $countryId;

    public function setCountryId(int $countryId): self
    {
        $this->countryId = $countryId;
        return $this;
    }

    public function dataTable($query)
    {
        return datatables()
            ->eloquent($query)

            ->addColumn('name', function(City $row) {
                $name = $row->getTranslation('name', app()->getLocale());
                $link = route('admin.cities.show', $row->id);
                return '<a href="' . $link . '" class="fw-medium text-primary">' . e($name) . '</a>';
            })

            ->addColumn('is_active', fn(City $row) =>
                $row->is_active
                    ? '<span class="badge bg-success">' . __('dashboard.active') . '</span>'
                    : '<span class="badge bg-danger">' . __('dashboard.inactive') . '</span>'
            )

            ->addColumn('created_at', fn(City $row) =>
                $row->created_at?->format('Y-m-d')
            )

            ->rawColumns([
                'name',
                'is_active',
            ])

            ->addIndexColumn();
    }

    public function query(City $model)
    {
        return $model->newQuery()
            ->where('country_id', $this->countryId)
            ->applyFilters();
    }

    public function html()
    {
        return $this->builder()
            ->setTableId('country-cities-table')
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->ajax([
                'url'  => route('admin.countries.cities.datatable', $this->countryId),
                'data' => dtFilters([
                    'period' => '.cities-report',
                    'is_active' => '.cities-status-filter',
                ])
            ])
            ->orderBy(1, 'desc')
            ->language([
                'url' => asset('/dashboard_assets/js/datatable/datatables/langs/' . app()->getLocale() . '.json'),
            ])
            ->scrollX(true)
            ->dom('Blfrtip')
            ->parameters(dtLength(10));
    }

    protected function getColumns(): array
    {
        return [
            addCol('name', __('dashboard.name'), true, true, true, true),
            addCol('is_active', __('dashboard.status'), true, false, true, true),
            addCol('created_at', __('dashboard.created_at'), true, false, true, true),
        ];
    }

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