<?php

namespace App\Livewire\Datatable\Studio\Manage;

use App\Models\Purchase;
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;
use Rappasoft\LaravelLivewireTables\Views\Columns\ArrayColumn;

class PurchasesTable extends DataTableComponent
{
    use WithConfiguration, WithMediaHandler, WithPrependColumn;

    protected $model = Purchase::class;

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

            Column::make('Nomor Invoice', 'invoice_number')->searchable(),

            Column::make('Tanggal Belanja', 'purchase_date')
                ->format(fn ($value) => formatDate($value))
                ->searchable()
                ->sortable(),

            Column::make('Total', 'total')
                ->format(fn ($value) => currency($value, 'Rp'))
                ->searchable()
                ->sortable(),

            ArrayColumn::make('Item')
                ->data(
                    fn ($value, $row) => $row->items->map(fn ($item) => [
                        'name' => $item->purchasable?->name,
                        'quantity' => currency($item->quantity, ''),
                        'unit_price' => currency($item->unit_price, 'Rp'),
                        'total_price' => currency($item->total_price, 'Rp'),
                    ])->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]'>{$value['quantity']} x {$value['unit_price']}</div>
                        <div class='text-gray-400 text-[12px]'>{$value['total_price']}</div>
                    </div>"
                )
                ->flexCol(['class' => 'flex-col gap-3']),

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

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

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

    public function builder(): Builder
    {
        return Purchase::select('purchases.id', 'invoice_number', 'purchase_date', 'total')->with('outlet');
    }
}
