<?php

namespace App\Livewire\Admin\Menu;

use App\Models\Menu;
use App\Models\ServiceCategory;
use Illuminate\Support\Str;
use Livewire\Component;

class Create extends Component
{
    public $menu_category_id;

    public $title;

    public $url; // slug only

    public $redirect_url;

    public $position;

    public $categories = [];

    public function mount()
    {
        $this->categories = ServiceCategory::where('status', 1)
            ->orderBy('position')
            ->get();
    }

    // 🔥 AUTO SLUG FROM TITLE
    public function updatedTitle($value)
    {
        $this->url = Str::slug($value);
    }

    // 🔥 AUTO FIX WHEN USER TYPES WRONG SLUG
    public function updatedUrl($value)
    {
        $this->url = Str::slug($value);
    }

    public function addItem()
    {
        $this->validate([
            'menu_category_id' => 'required|exists:service_categories,id',
            'title' => 'required|string|max:255',
            'url' => [
                'required',
                'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/',
            ],
            'position' => 'required|integer|min:1', // ❗ NOW REQUIRED
        ], [
            'menu_category_id.required' => 'Please select a category',
            'title.required' => 'Page name is required',
            'url.required' => 'URL slug is required',
            'url.regex' => 'Only lowercase letters, numbers and hyphens allowed (e.g. brand-strategy)',
            'position.required' => 'Position is required',
        ]);

        $finalPosition = $this->position
            ?? (Menu::where('menu_category_id', $this->menu_category_id)->max('position') + 1);

        Menu::create([
            'menu_category_id' => $this->menu_category_id,
            'title' => $this->title,
            'slug' => $this->url,
            'url' => '/services/'.$this->url,
            'redirect_url' => $this->redirect_url ?: null,
            'position' => $finalPosition,
            'status' => 1,
        ]);

        session()->flash('success', 'Menu page added successfully');

        return redirect()->route('admin.menus.list');
    }

    public function render()
    {
        return view('livewire.admin.menus.create')
            ->layout('layouts.admin');
    }
}
