<?php

namespace App\DataTables\Admin;

use App\Models\Review;
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 ReviewDataTable extends DataTable
{
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addIndexColumn()
            ->addColumn('user_name', function ($review) {
                $first = $review->user->first_name ?? '';
                $last = $review->user->last_name ?? '';
                return trim("$first $last") ?: '-';
            })
            ->addColumn('type_title', function ($review) {
                $type = class_basename($review->reviewable_type ?? '');
                $title = $review->reviewable->title ?? '—';
                return __('type') . ": $type<br>" . __('title') . ": $title";
            })
            ->addColumn('rating', function ($review) {
                return str_repeat('★', $review->rating ?? 0);
            })
            ->addColumn('review_reply', function ($review) {
                $reviewText = \Str::limit($review->review ?? '-', 50);
                $replyText = \Str::limit($review->reply ?? '-', 50);
                return __('review') . ": $reviewText<br>" . __('reply') . ": $replyText";
            })
            ->addColumn('option', function ($review) {
                return view('admin.reviews.partials.action', compact('review'))->render();
            })
            ->rawColumns(['type_title', 'review_reply', 'option'])
            ->setRowId('id');
    }



    public function query(): QueryBuilder
    {
        return Review::with(['user', 'reviewable'])
            ->when($this->request->search['value'] ?? false, function ($query) {
                $search = $this->request->search['value'];
                $query->where('reviewable_type', 'like', "%$search%")
                    ->orWhere('review', 'like', "%$search%")->orWhereHas('reviewable', 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('reply', '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_ ' . __('reviews_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('rating')->title(__('rating')),
            Column::computed('review_reply')->title(__('review_reply')),
            Column::computed('option')->title(__('Option')),
        ];
    }

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