<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Menu;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

class MenuController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $menus = Menu::with(['parent', 'children'])
            ->parents()
            ->orderBy('sort_order')
            ->get();
            
        return view('admin.menus.index', compact('menus'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $parentMenus = Menu::parents()->active()->orderBy('sort_order')->get();
        $availableRoutes = $this->getAvailableRoutes();
        
        return view('admin.menus.create', compact('parentMenus', 'availableRoutes'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'icon' => 'nullable|string|max:255',
            'route_name' => 'nullable|string|max:255',
            'url' => 'nullable|string|max:255',
            'parent_id' => 'nullable|exists:menus,id',
            'sort_order' => 'required|integer|min:0',
            'is_active' => 'boolean',
            'is_external' => 'boolean',
            'target' => 'required|in:_self,_blank',
            'description' => 'nullable|string'
        ]);

        // Set default values
        $validated['is_active'] = $request->has('is_active');
        $validated['is_external'] = $request->has('is_external');

        Menu::create($validated);

        return redirect()->route('admin.menus.index')
            ->with('success', 'Menu item created successfully.');
    }

    /**
     * Display the specified resource.
     */
    public function show(Menu $menu)
    {
        $menu->load(['parent', 'children']);
        return view('admin.menus.show', compact('menu'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Menu $menu)
    {
        $parentMenus = Menu::parents()
            ->active()
            ->where('id', '!=', $menu->id)
            ->orderBy('sort_order')
            ->get();
        $availableRoutes = $this->getAvailableRoutes();
        
        return view('admin.menus.edit', compact('menu', 'parentMenus', 'availableRoutes'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Menu $menu)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'icon' => 'nullable|string|max:255',
            'route_name' => 'nullable|string|max:255',
            'url' => 'nullable|string|max:255',
            'parent_id' => 'nullable|exists:menus,id',
            'sort_order' => 'required|integer|min:0',
            'is_active' => 'boolean',
            'is_external' => 'boolean',
            'target' => 'required|in:_self,_blank',
            'description' => 'nullable|string'
        ]);

        // Prevent setting parent to itself or its children
        if ($validated['parent_id'] && $this->wouldCreateCircularReference($menu, $validated['parent_id'])) {
            return back()->withErrors(['parent_id' => 'Cannot set parent to itself or its children.']);
        }

        // Set default values
        $validated['is_active'] = $request->has('is_active');
        $validated['is_external'] = $request->has('is_external');

        $menu->update($validated);

        return redirect()->route('admin.menus.index')
            ->with('success', 'Menu item updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Menu $menu)
    {
        // Check if menu has children
        if ($menu->children()->count() > 0) {
            return back()->withErrors(['error' => 'Cannot delete menu item that has children. Please delete or reassign children first.']);
        }

        $menu->delete();

        return redirect()->route('admin.menus.index')
            ->with('success', 'Menu item deleted successfully.');
    }

    /**
     * Get available routes for menu items
     */
    private function getAvailableRoutes()
    {
        $routes = [];
        $routeCollection = Route::getRoutes();
        
        foreach ($routeCollection as $route) {
            $name = $route->getName();
            if ($name && strpos($name, 'admin.') === 0) {
                $routes[$name] = $name;
            }
        }
        
        return $routes;
    }

    /**
     * Check if setting parent would create circular reference
     */
    private function wouldCreateCircularReference(Menu $menu, $parentId)
    {
        if ($menu->id == $parentId) {
            return true;
        }
        
        $parent = Menu::find($parentId);
        while ($parent) {
            if ($parent->id == $menu->id) {
                return true;
            }
            $parent = $parent->parent;
        }
        
        return false;
    }

    /**
     * Update menu order via AJAX
     */
    public function updateOrder(Request $request)
    {
        $request->validate([
            'items' => 'required|array',
            'items.*.id' => 'required|exists:menus,id',
            'items.*.sort_order' => 'required|integer|min:0'
        ]);

        foreach ($request->items as $item) {
            Menu::where('id', $item['id'])->update(['sort_order' => $item['sort_order']]);
        }

        return response()->json(['success' => true]);
    }
}
