<?php

namespace App\Livewire\Studio\Manage\Order;

use App\Livewire\Forms\Studio\Manage\OrderForm;
use App\Models\Bottle;
use App\Models\Perfume;
use App\Models\Product;
use App\Traits\Order\WithAddItem;
use App\Traits\Order\WithCalculateTotal;
use App\Traits\Order\WithDiscount;
use App\Traits\Order\WithManageItem;
use App\Traits\Order\WithMember;
use App\Traits\Order\WithOrderItem;
use App\Traits\Order\WithUpdateItem;
use App\Traits\WithAuthorization;
use App\Traits\WithConfirmation;
use App\Traits\WithToast;
use App\Traits\WithUpdatedData;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Tambah Order')]
class Create extends Component
{
    use WithAddItem, WithAuthorization, WithCalculateTotal, WithConfirmation, WithDiscount, WithManageItem, WithMember, WithOrderItem, WithToast, WithUpdatedData, WithUpdateItem;

    public OrderForm $form;

    public array $outlets = [];

    public array $perfumes = [];

    public array $bottles = [];

    public array $qualities = [];

    public array $products = [];

    public string $subtotal = '';

    public string $total = '';

    public $items;

    public array $vouchers = [];

    public function mount()
    {
        $this->outlets = auth()->user()->outlets->pluck('name', 'id')->toArray();

        // Set default outlet if only one available
        if (count($this->outlets) === 1) {
            $this->form->outlet_id = key($this->outlets);
        }

        $this->perfumes = Perfume::orderBy('name')->pluck('name', 'id')->toArray();

        $this->bottles = Bottle::orderBy('size')->pluck('name', 'id')->toArray();

        $this->products = Product::orderBy('name')->pluck('name', 'id')->toArray();

        $this->items = $this->loadOrderItems();

        $this->subtotal = $this->getSubTotal();

        $this->total = $this->getTotal();
    }

    public function save()
    {
        $this->canOrAbort('create order');

        if ($this->items->isEmpty()) {
            $this->toast('Keranjang tidak boleh kosong.', 'Gagal', 'danger');

            return;
        }

        $result = $this->form->store();

        if (! $result['status']) {
            $this->toast($result['message'], 'Gagal', 'danger');

            return;
        }

        $this->dispatch('refreshDatatable');

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

        $this->redirectRoute('studio.manage.order.index', navigate: true);
    }

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