<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Category;
use Illuminate\Support\Facades\Auth;

class CategoryController extends Component
{
    public $categories;
    public $name = '';
    public $active = true;
    public $editMode = false;
    public $categoryId;

    protected function rules()
    {
        return [
            'name' => ['required', 'string', 'min:2', 'max:255'],
        ];
    }

    protected function messages()
    {
        return [
            'name.required' => 'Category name is required.',
            'name.min' => 'Category name must be at least 2 characters.',
            'name.max' => 'Category name cannot exceed 255 characters.',
        ];
    }

    public function mount()
    {
        $this->loadCategories();
    }

    public function loadCategories()
    {
        $this->categories = Category::orderBy('id', 'desc')->get();
    }

    public function resetForm()
    {
        $this->reset(['name', 'active', 'editMode', 'categoryId']);
        $this->active = true;
    }

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

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

        $this->loadCategories();
        $this->resetForm();

        $this->dispatch('closeModal');
        $this->dispatch('refreshTable');
        $this->dispatch('showSuccess', 'Category created successfully!');
    }

    public function edit($id)
    {
        $category = Category::findOrFail($id);
        
        $this->categoryId = $category->id;
        $this->name = $category->name;
        $this->active = $category->active;
        $this->editMode = true;
    }

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

        $category = Category::findOrFail($this->categoryId);
        $category->name = $this->name;
        $category->active = $this->active;
        $category->created_by = auth()->id();
        $category->save();
        $this->loadCategories();
        $this->resetForm();

        $this->dispatch('closeModal');
        $this->dispatch('refreshTable');
        $this->dispatch('showSuccess', 'Category updated successfully!');
    }

    public function delete($id)
    {
        $category = Category::findOrFail($id);
        $category->delete();

        $this->loadCategories();
        
        $this->dispatch('refreshTable');
        $this->dispatch('showSuccess', 'Category deleted successfully!');
    }

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