<?php
$cms_root_path = "../../../";
require_once($cms_root_path."includes/compatibility_includer.php");
use Mtc\Cms\Models\PageListItemData as PageListItemData;
use Mtc\Cms\Models\PageListItem as PageListItem;
if ( sort_list_items_cms_pagedata($_POST) === true ) {
    die("true");
}
die("false");

function sort_list_items_cms_pagedata($data) {
    if ( !empty($data['page_id']) && is_numeric($data['page_id']) ) {
        $pli = PageListItem::where("page_list_id", $data['list_id'])
            ->orderBy("order")
            ->with("data")
            ->first();
        // if result doesn't match the count - js hasn't provided a valid new_order
        if ($pli->data->count() != count($data['new_order'])) {
            return false;
        }
        $order = 1;
        foreach ($data['new_order'] as $value) {
            $page_list_item_data = PageListItemData::find($value['id']);
            $page_list_item_data_list = PageListItemData::where("page_id", $data['page_id'])
                ->where("page_list_id", $data['list_id'])
                ->where("name", $page_list_item_data->name)
                ->get();
            foreach ($page_list_item_data_list as $page_list_item_data) {
                $page_list_item_data->order = $order;
                $page_list_item_data->save();
            }
            $order++;
        }
        return true;
    }
    return false;
}
