<?php

namespace App\Livewire\Datatable\Finance;

use App\Models\Expense;
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 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('Pegawai', 'user.employee.full_name')->searchable(),

            Column::make('Keterangan', 'description')->searchable(),

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

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

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

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

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

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

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

        ];
    }

    public function builder(): Builder
    {
        return Expense::select('expenses.id', 'expenses.user_id', 'expenses.outlet_id', 'expenses.description', 'expenses.amount', 'expenses.created_at')
            ->whereIn('outlet_id', auth()->user()->outlets->pluck('id')->toArray())
            ->with(['outlet', 'user', 'user.employee']);
    }
}
