<?php

namespace App\Livewire\ExpenseCategories;

use App\Models\ExpenseCategory;
use Livewire\Component;
use Livewire\Attributes\Layout;

#[Layout('layouts.dashboard')]
class Edit extends Component
{
    public ExpenseCategory $category;

    // Form properties
    public string $name = '';
    public ?string $description = null;
    public int $status = ExpenseCategory::STATUS_ACTIVE;

    // UI properties
    public bool $loading = false;
    public bool $success = false;

    public function mount(ExpenseCategory $category): void
    {
        $this->category = $category;

        // Populate form
        $this->name = $category->name;
        $this->description = $category->description;
        $this->status = $category->status;
    }

    public function rules()
    {
        return [
            'name' => ['required', 'string', 'max:255', 'unique:expense_categories,name,' . $this->category->id],
            'description' => ['nullable', 'string', 'max:1000'],
            'status' => ['required', 'integer', 'in:0,1,2'],
        ];
    }

    public function save(): void
    {
        $this->resetErrorBag();
        $this->validate();

        $this->loading = true;

        try {
            $this->category->update([
                'name' => $this->name,
                'description' => $this->description,
                'status' => $this->status,
            ]);

            $this->success = true;

        } catch (\Throwable $e) {
            report($e);
            $this->addError('error', 'Une erreur est survenue lors de la modification de la catégorie.');
        } finally {
            $this->loading = false;
        }
    }

    public function render(): \Illuminate\Contracts\View\View
    {
        return view('livewire.expense-categories.edit');
    }
}
