<?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");
require_once("../functions.php");
$id_user = $_SESSION['id_user'];
if(get_user_role($id_user)!='administrator') {
    ob_end_clean();
    echo json_encode(array("status"=>"error"));
    exit;
}

$username = strip_tags($_POST['username']);
$email = trim(strip_tags($_POST['email']));
if($email==='') $email = null;
$password = strip_tags($_POST['password']);
$role = $_POST['role'];
$key_enc = PASSWORDS_ENCRYPT_KEY;
if(!sml_is_valid_user_role($role) || empty($username) || empty($password) || ($email!==null && (!filter_var($email,FILTER_VALIDATE_EMAIL) || strlen($email)>191)) || sml_username_exists($username) || sml_email_exists($email)) {
    ob_end_clean();
    echo json_encode(array("status"=>"error"));
    exit;
}

$query = "INSERT INTO sml_users(username,email,password,role) VALUES(?,?,AES_ENCRYPT(?, ?),?); ";
if($smt = $mysqli->prepare($query)) {
    $smt->bind_param('sssss',$username,$email,$password,$key_enc,$role);
    $result = $smt->execute();
    if($result) {
        echo json_encode(array("status"=>"ok"));
    } else {
        echo json_encode(array("status"=>"error"));
    }
}
