<?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("../functions.php");
require_once("../../db/connection.php");
$id_user = $_POST['id_user'];
$name = strip_tags($_POST['name']);
$code = uniqid();
$settings = get_settings();
$id_map_template = $settings['id_map_template'];

if(!empty($id_map_template)) {
    $mysqli->query("CREATE TEMPORARY TABLE sml_maps_tmp SELECT * FROM sml_maps WHERE id = $id_map_template;");
    $now = date('Y-m-d H:i:s');
    $query="UPDATE sml_maps_tmp SET id=(SELECT MAX(id)+1 as id FROM sml_maps),active=1,id_user=?,name=?,code=?,date_created=?;";
    if($smt = $mysqli->prepare($query)) {
        $smt->bind_param('isss', $id_user,$name,$code,$now);
        $smt->execute();
    }
    $result = $mysqli->query("INSERT INTO sml_maps SELECT * FROM sml_maps_tmp;");
    if($result) {
        $insert_id = $mysqli->insert_id;
        $mysqli->query("DROP TEMPORARY TABLE IF EXISTS sml_maps_tmp;");
        $_SESSION['id_map_sel'] = $insert_id;
        $_SESSION['name_map_sel'] = $name;
        ob_end_clean();
        echo json_encode(array("status"=>"ok"));
    } else {
        ob_end_clean();
        echo json_encode(array("status"=>"error"));
    }
} else {
    $query = "INSERT INTO sml_maps(id_user,code,date_created,name) VALUES(?,?,?,?);";
    if($smt = $mysqli->prepare($query)) {
        $now = date('Y-m-d H:i:s');
        $smt->bind_param('isss',$id_user,$code,$now,$name);
        $result = $smt->execute();
        if($result) {
            $insert_id = $mysqli->insert_id;
            $_SESSION['id_map_sel'] = $insert_id;
            $_SESSION['name_map_sel'] = $name;
            ob_end_clean();
            echo json_encode(array("status"=>"ok"));
        } else {
            ob_end_clean();
            echo json_encode(array("status"=>"error"));
        }
    }
}