DELIMITER $$

CREATE FUNCTION AddUser(siteId INT, userName VARCHAR(100), emailAddress VARCHAR(255))
	RETURNS INT
	BEGIN
		SET @userId = 0;

		SELECT id INTO @userId FROM user WHERE email_address = emailAddress;

		IF (@userId = 0) THEN
			INSERT INTO user (name, email_address) VALUES (userName, emailAddress);

			SET @userId = LAST_INSERT_ID();

			INSERT INTO site_user (site_id, user_id, active, deleted) VALUES (@siteId, @userId, 1, 0);
		ELSE
			UPDATE site_user SET active = 1 WHERE user_id = @userId;
		END IF;

		RETURN @userId;
	END$$

DELIMITER ;

SET @siteId = 0;

SELECT id INTO @siteId FROM site LIMIT 1;

SET @newUserId = AddUser(@siteId, 'Beth Sargeson', 'bsargeson@arenaracingcompany.co.uk');

DROP FUNCTION IF EXISTS AddUser;