/* 
 * Arrebol Consultancy copyright.
 * 
 * This code belongs to Arrebol Consultancy
 * its use, redistribution or modification are prohibited 
 * without written authorization from Arrebol Consultancy.
 */
/**
 * Author:  Oscar Armando Vargas Cardenas <oscar.vargas@arrebol.com.mx>
 * Created: 8/06/2021
 */
/**
 * Author:  Carlos Janitzio Zavala Lopez <janitzio.zavala@arrebol.com.mx>
 * Modify: 21 jun. 2021
 */
DELIMITER //
CREATE PROCEDURE DailyFillToCollect()
BEGIN
    DECLARE driver_id_v CHAR(36);
    DECLARE v_total INT;
    DECLARE total_to_pay_v INT;
    DECLARE total_day_by_month INT;
    DECLARE user_v CHAR(36) DEFAULT '09ea84b8-b9d1-4a71-adfe-db653b2a9982';
    DECLARE done INT DEFAULT false;
    DECLARE drivers_c CURSOR FOR SELECT p.id_driver, p.total_to_pay FROM DASHBOARD_TO_COLLECT_VIEW p;			
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = true;

    SELECT COUNT(ID) INTO v_total FROM TO_COLLECT WHERE DATE(created_on) = CURDATE();

    IF v_total = 0 THEN
        OPEN drivers_c;
        read_loop: LOOP 
            FETCH drivers_c INTO driver_id_v, total_to_pay_v;

            IF done THEN
                    LEAVE read_loop;
            END IF;

            INSERT INTO TO_COLLECT(id, to_collect, complete, driver_id, created_by, created_on, total)
            VALUE(uuid(), now() , 1, driver_id_v, user_v, now(), total_to_pay_v);
        END LOOP;	
        COMMIT;
    END IF;

    CLOSE drivers_c;
END; //
DELIMITER ;