<?php

namespace App\Livewire\Studio\Manage\Order;

use App\Models\Order;
use App\Traits\Notification\WithSubscribeNotification;
use App\Traits\Order\WithUpdateStock;
use App\Traits\WithCloseModal;
use App\Traits\WithConfirmation;
use App\Traits\WithToast;
use Flux\Flux;
use Livewire\Attributes\On;
use Livewire\Attributes\Title;
use Livewire\Component;

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

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

            if (! $order) {
                return;
            }

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

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

    public function delete(Order $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)
    {
        $order->load(['items', 'user', 'user.employee']);

        $this->dispatch(
            'printReceipt',
            cashier: $order->user?->employee?->full_name ?? '',
            customer: $order->customer?->name ?? '',
            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;

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

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