<?php

namespace App\Livewire\Datatable\Manage;

use App\Models\Restock;
use App\Traits\Datatable\WithAppendColumn;
use App\Traits\Datatable\WithConfiguration;
use App\Traits\Datatable\WithPrependColumn;
use Illuminate\Database\Eloquent\Builder;
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;
use Rappasoft\LaravelLivewireTables\Views\Columns\ArrayColumn;

class RestocksTable extends DataTableComponent
{
    use WithAppendColumn, WithConfiguration, WithPrependColumn;

    protected $model = Restock::class;

    protected string $sortColumn = 'restock_date';

    protected string $sortDirection = 'desc';

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

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

            Column::make('Tanggal Restock', 'restock_date')
                ->format(fn ($value) => formatDateLocalized($value))
                ->searchable()
                ->sortable(),

            Column::make('Catatan', 'note')->searchable(),

            ArrayColumn::make('Item')
                ->data(
                    fn ($value, $row) => $row->items->map(fn ($item) => [
                        'name' => $item->restockable?->name,
                        'quantity' => formatCurrencyNumber($item->quantity, ''),
                    ])->toArray()
                )
                ->outputFormat(
                    fn ($index, $value) => "
                    <div class='text-[13px] leading-tight mb-1'>
                        <div class='font-bold text-gray-800 dark:text-white'>{$value['name']}</div>
                        <div class='text-gray-400 text-[12px]'>Qty: {$value['quantity']}</div>
                    </div>"
                )
                ->flexCol(['class' => 'flex-col gap-3']),

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

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

                    return $actions;
                })
                ->html()
                ->hideIf(auth()->user()->cannot('update restock')),
        ];
    }

    public function builder(): Builder
    {
        return Restock::select('restocks.id', 'warehouse_id', 'outlet_id', 'restock_date', 'note')
            ->with(['warehouse', 'outlet', 'items', 'items.restockable'])
            ->whereIn('outlet_id', auth()->user()->outlets->pluck('id')->toArray());
    }
}
