DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`client_mailSales`(
	vSelf INT,
	vDated DATE
)
proc: BEGIN
/**
 * Envia un correo electrónico con un resumen de los pedidos
 * preparados para un cliente.
 *
 * @param vSelf Id del cliente
 * @param vDated Fecha de preparación
 */
	DECLARE vTicketFk INT;
	DECLARE vAlias VARCHAR(50);
	DECLARE vStreet VARCHAR(255);
	DECLARE vCity VARCHAR(25);
	DECLARE vAmount DOUBLE;
	DECLARE vMailTo VARCHAR(250);
	DECLARE vString TEXT;
	DECLARE vDone BOOL DEFAULT FALSE;
	DECLARE vTickets CURSOR FOR 
		SELECT t.id,
				t.nickname,
				CAST(sub.amount AS DECIMAL(10,2)) amount,
				a.street,
				a.city
			FROM ticket t
				JOIN `address` a ON t.addressFk = a.id
				JOIN (
					SELECT s.ticketFk,
						SUM(
							s.quantity * s.price * (100 - s.discount) / 100
						) amount
					FROM sale s
						JOIN ticket t ON t.id = s.ticketFk
					WHERE t.shipped >= util.VN_CURDATE() - INTERVAL 6 MONTH
					GROUP BY s.ticketFk
				) sub ON sub.ticketFk = t.id
			WHERE t.shipped BETWEEN vDated AND util.dayEnd(vDated)
				AND t.clientFk = vSelf;
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

	SET vDated = IFNULL(vDated, util.yesterday());

	SET vString = CONCAT('<p><font face="verdana" >',
					'<h2> Relación de envíos.</h2>',
					'<h3><font color="green">Dia: ', vDated, '</font></h3>');

	OPEN vTickets;
	l: LOOP
		SET vDone = FALSE;
		FETCH vTickets INTO vTicketFk, vAlias, vAmount, vStreet, vCity;
		
		IF vDone THEN
			LEAVE l;
		END IF;
		
		SET vString = CONCAT(vString, '<br><br>',
						'<table>
							<tr>
								<th> <a href = "https://shop.verdnatura.es/#!form=ecomerce/ticket&ticket=',vTicketFk,'">
								<font color="green"> Ticket ', vTicketFk,'</font></th>
								<th></th><th></th><th></th><th></th>
								<th></th><th></th><th></th><th></th>
								<th> <font color="orange"> ', vAmount, ' € </a></font></th>
							</tr>
						</table>',
					'             ', vAlias, '<br>',
					'             ', vStreet, '(', vCity, ')');
	END LOOP;

	IF vTicketFk IS NULL THEN
		LEAVE proc;
	END IF;

	SET vString = CONCAT(
			vString, 
			'<table>',
			'<tr><th></th></tr>',
			'</table>',
			'<br><br>Puede acceder al detalle de los albaranes haciendo click sobre el número de Ticket',
			'<br><h3> Muchas gracias por su confianza</h3>',
			'</font></p>');

	SELECT email INTO vMailTo
		FROM client
		WHERE id = vSelf
			AND email <> '';

	-- Envío del email
	IF vMailTo IS NOT NULL THEN
		CALL mail_insert(
			vMailTo,
			NULL,
			'Resumen de pedidos preparados',
			vString
		);
	END IF;
END$$
DELIMITER ;
