<?php

use Livewire\Component;
use App\Models\Category;
use Illuminate\Support\Str;

return new class extends Component {
    public $name = '';
    public $slug = '';
    public $parent_id = null;

    public function render()
    {
        return $this->view()->layout('layouts::auth');
    }

    public function updatedName($value)
    {
        $this->slug = Str::slug($value);
    }

    public function save()
    {
        $this->validate([
            'name' => 'required|min:3',
            'slug' => 'required|unique:categories,slug',
            'parent_id' => 'nullable|exists:categories,id',
        ]);

        Category::create([
            'name' => $this->name,
            'slug' => $this->slug,
            'parent_id' => $this->parent_id ?: null,
        ]);

        $this->reset(['name', 'slug', 'parent_id']);
        session()->flash('message', 'Category created successfully.');
    }

    public function delete($id)
    {
        Category::find($id)->delete();
        session()->flash('message', 'Category deleted successfully.');
    }

    public function with()
    {
        return [
            'categories' => Category::with('parent')->orderBy('name')->get(),
            'parentCategories' => Category::whereNull('parent_id')->orderBy('name')->get(),
        ];
    }

    protected function view($data = [])
    {
        return app('view')->file('D:\02-my freelance\00-DR_Padhi\DR_PADHI\storage\framework/views/livewire/views/fa3aa45c.blade.php', $data);
    }
};
