<?php
require_once __DIR__ . '/../app/bootstrap.php';
use App\Core\Auth;use App\Core\Database;use App\Core\Response;use App\Core\Security;
Auth::requireAdminModule('menus');
if($_SERVER['REQUEST_METHOD']!=='POST'||!verify_csrf())Response::json(['ok'=>false,'message'=>'Invalid request.'],419);
$data=request_data();$items=$data['items']??[];if(is_string($items))$items=json_decode($items,true)?:[];
if(!is_array($items)||count($items)>500)Response::json(['ok'=>false,'message'=>'Invalid menu payload.'],422);
Database::transaction(function()use($items){foreach($items as $index=>$item){if(!is_array($item))continue;$id=(int)($item['id']??0);$parentId=!empty($item['parent_id'])?(int)$item['parent_id']:null;if($id<1||$parentId===$id)continue;Database::execute('UPDATE menus SET sort_order=?,parent_id=? WHERE id=?',[(int)($item['sort_order']??$index),$parentId,$id]);}});
Security::logActivity(Auth::id(),'menu_order_updated',['items'=>count($items)]);
Response::json(['ok'=>true,'message'=>'Menu order saved.']);
