<?php

namespace App\Livewire\Datatable\Studio\Information;

use App\Models\Broadcast;
use App\Traits\Datatable\WithAppendColumn;
use App\Traits\Datatable\WithConfiguration;
use App\Traits\Datatable\WithPrependColumn;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Blade;
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;
use Rappasoft\LaravelLivewireTables\Views\Columns\ArrayColumn;

class BroadcastsTable extends DataTableComponent
{
    use WithAppendColumn, WithConfiguration, WithPrependColumn;

    protected $model = Broadcast::class;

    public function columns(): array
    {
        return [
            Column::make('Judul', 'title')->searchable(),

            Column::make('Body', 'body')->searchable(),

            ArrayColumn::make('Audiensi')
                ->data(
                    fn ($value, $row) => $row->audiences->map(fn ($audience) => [
                        'name' => $audience->name,
                    ])->toArray()
                )
                ->outputFormat(fn ($index, $value) => Blade::render('
                    <div class="flex items-center space-x-2 bg-gray-50 border border-gray-200 rounded-lg px-2 py-1 text-xs">
                        <span class="font-medium text-gray-700">{{ $value["name"] }}</span>
                    </div>', ['value' => $value]))
                ->flexRow(['class' => 'gap-2 flex-wrap']),

            Column::make('Tanggal')
                ->label(fn ($row, $column) => formatDateTime($row->created_at)),
        ];
    }

    public function builder(): Builder
    {
        return Broadcast::select('id', 'title', 'body')
            ->with('audiences');
    }
}
