<?php

namespace App\Http\Controllers;

use App\Models\Menu;
use App\Models\AdminModels\Category;
use Illuminate\Http\Request;

class MenuController
{
    public function index()
    {
        // $menus = Menu::whereNull('parent_id')->with('children')->orderBy('order')->get();
        $menus = Category::whereNull('parent_id')->with('children')->orderBy('order')->get();
        return view('admin.menu-order', compact('menus'));
    }

    public function updateOrder(Request $request)
    {
        $data = $request->input('data');

        if (!is_array($data)) {
            return response()->json(['status' => 'failed', 'message' => 'Invalid input']);
        }
        $this->saveOrder($data);
        return response()->json(['status' => 'success']);
    }


    private function saveOrder(array $menus, $parentId = null)
    {
        foreach ($menus as $index => $menu) {
            Category::where('id', $menu['id'])->update([
                'order' => $index + 1,
                'parent_id' => $parentId,
            ]);

            if (!empty($menu['children'])) {
                $this->saveOrder($menu['children'], $menu['id']);
            }
        }

        return true; 
    }

}

