<?php

namespace App\Livewire\Admin\Navigation\Menu;

use Livewire\Component;
use Illuminate\Support\Str;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Validate;
use App\Models\Admin\NavigationMenu;

class Create extends Component
{
    #[Validate('required|min:3|max:255|string')]
    public $name;

    #[Validate('required|min:3|max:255|string|unique:navigation_menus,slug')]
    public $slug;
    public $description;
    public $parent_id;

    #[Computed()]
    public function menus()
    {
        return NavigationMenu::get();
    }

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

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

        $navigationMenu = NavigationMenu::create([
            'parent_id' => $this->parent_id,
            'name' => $this->name,
            'slug' => $this->slug,
            'description' => $this->description,
        ]);

        activity()->performedOn($navigationMenu)->causedBy(auth()->id())->log('Menü oluşturuldu');

        $this->dispatch('showAlert', [
            'title' => 'Başarılı!', 'text' => 'Menü oluşturuldu.', 'icon' => 'success'
        ]);

        $this->reset();
    }

    public function saveAndRedirect(){
        $this->save();

        return redirect()->route('admin.navigation.menu.index');
    }

    public function render()
    {
        return view('livewire.admin.navigation.menu.create');
    }
}
