<?php
/**
 * Order script for module builder modules
 * @author Rihards Silins <rihards.silins@mtcmedia.co.uk>
 * @version 1 16/12/2016
 * @copyright MTC media Ltd.
 */
$path = '{{{PATH_TO_ROOT}}}';
require_once $path.'core/includes/header.inc.php';
require_once '../includes/settings.php'; // MODEL SETTINGS

if (empty($_GET['rorder'])) {
    header("HTTP/1.0 400 Bad Request");
    exit();
}

if (!empty($_GET['relation_key']) && preg_match("/^[a-zA-Z_]+$/", $_GET['relation_key']) && isset($module['relations'][$_GET['relation_key']])) {
    $model_class_name = $module['relations'][$_GET['relation_key']]['class_name'];
} else {
    $model_class_name = MODEL_CLASS_NAMESPACE_PREFIX.MODEL_CLASS_NAME;
}

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

$module_list_order_array_key_thats_ordering_by_order = false;
$module_list_order_string = "";

$top_order_row_builder = $model_class_name::whereIn("id", $_GET['rorder']);
// apply order
if (!empty($module['list_order'])) {
    foreach ($module['list_order'] as $key => $order) {
        $top_order_row_builder = $top_order_row_builder->orderBy($order[0], $order[1]);
        if ($order[0] === "order") {
            $module_list_order_array_key_thats_ordering_by_order = $key;
        }
        $module_list_order_string = "'" .$order[0] . "' " . ($order[1] === "asc" ? "ascending" : "descending");
    }
}

if ($module_list_order_array_key_thats_ordering_by_order === false) {
    $error_message = "Can't order this list with drag and drop ordering. The " . ucwords(MODEL_PLURAL);
    $error_message .= " in this list are being ordered by " . $module_list_order_string;
    $error_message .= " and needs to be ordered by 'order' for the drag and drop ordering to work.";
    $_SESSION['model_form']['error'][] = $error_message;
    exit(json_encode([
        "result" => false,
        "message" => $error_message
    ]));
}

$top_order_row = $top_order_row_builder->first();

$order = $top_order_row->order;
for ($i=0; $i < count($new_order); $i++) {
    $row = $model_class_name::find($new_order[$i]);
    $row->order = $order;
    $row->save();
    if ($module['list_order'][$module_list_order_array_key_thats_ordering_by_order][1] === "asc") {
        ++$order;
    } else {
        --$order;
    }
}

exit(json_encode([
    "result" => true,
    "message" => "Success!"
]));
