<?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('Pegawai', 'user.employee.full_name')->searchable(),

            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 ($row->user_id == auth()->id() || auth()->user()->hasAnyRole(['Developer', 'Owner'])) {
                        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()
                ->hideIf(auth()->user()->cannot('update expense') && auth()->user()->cannot('delete expense') && auth()->id !== $row->user_id),
        ];
    }

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