<?php

namespace App\Livewire\Datatable\Manage;

use App\Models\StockOpname;
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 StockOpnameTable extends DataTableComponent
{
    use WithAppendColumn, WithConfiguration, WithMediaHandler, WithPrependColumn;

    protected $model = StockOpname::class;

    public function columns(): array
    {
        return [
            Column::make('Outlet', 'outlet.name')->searchable(),

            Column::make('Periode Bulan', 'period_month')
                ->format(fn ($row) => formatDateLocalized($row, 'F Y'))
                ->searchable()
                ->sortable(),

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

                    if (auth()->user()->can('show stock opname')) {
                        $actions .= view('components.actions.table.new-page-action', [
                            'label' => 'Lihat',
                            'route' => route('studio.manage.stock_opname.show', ['stockOpname', $row->hash]),
                            'buttonColor' => 'blue',
                            'buttonIcon' => 'eye',
                        ])->render();
                    }

                    return $actions;
                })
                ->html()
                ->hideIf(auth()->user()->cannot('show stock opname')),
        ];
    }

    public function builder(): Builder
    {
        return StockOpname::select('stock_opname.id', 'outlet_id', 'period_month')
            ->where('period_month', '!=', now()->format('Y-m'))
            ->with('outlet')
            ->whereIn('outlet_id', auth()->user()->outlets->pluck('id')->toArray());
    }
}
