<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
session_start();
if((($_SERVER['SERVER_ADDR']==$_SESSION['demo_server_ip']) && ($_SERVER['REMOTE_ADDR']!=$_SESSION['demo_developer_ip']) && ($_SESSION['id_user']==$_SESSION['demo_user_id'])) || ($_SESSION['sml_si']!=session_id())) {
    //DEMO CHECK
    die();
}
require_once("../../db/connection.php");
require_once("../../config/config.inc.php");

$id_map = $_POST['id_map'];
$id_category = $_POST['id_category'];
$direction = $_POST['direction'];

$index_category = 0;
$index_category_sel = 0;
$array_order = array();
$query = "SELECT c.id,IF(cc.name IS NULL,c.name,CONCAT(cc.name,' - ',c.name)) as category
FROM sml_categories as c
LEFT JOIN sml_categories as cc ON c.id_category_parent=cc.id
WHERE c.id_map=$id_map
ORDER BY c.`order` ASC, category ASC;";
$result = $mysqli->query($query);
if($result) {
    if($result->num_rows>0) {
        while($row = $result->fetch_array(MYSQLI_ASSOC)) {
            $id = $row['id'];
            $order = $row['order'];
            if($id_category==$id) $index_category_sel = $index_category;
            array_push($array_order,$id);
            $index_category++;
        }
    }
}

switch ($direction) {
    case 'down':
        $next_index = $index_category_sel+1;
        if($next_index>=count($array_order)) {
            $next_index = 0;
        }
        array_move($array_order,$index_category_sel,$next_index);
        break;
    case 'up':
        $prev_index = $index_category_sel-1;
        if($prev_index<0) {
            $prev_index = count($array_order)-1;
        }
        array_move($array_order,$index_category_sel,$prev_index);
        break;
}

foreach ($array_order as $order=>$id_category) {
    $mysqli->query("UPDATE sml_categories SET `order`=$order WHERE id=$id_category;");
}

function array_move(&$a, $oldpos, $newpos) {
    if ($oldpos==$newpos) {return;}
    array_splice($a,max($newpos,0),0,array_splice($a,max($oldpos,0),1));
}