<?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");

include_once '../config/database.php';
include_once '../objects/user.php';
session_start();

$database = new Database();
$db = $database->getConnection();
 
$user = new User($db);
$data = json_decode(file_get_contents("php://input"));

$user->id = $_SESSION['userid'];
$user->username = $_SESSION['user'];

$targetPath = "";
$img = $_FILES['file'];
if(!empty($_FILES['file']))
{
	$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
	if($ext!=""){
		$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['txtCurrentPassword'] && $_POST['txtNewPassword']){
	$user->password = $_POST['txtNewPassword'];
	$user->currentpassword = $_POST['txtCurrentPassword'];

	if($user->exist3()){
		if($user->updateProfile()){
		    echo 'updated';
		}else{
		    echo 'error';
		}
	}else{
		echo 'not exist';
	}
}else{
	if($targetPath){
		if($user->updateProfile()){
		    echo 'updated';
		}else{
		    echo 'error';
		}
	}
}
?>