<?php

namespace App\DataTables\Admin;

use App\Models\Report;
use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Yajra\DataTables\Html\Builder as HtmlBuilder;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Services\DataTable;
use Yajra\DataTables\EloquentDataTable;

class ReportDataTable extends DataTable
{
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addIndexColumn()
            ->addColumn('user_name', function ($report) {
                if ($report->user) {
                    $first = $report->user->first_name ?? '';
                    $last = $report->user->last_name ?? '';
                } else {
                    $first = '';
                    $last = '';
                }
                return trim("$first $last") ?: '-';
            })
            ->addColumn('type_title', function ($report) {
                $type = class_basename($report->reportable_type ?? '');
                $title = $report->reportable->title ?? '—';
                return __('type') . ": $type<br>" . __('title') . ": $title";
            })
            ->addColumn('issues', function ($report) {
                $video = $report->video_issue ? __('video_issue') . ': ' . __($report->video_issue) : null;
                $audio = $report->audio_issue ? __('audio_issue') . ': ' . __($report->audio_issue) : null;
                $subtitle = $report->subtitle_issue ? __('subtitle_issue') . ': ' . __($report->subtitle_issue) : null;

                $issues = array_filter([$video, $audio, $subtitle]);

                return $issues ? implode('<br>', $issues) : '-';
            })
            ->addColumn('message', function ($report) {
                return \Str::limit($report->message ?? '-', limit: 100);
            })
            ->addColumn('option', function ($report) {
                return view('admin.reports.partials.action', compact('report'))->render();
            })
            ->rawColumns(['type_title', 'issues', 'option'])
            ->setRowId('id');
    }



    public function query(): QueryBuilder
    {
        return Report::with(['user', 'reportable'])
            ->when($this->request->search['value'] ?? false, function ($query) {
                $search = $this->request->search['value'];
                $query->where('reportable_type', 'like', "%$search%")
                    ->orWhereHas('reportable', function ($q) use ($search) {
                        $q->where('title', 'like', "%$search%");
                    })->orWhereHas('user', fn($q) => $q->where('first_name', 'like', "%$search%")->orWhere('last_name', 'like', "%$search%"))
                    ->orWhere('video_issue', 'like', "%$search%")
                    ->orWhere('audio_issue', 'like', "%$search%")
                    ->orWhere('subtitle_issue', 'like', "%$search%")
                    ->orWhere('message', 'like', "%$search%")
                ;
            })
            ->latest()
        ;
    }

    public function html(): HtmlBuilder
    {
        return $this->builder()
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->orderBy(1)
            ->selectStyleSingle()
            ->setTableAttribute('style', 'width:99.8%')
            ->footerCallback('function ( row, data, start, end, display ) {
                $(".dataTables_length select").addClass("form-select form-select-lg without_search mb-3");
                selectionFields();
            }')
            ->parameters([
                'dom' => 'Blfrtip',
                'buttons' => [
                    [], // Customize if needed
                ],
                'lengthMenu' => [[10, 25, 50, 100, 250], [10, 25, 50, 100, 250]],
                'language' => [
                    'searchPlaceholder' => __('search'),
                    'lengthMenu' => '_MENU_ ' . __('reports_per_page'),
                    'search' => '',
                ],
            ]);
    }

    public function getColumns(): array
    {
        return [
            Column::computed('id')->data('DT_RowIndex')->title('#')->searchable(false)->width(10),
            Column::computed('user_name')->title(__('user_name')),
            Column::computed('type_title')->title(__('type_title')),
            Column::computed('issues')->title(__('issues')),
            Column::computed('message')->title(__('message')),
            Column::computed('option')->title(__('Option')),
        ];
    }

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