<?php

namespace App\Livewire\Studio\Finance;

use App\Livewire\Forms\Studio\Finance\ExpenseForm;
use App\Models\Expense as ExpenseModel;
use App\Models\Outlet;
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\Utilities\WithUpdatedData;
use Flux\Flux;
use Illuminate\View\View;
use Livewire\Attributes\On;
use Livewire\Attributes\Title;
use Livewire\Component;
use Livewire\WithFileUploads;

#[Title('Pengeluaran')]
class Expense extends Component
{
    use WithAuthorization, WithCloseModal, WithConfirmation, WithFileUploads, WithSubscribeNotification, WithToast, WithUpdatedData;

    public ExpenseForm $form;

    public array $outlets = [];

    public bool $userHasMultipleOutlets = false;

    public string $method = 'create';

    public string $modalTitle = '';

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

        $this->userHasMultipleOutlets = auth()->user()->outlets()->count() > 1;
    }

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

        $this->form->store();

        $this->dispatch('refreshDatatable');

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

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

    public function update(): void
    {
        $this->canOrAbort('update expense');

        $this->form->update();

        $this->dispatch('refreshDatatable');

        $this->toast('Pengeluaran berhasil diperbarui.');

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

    public function delete(ExpenseModel $expense): void
    {
        $this->canOrAbort('delete expense');

        $expense->delete();

        $this->dispatch('refreshDatatable');

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

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

    #[On('modal:open')]
    public function openModal(string $method, string $modalTitle, ?string $id = null): void
    {
        $this->resetValidation();
        $this->resetErrorBag();

        $this->method = $method;
        $this->modalTitle = $modalTitle;

        $id && $this->form->setExpense(ExpenseModel::byHashOrFail($id));
    }

    public function render(): View
    {
        return view('livewire.studio.finance.expenses', [
            'pageTitle' => 'Pengeluaran',
        ]);
    }
}
