<?php

namespace App\Http\Controllers;

use App\Models\Language;
use App\Models\Menu;
use App\Models\MenuItem;
use App\Models\Page;
use Exception;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;

class MenuController extends Controller implements HasMiddleware
{

    public static function middleware(): array
    {
        return [
            new Middleware('CheckPermission:menuA', only: [ 'store']),
            new Middleware('CheckPermission:menuE', only: ['update','edit']),
            new Middleware('CheckPermission:menuD', only: ['destroy'])
        ];
    }
    
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        try {
            $menus = $menus = Menu::all();
            $languages = Language::where('status', 1)->get();



            $messages = [
                'errors' => $request->session()->get('errors'),
                'message' => $request->session()->get('message'),
                'success' => $request->session()->get('success'),
            ];

            return inertia('Menu/Index', [
                'menus' => $menus,
                'languages' => $languages,
                'messages' => $messages,
            ]);

        } catch (Exception $e) {
            return response()->json([
                'error' => 'An error occurred while fetching the menu items.',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try{
            $validated = $request->validate([
                'title' => 'required|string|max:255',
            ]);

            $menu = new Menu();
            $menu->title = $validated['title'];
            $menu->save();

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

            return redirect()->route('menus.index');
        }catch(Exception $e){
            return response()->json([
                'error' => 'An error occurred while creating the menu.',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        try{
            $menu = Menu::with('items')->findOrFail($id);
            $languages = Language::where('status', 1)->get();

            //dd($menu['items']->toArray());
            $pages = Page::where('status', 1)->get();

            return inertia('Menu/Update', [
                'menu' => $menu,
                'pages' => $pages,
                'languages' => $languages,
                'messages' => [
                    'errors' => session()->get('errors'),
                    'message' => session()->get('message'),
                    'success' => session()->get('success'),
                ],
            ]);

        }catch(Exception $e){

        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        try{
            $validated = $request->validate([
                'title' => 'required|string|max:255',
                'items' => 'array',
            ]);

            $menu = Menu::with('items')->findOrFail($id);
            $menu->title = $validated['title'];
            $menu->save();

           
            //dd($validated['items']);
            if (isset($menu->items)) {
                foreach ($menu->items as $item) {
                    $item->delete();
                }
            }


            // Update menu items if provided
            if (isset($validated['items'])) {
                
                foreach ($validated['items'] as $item) {
                    $menuItem = new MenuItem();
                    $menuItem->id = $item['id'];
                    $menuItem->order = $item['order'] ?? 0;
                    $menuItem->menu_id = $menu->id;
                    $menuItem->title = $item['title'];
                    $menuItem->link = $item['link'] ?? '';
                    $menuItem->parent_id = $item['parent_id'] ?? null;
                    $menuItem->page_id = $item['page_id'] ?? null;
                    $menuItem->type = $item['type'] ?? 'link';
                    $menuItem->save();
                }
            }

            session()->flash('success', 'Menu updated successfully!');

            return Inertia::location(route('menus.index'));
        }catch(Exception $e){
            return response()->json([
                'error' => 'An error occurred while updating the menu.',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        try{
            $menu = Menu::findOrFail($id);
            $menu->delete();

            session()->flash('success', 'Menu deleted successfully!');

            return Inertia::location(route('menus.index'));
        }catch(Exception $e){
            return response()->json([
                'error' => 'An error occurred while deleting the menu.',
                'message' => $e->getMessage()
            ], 500);
        }
    }
}
