<?php

namespace App\Http\Controllers;

use App\Http\Requests\MenuRequest;
use App\Models\Menu;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class MenusController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return view('menus.index');
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $parent_menus = Menu::whereNull('parent_id')->get();
        return view("menus.create", compact('parent_menus'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(MenuRequest $request)
    {
        try{
            $validated_menu = $request->validated();
            DB::beginTransaction();
            Menu::create($validated_menu);
            DB::commit();
            return response()->json(['message' => 'Successfully created'], 200);
        }catch(\Exception $e){
            DB::rollBack();
            \Log::error('Menu creation failed: ' . $e->getMessage()); // Log the error for debugging
            return response()->json(['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)
    {
        $menu = Menu::findOrFail($id);
        $parent_menus = Menu::whereNull('parent_id')->where('id','!=',$id)->get();
        return view("menus.edit", compact('menu','parent_menus'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(MenuRequest $request, string $id)
    {
        try{
            $validate_menu = $request->validated();
            $menu = Menu::findOrFail($id);
            DB::beginTransaction();
            $menu->update($validate_menu);
            DB::commit();
            return response()->json(['message' => 'Successfully updated'], 200);
        }catch(\Exception $e){
            DB::rollBack();
            \Log::error('Menu update failed: '. $e->getMessage()); // Log the error for debugging
            return response()->json(['message' => $e->getMessage()],500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        try{
            DB::beginTransaction();
                $menu = Menu::findOrFail($id);
                $this->deleteChildren($menu);
                $menu->roles()->detach();
                $menu->delete();
            DB::commit();
            return response()->json(['success' => true, 'message' => 'Successfully deleted']);
        }catch(\Exception $e){
            DB::rollBack();
            \Log::error('failed delete menu'. $e->getMessage());
            return response()->json(['success' => false, 'message' => 'Something went wrong! Please try again.']);
        }
    }

    private function deleteChildren($menu)
    {
        foreach ($menu->children as $child) {
            $this->deleteChildren($child); // Recursively delete its children
            $child->roles()->detach(); // Detach roles before deleting
            $child->delete();
        }
    }
}
