<?php

namespace App\Livewire\Studio\Manage\Purchase;

use App\Livewire\Forms\Studio\Manage\PurchaseForm;
use App\Models\Bottle;
use App\Models\Perfume;
use App\Models\Product;
use App\Models\Warehouse as WarehouseModel;
use App\Traits\Authorization\WithAuthorization;
use App\Traits\Components\WithConfirmation;
use App\Traits\Components\WithToast;
use App\Traits\Purchase\WithAddItem;
use App\Traits\Purchase\WithCalculateTotal;
use App\Traits\Purchase\WithDeleteItem;
use App\Traits\Purchase\WithPurchaseItems;
use App\Traits\Purchase\WithUpdateItem;
use App\Traits\Utilities\WithUpdatedData;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Tambah Belanja')]
class Create extends Component
{
    use WithAddItem, WithAuthorization, WithCalculateTotal, WithConfirmation, WithDeleteItem, WithPurchaseItems, WithToast, WithUpdatedData, WithUpdateItem;

    public PurchaseForm $form;

    public array $warehouses = [];

    public array $perfumes = [];

    public array $products = [];

    public array $bottles = [];

    public $purchaseItems;

    public function mount(): void
    {
        $this->warehouses = WarehouseModel::orderBy('name')->pluck('name', 'id')->toArray();

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

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

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

        $this->purchaseItems = $this->loadPurchaseItems();

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

    public function save(): void
    {
        $this->canOrAbort('create purchase');

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

            return;
        }

        $this->form->store();

        $this->redirectRoute('studio.manage.purchase.index', [
            'notification' => 'Belanja berhasil ditambahkan.',
        ], navigate: true);
    }

    public function render(): View
    {
        return view('livewire.studio.manage.purchase.form', [
            'pageTitle' => 'Tambah Belanja',
        ]);
    }
}
