<?php
// required headers
header("Access-Control-Allow-Origin: *");
//header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
session_start();
include_once '../config/database.php';
include_once '../objects/user.php';

$database = new Database();
$db = $database->getConnection();

$user = new User($db);
$data = json_decode(file_get_contents("php://input"));

// $user->form_state = $_POST['txtFormState'];
$user->username = $_POST['txtUserName'];
$user->userrole = $_POST['cboUserRole'];
$user->city = $_POST['cboCity'];
$user->accounting_view = $_POST['cboAccFullView'];

if($_POST['formState'] == "Create"){
	$user->password = $_POST['txtPassword'];
}

$targetPath = "";
$img = $_FILES['file'];
if(!empty($_FILES['file']))
{
	$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
	if($ext==""){
		if($_POST['formState'] == "Create"){
			$targetPath = "/upload/dummy_user.png";
		}
	}else{
		$newname = date("Y-m-d H-i-s") .  "." . $ext;
		$targetPath = './upload/' . $newname;
		move_uploaded_file($_FILES['file']['tmp_name'],$targetPath);
	}
	$user->profilepicture = $targetPath;	
}

if($_POST['formState'] == "Create"){
	if($user->exist2()){
		echo 'duplicate';
	}else if($user->create()){
		echo 'created';
	}else{
		echo 'error1';
	}
}else{
	if($user->edit()){
		echo 'updated';
	}else{
		echo 'error2';
	}
}


?>