<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SiteMenu;
use App\Models\Language;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class MenuManagementController extends Controller
{
    /**
     * Display a listing of the menus.
     */
    public function index(Request $request)
    {
        $languageCode = $request->get('lang', 'fa');
        $languages = Language::active()->get();
        
        $menus = SiteMenu::forLanguage($languageCode)
            ->with(['parent', 'children'])
            ->orderBy('sort_order')
            ->paginate(20);

        return view('admin.menu-management.index', compact('menus', 'languages', 'languageCode'));
    }

    /**
     * Show the form for creating a new menu.
     */
    public function create(Request $request)
    {
        $languageCode = $request->get('lang', 'fa');
        $languages = Language::active()->get();
        $parentMenus = SiteMenu::forLanguage($languageCode)->main()->active()->get();

        return view('admin.menu-management.create', compact('languages', 'languageCode', 'parentMenus'));
    }

    /**
     * Store a newly created menu in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:100',
            'url' => 'required|string|max:255',
            'icon' => 'nullable|string|max:50',
            'target' => 'required|in:_self,_blank',
            'parent_id' => 'nullable|exists:site_menus,id',
            'sort_order' => 'required|integer|min:0',
            'is_active' => 'boolean',
            'show_for_guests' => 'boolean',
            'show_for_users' => 'boolean',
            'language_code' => 'required|exists:languages,code',
        ]);

        SiteMenu::create($validated);

        // Clear menu cache
        Cache::forget('site_menus_' . $validated['language_code']);

        return redirect()->route('admin.menu-management.index', ['lang' => $validated['language_code']])
            ->with('success', 'منو با موفقیت ایجاد شد.');
    }

    /**
     * Display the specified menu.
     */
    public function show(SiteMenu $menu)
    {
        return view('admin.menu-management.show', compact('menu'));
    }

    /**
     * Show the form for editing the specified menu.
     */
    public function edit(SiteMenu $menu)
    {
        $languages = Language::active()->get();
        $parentMenus = SiteMenu::forLanguage($menu->language_code)
            ->main()
            ->active()
            ->where('id', '!=', $menu->id)
            ->get();

        return view('admin.menu-management.edit', compact('menu', 'languages', 'parentMenus'));
    }

    /**
     * Update the specified menu in storage.
     */
    public function update(Request $request, SiteMenu $menu)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:100',
            'url' => 'required|string|max:255',
            'icon' => 'nullable|string|max:50',
            'target' => 'required|in:_self,_blank',
            'parent_id' => 'nullable|exists:site_menus,id',
            'sort_order' => 'required|integer|min:0',
            'is_active' => 'boolean',
            'show_for_guests' => 'boolean',
            'show_for_users' => 'boolean',
            'language_code' => 'required|exists:languages,code',
        ]);

        // Prevent self-referencing parent
        if ($validated['parent_id'] == $menu->id) {
            return back()->withErrors(['parent_id' => 'منو نمی‌تواند والد خودش باشد.']);
        }

        $menu->update($validated);

        // Clear menu cache
        Cache::forget('site_menus_' . $validated['language_code']);

        return redirect()->route('admin.menu-management.index', ['lang' => $validated['language_code']])
            ->with('success', 'منو با موفقیت به‌روزرسانی شد.');
    }

    /**
     * Remove the specified menu from storage.
     */
    public function destroy(SiteMenu $menu)
    {
        $languageCode = $menu->language_code;
        
        // Delete children first
        $menu->children()->delete();
        $menu->delete();

        // Clear menu cache
        Cache::forget('site_menus_' . $languageCode);

        return redirect()->route('admin.menu-management.index', ['lang' => $languageCode])
            ->with('success', 'منو با موفقیت حذف شد.');
    }

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

        foreach ($validated['menus'] as $menuData) {
            SiteMenu::where('id', $menuData['id'])
                ->update(['sort_order' => $menuData['sort_order']]);
        }

        // Clear menu cache
        Cache::forget('site_menus_' . $validated['language_code']);

        return response()->json(['success' => true, 'message' => 'ترتیب منوها به‌روزرسانی شد.']);
    }

    /**
     * Toggle menu status via AJAX.
     */
    public function toggleStatus(SiteMenu $menu)
    {
        $menu->update(['is_active' => !$menu->is_active]);

        // Clear menu cache
        Cache::forget('site_menus_' . $menu->language_code);

        return response()->json([
            'success' => true,
            'status' => $menu->is_active,
            'message' => $menu->is_active ? 'منو فعال شد.' : 'منو غیرفعال شد.'
        ]);
    }
}
