<?php

namespace App\Livewire\Studio\Manage\Purchase;

use App\Models\Purchase;
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\Purchase\WithUpdateStock;
use App\Traits\Utilities\WithRequestNotification;
use Flux\Flux;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\Title;
use Livewire\Component;

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

    public function delete(Purchase $purchase): void
    {
        $this->canOrAbort('delete purchase');

        DB::transaction(function () use ($purchase) {
            foreach ($purchase->items as $item) {
                $this->decreaseWarehouseStock($purchase->warehouse, $item);
            }

            $purchase->delete();
        });

        $this->dispatch('refreshDatatable');

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

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

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