<?php
header("Access-Control-Allow-Origin: *");
include 'conexion.php';

$getJson = file_get_contents('php://input');
$json = json_decode($getJson);

$email = $json->email;
$phone = $json->phone;
$pass = $json->password;
$user = strstr($email, ".", true);
$user = str_replace("@", "", $user);

$userCheck = $connect->query("SELECT * FROM users WHERE username LIKE '" . $user . "%'");
if ($userCheck->num_rows > 0) {
	$user = $user . $userCheck->num_rows;
}
// Check if the username already exists
$emailCheck = $connect->query("SELECT * FROM users WHERE email = '" . $email . "'");
$phoneCheck = $connect->query("SELECT * FROM users WHERE phone='" . $phone . "'");

if ($phoneCheck->num_rows > 0) {
	$response = array(
		'error' => true,
		'message' => 'Phone Number already exists'
	);
} else if ($emailCheck->num_rows > 0) {
	$response = array(
		'error' => true,
		'message' => 'Email already exists'
	);
} else {
	// Proceed with inserting the new user data
	$result = $connect->query("INSERT INTO users ( username, email, phone, password, spin_chance) 
                               VALUES ('" . $user . "', '" . $email . "', '" . $phone . "', md5('" . $pass . "'),100)");

	if ($result) {
		$response = array(
			'error' => false,
			'message' => 'User registered successfully'
		);
	} else {
		$response = array(
			'error' => true,
			'message' => 'User registration failed',
			'data' => $result
		);
	}
}

header('Content-Type: application/json');
echo json_encode($response);
