DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`recipe_Cook`(vItemFk INT, vBunchesQuantity INT, vDate DATE)
BEGIN

	DECLARE vCalc INT;
    DECLARE vWarehouseFk INT DEFAULT 1; -- Silla FV

	SET @element := '';
    SET @counter := 0;

	CALL cache.available_refresh(vCalc, FALSE, vWarehouseFk, vDate);

	DROP TEMPORARY TABLE IF EXISTS tmp.recipeCook;
    
    CREATE TEMPORARY TABLE tmp.recipeCook
    SELECT *,
            @counter := IF(@element = element COLLATE utf8_general_ci , @counter + 1, 1) as counter,
            @element := element COLLATE utf8_general_ci
		FROM
			(
			SELECT 	i.id itemFk,
					CONCAT(i.longName, ' (ref: ',i.id,')') longName,
					i.size,
					i.inkFk,
					a.available,
					r.element,
					vBunchesQuantity * r.quantity as quantity,
					r.itemFk as bunchItemFk,
					IFNULL((i.inkFk = r.inkFk ) ,0)
						+ IFNULL((i.size = r.size) ,0)
                        + IFNULL((i.name LIKE CONCAT('%',r.name,'%')) ,0)
                        + IFNULL((i.longName LIKE CONCAT('%',r.longName,'%')),0) 
                        + IFNULL((i.typeFk = r.typeFk),0) as matches,
                    i.typeFk,
                    rl.previousSelected
				FROM vn.recipe r 
					JOIN vn.item i ON (IFNULL(i.name LIKE CONCAT('%',r.name,'%'), 0)
									OR IFNULL(i.longName LIKE CONCAT('%',r.longName,'%'),0))
									OR i.typeFk <=> r.typeFk
					JOIN cache.available a ON a.item_id = i.id AND a.calc_id = vCalc
                    LEFT JOIN (SELECT recipe_ItemFk, element as log_element, selected_ItemFk, count(*) as previousSelected
									FROM vn.recipe_log
                                    GROUP BY recipe_ItemFk, element, selected_ItemFk) rl ON rl.recipe_ItemFk = r.itemFk 
																						AND rl.log_element = r.element
                                                                                        AND rl.selected_ItemFk = i.id
				WHERE r.itemFk = vItemFk
					AND a.available > vBunchesQuantity * r.quantity 
			 UNION ALL
				 SELECT 100 itemFk,
							CONCAT('? ',r.element,' ',IFNULL(r.size,''),' ',IFNULL(r.inkFk,'')) as longName,
							NULL,
							NULL,
							0,
							r.element,
							vBunchesQuantity * r.quantity as quantity,
							r.itemFk as bunchItemFk,
					  -1 as matches,
                      r.typeFk,
                      NULL
					FROM vn.recipe r
					WHERE r.itemFk = vItemFk
                    GROUP BY r.element
			) sub
             
            ORDER BY element, matches DESC, previousSelected DESC;
 
		SELECT * 
			FROM tmp.recipeCook
			WHERE counter < 6
            OR itemFk = 100 
            ;
    
END$$
DELIMITER ;
