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

$conn = connect_db();

$res = array();

if ($username == "") {
	$res["error"] = "Username is empty";
} else {	
	if ($conn->connect_error) {
		die("Connection failed: " . $conn->connect_error);
	} else {
		$sql = "
			SELECT * FROM `users`
			WHERE username = '" . $username . "'
			LIMIT 1
		";
		$result = $conn->query($sql);

		if ($result->num_rows > 0) {
			while ($row = $result->fetch_assoc()) {
				$res["error"] = "Username is existed";
			}
		} else {
			$res["success"] = "Username is valid";
		}
	}
}

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