<?php

$cms_root_path = "../../../";
require_once($cms_root_path."includes/compatibility_includer.php");

$page = new Page();
if ( isset($_GET['page_id']) && is_numeric($_GET['page_id']) ) {
	$page->Get($_GET['page_id']);
} else {
	die("false");
}

$new_order = [];
for ($i=0; $i < count($_GET['rorder']); $i++) {
	if ( !empty($_GET['rorder'][$i]) && is_numeric($_GET['rorder'][$i]) ) {

		$new_order = $_GET['rorder'][$i];
	}
}

$lowest_order_page = null;

$lowest_order_page = \Mtc\Cms\Models\Page::query()
    ->whereIn('id', $new_order)
    ->where('sub_id', $page->id)
    ->orderBy('order')
    ->first();

$order = $lowest_order_page->order;

for ($i=0; $i < count($new_order); $i++) {
    \Mtc\Cms\Models\Page::query()
        ->where('id', $new_order[$i])
        ->update([
            'order' => $order,
            'sub_id' => $page->id,
        ]);
	$order++;
}
// rebuild listing cache if relevant
\Mtc\Cms\Handlers\ListingCacheHandler::triggerAsyncRefresh($page);
