/**
 * Obtains a customer id from a phone number.
 *
 * @param v_phone The caller phone number
 * @return The customer id or %NULL if customer not exists or is inactive
 **/
USE pbx;
DROP FUNCTION IF EXISTS customer_from_phone;
DELIMITER $$
CREATE FUNCTION customer_from_phone (v_phone VARCHAR(255))
RETURNS INT
DETERMINISTIC
BEGIN
	DECLARE v_customer INT DEFAULT NULL;

	SET @phone = v_phone COLLATE 'utf8_unicode_ci';

	-- Searchs a customer associated to the phone number

	DROP TEMPORARY TABLE IF EXISTS tmp.customer;
	CREATE TEMPORARY TABLE tmp.customer
		ENGINE = MEMORY
		SELECT id_cliente customer
			FROM vn2008.Clientes c
			WHERE telefono = @phone
				OR movil = @phone
		UNION
		SELECT id_cliente
			FROM vn2008.Consignatarios
			WHERE telefono = @phone
				OR movil = @phone
		UNION
		SELECT r.id_cliente
			FROM vn2008.Relaciones r
				JOIN vn2008.Contactos c ON r.Id_Contacto = c.Id_Contacto
			WHERE telefono = @phone
				OR movil = @phone;

	SELECT t.customer INTO v_customer
		FROM tmp.customer t
			JOIN vn2008.Clientes c ON c.id_cliente = t.customer
		WHERE c.activo
		LIMIT 1;

	DROP TEMPORARY TABLE tmp.customer;

	RETURN v_customer;
END$$
DELIMITER ;
