<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
ob_start();
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("../functions.php");
$id_user = $_SESSION['id_user'];
session_write_close();
$id_map = (int)$_POST['id_map'];
switch(get_user_role($id_user)) {
    case 'administrator':
        $query = "SELECT * FROM sml_maps WHERE id=$id_map; ";
        break;
    case 'customer':
        $query = "SELECT * FROM sml_maps WHERE id_user=$id_user AND id=$id_map; ";
        break;
    case 'editor':
        $query = "SELECT * FROM sml_maps WHERE id=$id_map AND (SELECT COUNT(*) FROM sml_assign_maps WHERE id_map=$id_map AND id_user=$id_user LIMIT 1)=1; ";
        break;
}
$result = $mysqli->query($query);
if($result) {
    if($result->num_rows==0) {
        ob_end_clean();
        echo json_encode(array("status"=>"unauthorized"));
        exit;
    }
}
$map = get_map($id_map,$id_user);
$default_marker_size = $map['markers_size'];
$markers_icon = $map['markers_icon'];
$markers_id_icon_library = $map['markers_id_icon_library'];
$markers_color_hex = $map['markers_color_hex'];
if(empty($markers_color_hex)) $markers_color_hex = $map['main_color_hex'];
$markers_icon_color_hex = $map['markers_icon_color_hex'];
$markers_color_hex_hover = $map['markers_color_hex_hover'];
$markers_icon_color_hex_hover = $map['markers_icon_color_hex_hover'];
$name = strip_tags($_POST['name']);
$query_order = "SELECT (MAX(`order`)+1) as `order` FROM sml_markers WHERE id_map=$id_map;";
$result_order = $mysqli->query($query_order);
if($result_order) {
    $row_order = $result_order->fetch_array(MYSQLI_ASSOC);
    $order = $row_order['order'];
}
if(empty($order)) $order=0;
$query = "INSERT INTO sml_markers(id_map,name,marker_size,icon,id_icon_library,color_hex,icon_color_hex,color_hex_hover,icon_color_hex_hover,`order`) VALUES(?,?,?,?,?,?,?,?,?,?); ";
if ($smt = $mysqli->prepare($query)) {
    $smt->bind_param('isisissssi',$id_map,$name,$default_marker_size,$markers_icon,$markers_id_icon_library,$markers_color_hex,$markers_icon_color_hex,$markers_color_hex_hover,$markers_icon_color_hex_hover,$order);
    $result = $smt->execute();
    if ($result) {
        $insert_id = $mysqli->insert_id;
        ob_end_clean();
        echo json_encode(array("status"=>"ok","id"=>$insert_id));
    } else {
        ob_end_clean();
        echo json_encode(array("status"=>"error"));
    }
} else {
    ob_end_clean();
    echo json_encode(array("status"=>"error"));
}