<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");

require_once "../config.php";

$json = file_get_contents("php://input");
$data = json_decode($json);

$username = $data->username;
$role = $data->role;
$name = $data->name;
$nameZh = $data->nameZh;
$email = $data->email;
$contact = $data->contact;
$dob_year = $data->dob_year;
$dob_month = $data->dob_month;
$dob_date = $data->dob_date;
$xingzuo = $data->xingzuo;
$password = $data->password;

$conn = connect_db();

$res = array();

if ($conn->connect_error) {
	die('Connection failed: ' . $conn->connect_error);
} else {
	$sql = "
		UPDATE `user`
		SET name = ?, nameZh = ?, email = ?, contact = ?, dob = ?, xingzuo = ? 
	";

	if ($password != "") {
		$sql .= ", password = ? ";
	}

	$sql .= "
		WHERE username = ?
		AND role = ?
	";

	if ($stmt = $conn->prepare($sql)) {
		if ($password != "") {
			$stmt->bind_param("sssssssss", $param_name, $param_name_zh, $param_email, $param_contact, $param_dob, $param_xingzuo, $param_password, $param_username, $param_role);
		} else {
			$stmt->bind_param("ssssssss", $param_name, $param_name_zh, $param_email, $param_contact, $param_dob, $param_xingzuo, $param_username, $param_role);
		}

		$param_name = $name;
		$param_name_zh = $nameZh;
		$param_email = $email;
		$param_contact = $contact;
		$param_dob = $dob_year . "-" . $dob_month . "-" . $dob_date;
		$param_xingzuo = $xingzuo;
		$param_password = md5(md5(AUTH_SECRET1 . $password . AUTH_SECRET2));
		$param_username = $username;
		$param_role = $role;

		if ($stmt->execute()) {
			$res["success"] = "Update Successful";
		} else {
			$res["failed"] = "Update Failed";
			$res["error"] = $stmt->error;
		}
	}
}

$conn->close();
echo json_encode($res);
