<?php

namespace App\Livewire\Datatable\Studio\Manage;

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

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(),

            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) => formatDateTime($value))
                ->searchable(),

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

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

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

                    return $actions;
                })
                ->html(),
        ];
    }

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