<?php

namespace App\Livewire\Datatable\Studio\Finance;

use App\Models\Expense;
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 Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;

class ExpensesTable extends DataTableComponent
{
    use WithAppendColumn, WithConfiguration, WithMediaHandler, WithPrependColumn;

    protected $model = Expense::class;

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

            Column::make('Jumlah', 'amount')
                ->format(fn ($value) => currency($value, 'Rp'))
                ->searchable(),

            Column::make('Outlet', 'outlet.name')
                ->searchable(),

            Column::make('Tanggal', 'created_at')
                ->format(fn ($value) => formatDateTime($value))
                ->searchable(),

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

                    if (auth()->user()->can('update expense')) {
                        $actions .= view('components.datatables.edit-modal', [
                            'id' => $row->hash,
                            'method' => 'update',
                            'modalTitle' => 'Ubah Kategori',
                        ])->render();
                    }

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

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

    public function builder(): Builder
    {
        return Expense::select('expenses.id', 'description', 'amount', 'expenses.created_at')->with('outlet');
    }
}
