DROP PROCEDURE IF EXISTS `vn`.`ticketGetProblems`;

DELIMITER $$
$$
CREATE
    DEFINER = root@`%` PROCEDURE `vn`.`ticketGetProblems`(IN vIsTodayRelative TINYINT(1))
BEGIN
/**
 * @deprecated Use ticket_getProblems() instead
 *
 */
    DECLARE vWarehouse INT;
    DECLARE vDate DATE;
    DECLARE vAvailableCache INT;
    DECLARE vDone INT DEFAULT 0;
   	DECLARE vComponentCount INT;

    DECLARE vCursor CURSOR FOR
        SELECT DISTINCT tt.warehouseFk, IF(vIsTodayRelative, CURDATE(), date(tt.shipped))
            FROM tmp.ticketGetProblems tt
            WHERE DATE(tt.shipped) BETWEEN CURDATE()
                AND TIMESTAMPADD(DAY, IF(vIsTodayRelative, 9.9, 1.9), CURDATE());
  
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1;

    DROP TEMPORARY TABLE IF EXISTS tmp.ticketProblems;
        CREATE TEMPORARY TABLE tmp.ticketProblems (
            ticketFk INT(11) PRIMARY KEY,
            isFreezed INTEGER(1) DEFAULT 0,
            risk DECIMAL(10,2) DEFAULT 0,
            hasTicketRequest INTEGER(1) DEFAULT 0,
            isAvailable INTEGER(1) DEFAULT 1,
            itemShortage VARCHAR(250),
			isTaxDataChecked  INTEGER(1) DEFAULT 1,
			itemDelay VARCHAR(250), 
			componentLack INTEGER(1)
        ) ENGINE = MEMORY;

     DROP TEMPORARY TABLE IF EXISTS tmp.ticketList;
        CREATE TEMPORARY TABLE tmp.ticketList
        (PRIMARY KEY (ticketFk))
         ENGINE = MEMORY
            SELECT tp.ticketFk, c.id clientFk
                FROM tmp.ticketGetProblems tp
        JOIN vn.client c ON c.id = tp.clientFk;
 
    SELECT COUNT(*) INTO vComponentCount
    	FROM vn.component c 
    	WHERE c.isRequired;
    
    INSERT INTO tmp.ticketProblems(ticketFk, componentLack)
    	SELECT tl.ticketFk, (COUNT(DISTINCT s.id) * vComponentCount > COUNT(c.id))
            FROM tmp.ticketList tl
            	JOIN vn.sale s ON s.ticketFk = tl.ticketFk
            	LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id 
            	LEFT JOIN vn.component c ON c.id = sc.componentFk AND c.isRequired
            GROUP BY tl.ticketFk;
         
    INSERT INTO tmp.ticketProblems(ticketFk, isFreezed)
        SELECT DISTINCT tl.ticketFk, 1
            FROM tmp.ticketList tl
                JOIN vn.client c ON c.id = tl.clientFk
            WHERE c.isFreezed
            ON DUPLICATE KEY UPDATE
            isFreezed = c.isFreezed;
            
     DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt;
     CREATE TEMPORARY TABLE tmp.clientGetDebt
        (PRIMARY KEY (clientFk))
        ENGINE = MEMORY
            SELECT DISTINCT clientFk
                FROM tmp.ticketList;

    CALL clientGetDebt(CURDATE());

    INSERT INTO tmp.ticketProblems(ticketFk, risk)
        SELECT DISTINCT tl.ticketFk, r.risk
            FROM tmp.ticketList tl
                JOIN vn.ticket t ON t.id = tl.ticketFk
                JOIN vn.agencyMode a ON t.agencyModeFk = a.id
                JOIN tmp.risk r ON r.clientFk = t.clientFk
                JOIN vn.client c ON c.id = t.clientFk
                JOIN vn.clientConfig cc
            WHERE r.risk - cc.riskTolerance > c.credit + 10
                AND a.isRiskFree = FALSE
        ON DUPLICATE KEY UPDATE
            risk = r.risk;
     
    INSERT INTO tmp.ticketProblems(ticketFk, hasTicketRequest)
        SELECT DISTINCT tl.ticketFk, 1
            FROM tmp.ticketList tl
                JOIN vn.ticketRequest tr ON tr.ticketFk = tl.ticketFk
            WHERE tr.isOK IS NULL AND tr.saleFk IS NOT NULL
        ON DUPLICATE KEY UPDATE
            hasTicketRequest = 1;

    OPEN vCursor;

    WHILE NOT vDone
    DO
        FETCH vCursor INTO vWarehouse, vDate;
   
        CALL cache.available_refresh(vAvailableCache, FALSE, vWarehouse, vDate);

        INSERT INTO tmp.ticketProblems(ticketFk, isAvailable)
            SELECT tl.ticketFk, 0
                FROM tmp.ticketList tl
                    JOIN vn.ticket t ON t.id = tl.ticketFk
                    JOIN vn.sale s ON s.ticketFk = t.id
                    JOIN vn.item i ON i.id = s.itemFk
                    JOIN vn.itemType it on it.id = i.typeFk
                    LEFT JOIN cache.available av ON av.item_id = i.id
                    AND av.calc_id = vAvailableCache
                WHERE date(t.shipped) = vDate
                    AND it.categoryFk != 6
                    AND IFNULL(av.available, 0) < 0
                    AND s.isPicked = FALSE
                    AND NOT i.generic
                    AND vWarehouse = t.warehouseFk
                GROUP BY tl.ticketFk
            ON DUPLICATE KEY UPDATE
                isAvailable = 0;
/*
    INSERT INTO tmp.ticketProblems(ticketFk, itemShortage)
    	SELECT ticketFk, problem
    	FROM (
        SELECT tl.ticketFk, CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')) problem
            FROM tmp.ticketList tl
                JOIN vn.ticket t ON t.id = tl.ticketFk
                JOIN vn.sale s ON s.ticketFk = t.id
                JOIN vn.item i ON i.id = s.itemFk
                JOIN vn.itemType it on it.id = i.typeFk
                LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk 
                LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache
            WHERE IFNULL(av.available, 0) < 0
                AND s.quantity > IFNULL(issw.visible, 0)
                AND s.quantity > 0
                AND s.isPicked = FALSE
                AND s.reserved = FALSE
                AND it.categoryFk != 6
                AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate)
                AND NOT i.generic
                AND CURDATE() = vDate
                AND t.warehouseFk = vWarehouse
            GROUP BY tl.ticketFk LIMIT 1) sub
        ON DUPLICATE KEY UPDATE
            itemShortage = sub.problem;
*/
           INSERT INTO tmp.ticketProblems(ticketFk, itemDelay)
           SELECT ticketFk, problem
    		FROM (
	        SELECT tl.ticketFk, GROUP_CONCAT('I: ',i.id, ' ', i.longName, ' ') problem
	            FROM tmp.ticketList tl
	                JOIN vn.ticket t ON t.id = tl.ticketFk
	                JOIN vn.sale s ON s.ticketFk = t.id
	                JOIN vn.item i ON i.id = s.itemFk
	                JOIN vn.itemType it on it.id = i.typeFk
	              	LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk 
               WHERE s.quantity > IFNULL(issw.visible, 0)
	                AND s.quantity > 0
	                AND s.isPicked = FALSE
	                AND s.reserved = FALSE
	                AND it.categoryFk != 6
	                AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate)
                	AND NOT i.generic
	                AND CURDATE() = vDate
	                AND t.warehouseFk = vWarehouse
	            GROUP BY tl.ticketFk LIMIT 1) sub
        ON DUPLICATE KEY UPDATE
            itemDelay = sub.problem;
    END WHILE;

    CLOSE vCursor;
	
	INSERT INTO tmp.ticketProblems(ticketFk, isTaxDataChecked)
        SELECT DISTINCT tl.ticketFk, FALSE
            FROM tmp.ticketList tl
                JOIN vn.client c ON c.id = tl.clientFk
            WHERE c.isTaxDataChecked= FALSE
		ON DUPLICATE KEY UPDATE
            isTaxDataChecked = FALSE;

    DROP TEMPORARY TABLE
        tmp.clientGetDebt,
        tmp.ticketList; 
      
END;;$$
DELIMITER ;
