<?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\WithAuthorization;
use App\Traits\WithCloseModal;
use App\Traits\WithConfirmation;
use App\Traits\WithToast;
use App\Traits\WithUpdatedData;
use Flux\Flux;
use Livewire\Attributes\On;
use Livewire\Attributes\Title;
use Livewire\Component;

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

    public ExpenseForm $form;

    public array $outlets = [];

    public bool $userHasMultipleOutlets = false;

    public string $method = 'create';

    public string $modalTitle = '';

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

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

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

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

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

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

        $this->form->store();

        $this->dispatch('refreshDatatable');

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

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

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

        $this->form->update();

        $this->dispatch('refreshDatatable');

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

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

    public function delete(ExpenseModel $expense)
    {
        $expense->delete();

        $this->dispatch('refreshDatatable');

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

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

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