<?php

use Illuminate\Support\Facades\DB;
use Mtc\Shop\Category;

$path = "../../../";
require_once($path . "core/includes/header.inc.php");

if ($_REQUEST['action'] == "order") {

    $table_name = preg_replace('/[^a-z0-9_]/i', '', $_REQUEST['table']);
    $order_column = preg_replace('/[^a-z0-9_]/i', '', $_REQUEST['field']);
    $page_num = $_REQUEST['page_num'];
    $rows_per_page = $_REQUEST['rows_per_page'];
    $item_position = $_REQUEST['item_position'];
    $item_id = $_REQUEST['item_id'];

    if (isset($table_name, $order_column, $page_num, $rows_per_page, $item_position, $item_id)) {

        $query = DB::table($table_name);

        //ensure categories don't pull in sub cats when re ordering stuff
        if ($table_name == 'categories') {
            $category = Category::query()
                ->find($item_id);
            $query = $query->where('sub_id', $category->sub_id);
        }

        $records = $query->get()
            ->toArray();

        if ($query->count() === 0) {
            return;
        }

        //remove the element representing the item from the array
        if (($key = array_search($item_id, $records)) !== false) {
            unset($records[$key]);
        }

        //work out where the item should go in the array, ie the nth position
        $new_position = (($page_num - 1) * $rows_per_page) + $item_position;

        //split the order array up into a before and an after chunk
        $chunk_before_new_position = array_slice($records, 0, $new_position);
        $chunk_after_new_position = array_slice($records, $new_position);

        //stitch them back together with the moved item at the new position
        $records = array_merge($chunk_before_new_position, [$item_id], $chunk_after_new_position);

        foreach ($records as $position => $id) {
            DB::table($table_name)
                ->where('id', $id)
                ->update([$order_column => $position]);
        }
    }
}
