/**
 * Reformats a phone number
 *
 * @param v_phone The phone to format
 * @return The formated phone or %NULL if bad sintax
 **/
USE pbx;
DROP FUNCTION IF EXISTS phone_format;
DELIMITER $$
CREATE FUNCTION phone_format (phone VARCHAR(255))
RETURNS VARCHAR(255)
DETERMINISTIC
BEGIN
	DECLARE i INT DEFAULT 0;
	DECLARE chr VARCHAR(1);
	DECLARE len INT DEFAULT LENGTH(phone);
	DECLARE newPhone VARCHAR(255) DEFAULT '';

	WHILE i < len
	DO
		SET chr = SUBSTR(phone, i+1, 1);

		IF chr REGEXP '^[0-9]$'
		THEN
			SET newPhone = CONCAT(newPhone, chr);
		ELSEIF chr = '+' AND i = 0
		THEN
			SET newPhone = CONCAT(newPhone, '00');
		END IF;

		SET i = i + 1;
	END WHILE;

	IF newPhone REGEXP '^0+$' OR newPhone = '' THEN
		RETURN NULL;
	END IF;

	IF newPhone REGEXP '^0034' THEN
		SET newPhone = SUBSTR(newPhone, 5);
	END IF;

	RETURN newPhone;
END$$
DELIMITER ;
