<?php

namespace App\Livewire\Datatable\Studio\Manage;

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

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

    protected $model = Order::class;

    public function columns(): array
    {
        return [
            Column::make('Pegawai', 'user.employee.full_name')->searchable(),

            Column::make('Voucher', 'voucher.name')->searchable(),

            Column::make('Nomor Invoice')
                ->label(function ($row) {
                    return <<<HTML
                        <div>
                            <div>{$row->invoice_number}</div>
                            <span class="text-xs text-gray-400">{$row?->customer?->name}</span>
                        </div>
                    HTML;
                })
                ->searchable(function ($query, $searchTerm) {
                    $query->where('invoice_number', 'like', "%{$searchTerm}%")
                        ->orWhereHas('customer', function (Builder $query) use ($searchTerm) {
                            $query->where('name', 'like', "%{$searchTerm}%");
                        });
                })
                ->html(),

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

            Column::make('HPP', 'cogs')
                ->format(fn ($value) => currency($value, 'Rp'))
                ->searchable(),

            ArrayColumn::make('Item')
                ->data(
                    fn ($value, $row) => $row->items->map(fn ($item) => [
                        'name' => $item->orderable?->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('Ringkasan')
                ->label(function ($value) {
                    $subtotal = currency($value->subtotal, 'Rp');

                    $discount = currency($value->discount, 'Rp');

                    $total = currency($value->total, 'Rp');

                    return Blade::render('
                        <div class="mt-2 text-start space-y-1">
                            <div>
                                <flux:text>{{ $subtotal }}</flux:text>
                            </div>
                            <div>
                                <flux:text class="text-xs italic">-{{ $discount }}</flux:text>
                            </div>
                            <flux:separator class="my-2 !bg-black dark:!bg-white" />
                            <div class="text-lg font-bold">
                                <flux:heading>{{ $total }}</flux:heading>
                            </div>
                        </div>
                    ', ['value' => $value, 'subtotal' => $subtotal, 'discount' => $discount, 'total' => $total]);
                })
                ->html(),

            Column::make('Channel', 'channel')
                ->format(fn ($value) => Blade::render(
                    '<flux:badge color="'.$value->color().'">'
                        .$value->label()
                        .'</flux:badge>'
                ))
                ->html(),

            Column::make('Status', 'status')
                ->format(fn ($value) => Blade::render(
                    '<flux:badge color="'.$value->color().'">'
                        .$value->label()
                        .'</flux:badge>'
                ))
                ->html(),

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

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

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

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

    public function builder(): Builder
    {
        return Order::select('orders.id', 'orders.user_id', 'invoice_number', 'customer_id', 'orders.ordered_at', 'cogs', 'subtotal', 'discount', 'total', 'orders.status', 'channel', 'orders.voucher_id', 'orders.created_at')
            ->with(['user', 'user.employee', 'customer', 'voucher']);
    }
}
