<?php

namespace App\Livewire\Modals;

use Livewire\Component;
use App\Models\Category;

class CategoryModal extends Component
{
    public $name = '';
    public $active = '';
    
    protected $rules = [
        'name' => 'required|string|max:255',
        'active' => 'required|in:0,1',
    ];

    protected $messages = [
        'name.required' => 'Please enter a category name',
        'active.required' => 'Please select a status',
    ];

    public function render()
    {
        return view('livewire.modals.category-modal');
    }

    public function add_category()
    {
        $this->validate();

        // Category::create([
        //     'name' => $this->name,
        //     'active' => $this->active,
        //     'created_by' => auth()->id(),
        // ]);
        $category = new Category();
        $category->name = $this->name;
        $category->active = $this->active;
        $category->created_by = auth()->id();
        $category->save();

        $this->reset(['name', 'active']);

        // Close modal
        $this->dispatch('closeModal');

        // Show success toast
        $this->dispatch('showSuccess', 'Category added successfully!');

        // Refresh table in parent component
        $this->dispatch('refreshTable');
    }

    public function resetForm()
    {
        $this->reset(['name', 'active']);
        $this->resetErrorBag();
    }
}