<?php

namespace App\Livewire\Studio\Manage\Order;

use App\Models\Order;
use App\Traits\Authorization\WithAuthorization;
use App\Traits\Components\WithCloseModal;
use App\Traits\Components\WithConfirmation;
use App\Traits\Components\WithToast;
use App\Traits\Notification\WithSubscribeNotification;
use App\Traits\Order\WithUpdateStock;
use Flux\Flux;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\On;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Order')]
class Index extends Component
{
    use WithAuthorization, WithCloseModal, WithConfirmation, WithSubscribeNotification, WithToast, WithUpdateStock;

    public function mount(): void
    {
        if (request()->has('order')) {
            $order = Order::find(request('order'));

            if (! $order) {
                return;
            }

            $this->dispatch('fn:print', order: $order->hash);

            $this->js(<<<'JS'
                const url = new URL(window.location);
                url.search = '';
                window.history.replaceState({}, '', url);
            JS);
        }
    }

    public function delete(Order $order): void
    {
        $this->canOrAbort('delete order');

        foreach ($order->items as $item) {
            $this->increaseOutletStock($order->outlet, $item);
        }

        $order->delete();

        $this->dispatch('refreshDatatable');

        $this->toast('Order berhasil dihapus.');

        Flux::modals()->close();
    }

    #[On('fn:print')]
    public function print(Order $order): void
    {
        $order->load(['items', 'user', 'user.employee', 'outlet']);

        $this->dispatch(
            'open-print-modal',
            cashier: $order->user?->employee?->full_name ?? '',
            customer: $order->customer?->name ?? '',
            date: formatDateLocalized($order->created_at, 'd F Y H:i'),
            outlet_name: $order->outlet?->name ?? '',
            outlet_address: $order->outlet?->address ?? '',
            subtotal: $order->subtotal,
            discount: $order->discount,
            total: $order->total,
            items: $order->items->map(function ($item) {
                $item->name = $item->orderable?->name;
                $item->total = $item->unit_price * $item->quantity;
                $item->quality = $item->quality;

                return $item;
            })->toArray()
        );
    }

    public function render(): View
    {
        return view('livewire.studio.manage.order.index', [
            'pageTitle' => 'Order',
        ]);
    }
}
