<?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\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\WithAuthorization;
use App\Traits\WithConfirmation;
use App\Traits\WithToast;
use App\Traits\WithUpdatedData;
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 $outlets = [];

    public array $perfumes = [];

    public array $products = [];

    public array $bottles = [];

    public $purchaseItems;

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

        $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->purchaseItems = $this->loadPurchaseItems();

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

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

            return;
        }

        $this->canOrAbort('create purchase');

        $this->form->store();

        $this->dispatch('refreshDatatable');

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

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

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