<?php

namespace App\DataTables;

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

class BannerDataTable extends DataTable
{
    public function dataTable($query)
    {
        return datatables()
            ->eloquent($query)
            ->addColumn('checkbox', fn (Banner $row) =>
                '<input type="checkbox" class="row-checkbox" value="' . $row->id . '">'
            )
            ->addColumn('name', function (Banner $row) {
                $link = route('admin.banners.show', $row->id);
                return '<a href="' . $link . '" class="fw-medium text-primary">' . e($row->name) . '</a>';
            })
            ->addColumn('image', function (Banner $row) {
                if ($row->image) {
                    return '<img src="' . asset('storage/' . $row->image) . '" alt="" class="rounded" style="max-width: 60px; max-height: 40px; object-fit: cover;">';
                }
                return '-';
            })
            ->addColumn('button_text', fn (Banner $row) => e($row->button_text ?? '-'))
            ->addColumn('link_target', function (Banner $row) {
                if (! $row->linkable_type || ! $row->linkable_id) {
                    return '<span class="text-muted">—</span>';
                }
                $kind = Banner::adminLabelForLinkableType($row->linkable_type) ?? class_basename((string) $row->linkable_type);
                $title = $row->linkableTitle() ?? ('#' . $row->linkable_id);
                $url = $row->adminLinkTargetUrl();
                if ($url) {
                    return '<a href="' . e($url) . '" class="text-primary">' . e($kind) . ' — ' . e($title) . '</a>';
                }

                return e($kind) . ' — ' . e($title);
            })
            ->addColumn('is_active', fn (Banner $row) =>
                $row->is_active
                    ? '<span class="badge bg-success">' . __('dashboard.active') . '</span>'
                    : '<span class="badge bg-danger">' . __('dashboard.inactive') . '</span>'
            )
            ->addColumn('action', fn (Banner $row) =>
                view('admin.banners.partials.actions', ['row' => $row])->render()
            )
            ->rawColumns(['checkbox', 'name', 'image', 'link_target', 'is_active', 'action'])
            ->addIndexColumn();
    }

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

    public function html()
    {
        $data = $this->getExportData();
        return $this->builder()
            ->setTableId('banners-table')
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->ajax([
                'url'  => route('admin.banners.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('image', __('dashboard.image'), true, false, false, false),
            addCol('button_text', __('dashboard.button_text'), true, false, true, true),
            computedCol('link_target', __('dashboard.banner_link_target'), 'text-start', false, false, 12),
            addCol('is_active', __('dashboard.status'), true, false, true, true),
            computedCol('action', __('dashboard.actions')),
        ];
    }

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

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