<?php

namespace App\Livewire\Datatable\Manage;

use App\Models\Article;
use App\Traits\Datatable\WithAppendColumn;
use App\Traits\Datatable\WithConfiguration;
use App\Traits\Datatable\WithPrependColumn;
use App\Traits\Media\WithMediaHandler;
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 ArticlesTable extends DataTableComponent
{
    use WithAppendColumn, WithConfiguration, WithMediaHandler, WithPrependColumn;

    protected $model = Article::class;

    public function columns(): array
    {
        return [
            Column::make('Penulis', 'author.employee.full_name')->searchable(),

            Column::make('Judul', 'title')->searchable(),

            ArrayColumn::make('Kategori')
                ->data(fn ($value, $row) => $row->categories->pluck('name')->toArray())
                ->outputFormat(fn ($index, $value) => Blade::render('<span class="text-xs text-gray-400 border border-gray-400 rounded px-1">'.$value.'</span>'))
                ->flexRow(['class' => 'gap-2 flex-wrap']),

            Column::make('Status', 'status')
                ->format(
                    fn ($value) => Blade::render('<flux:badge color="'.$value->color().'">'.$value->label().'</flux:badge>')
                )
                ->html(),

            Column::make('Waktu Publish', 'published_at')
                ->format(fn ($value) => formatDateTimeLocalized($value))
                ->searchable(),

            Column::make('Dilihat', 'views')
                ->format(fn ($value) => formatCurrencyNumber($value))
                ->searchable()
                ->sortable(),

            Column::make('Aksi')
                ->label(function ($row) {
                    $actions = '';

                    if (auth()->user()->can('update article')) {
                        $actions .= view('components.actions.table.edit', [
                            'id' => $row->hash,
                            'editRoute' => route('studio.manage.article.edit', $row->hash),
                        ])->render();
                    }

                    if (auth()->user()->can('delete article')) {
                        $actions .= view('components.actions.table.delete', [
                            'id' => $row->hash,
                        ])->render();
                    }

                    return $actions;
                })
                ->html()
                ->hideIf(auth()->user()->cannot('update article') && auth()->user()->cannot('delete article')),
        ];
    }

    public function builder(): Builder
    {
        return Article::select('articles.id', 'author_id', 'title', 'articles.status', 'published_at', 'views')->with(['author', 'author.employee', 'categories']);
    }
}
