/**
 * Reformats a phone number
 *
 * @param v_phone The phone to format
 * @return The formated phone or %NULL if bad sintax
 **/
DROP FUNCTION IF EXISTS pbx.phoneFormat;
DELIMITER $$
CREATE FUNCTION pbx.phoneFormat (vPhone VARCHAR(255))
RETURNS VARCHAR(255)
DETERMINISTIC
BEGIN
	DECLARE vI INT DEFAULT 0;
	DECLARE vChr VARCHAR(1);
	DECLARE vLen INT DEFAULT LENGTH(vPhone);
	DECLARE vNewPhone VARCHAR(255) DEFAULT '';

	WHILE vI < vLen
    DO
		SET vChr = SUBSTR(vPhone, vI + 1, 1);
    
		IF vChr REGEXP '^[0-9]$'
        THEN
			SET vNewPhone = CONCAT(vNewPhone, vChr);
		ELSEIF vChr = '+' AND vI = 0
        THEN
			SET vNewPhone = CONCAT(vNewPhone, '00');
		END IF;
        
        SET vI = vI + 1;
    END WHILE;

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

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

	RETURN vNewPhone;
END$$
DELIMITER ;
