<?php

namespace App\Livewire\Datatable\Information;

use App\Enums\IsShow;
use App\Models\Testimonial;
use App\Traits\Datatable\WithConfiguration;
use App\Traits\Datatable\WithPrependColumn;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Str;
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;

class TestimonialsTable extends DataTableComponent
{
    use WithConfiguration, WithPrependColumn;

    protected $model = Testimonial::class;

    public function columns(): array
    {
        return [
            Column::make('Nama', 'user.customer.name')
                ->searchable(),

            Column::make('Konten', 'content')
                ->searchable()
                ->format(fn ($value) => Str::limit($value, 50)),

            Column::make('Rating', 'rating')
                ->sortable(),

            Column::make('Visibilitas', 'is_show')
                ->label(fn ($row, $column) => Blade::render('<flux:switch wire:change="toggleShow('.$row->id.')" :checked="$checked" />', ['checked' => $row->is_show === IsShow::SHOW]))
                ->html(),
        ];
    }

    public function toggleShow(Testimonial $testimonial): void
    {
        $testimonial->update([
            'is_show' => $testimonial->is_show === IsShow::SHOW ? IsShow::HIDDEN : IsShow::SHOW,
        ]);
    }

    public function builder(): Builder
    {
        return Testimonial::select('testimonials.id', 'rating', 'content', 'is_show', 'testimonials.created_at')->with(['user', 'user.customer']);
    }
}
