/**
 * Checks whether a passed phone number has valid sintax
 *
 * @param v_phone The phone to check format
 * @return %TRUE if it's well formated
 **/
USE pbx;
DROP PROCEDURE IF EXISTS phone_is_valid;
DELIMITER $$
CREATE PROCEDURE phone_is_valid (v_phone VARCHAR(255))
BEGIN
	DECLARE v_is_valid BOOLEAN;

	SET v_is_valid =  v_phone IS NULL
		OR (v_phone REGEXP '^[0-9]+$'
		AND v_phone NOT REGEXP '^0+$'
		AND v_phone NOT REGEXP '^0034');

	IF NOT v_is_valid
	THEN
		SIGNAL SQLSTATE '45000'
			SET MESSAGE_TEXT = 'PHONE_INVALID_FORMAT';
	END IF;
END$$
DELIMITER ;
