/* 
 * 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: 26 jul. 2021
 */
-- --------------------------------------------------------
--
-- DROP FUNCTION IF EXISTS `DailyFillFee`
--
DROP PROCEDURE IF EXISTS `DailyFillFee`;
 -- --------------------------------------------------------
--
-- Estructura para la función `DailyFillFee`
--
DELIMITER //
CREATE PROCEDURE DailyFillFee()
BEGIN
    DECLARE driver_id_v CHAR(36);
    DECLARE taxi_id_v CHAR(36);
    DECLARE totalSalesByTaxiId INT;
    DECLARE totalGarage INT;
    DECLARE total_amount_paid_v 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_vehicle, p.id_driver, p.amount_paid FROM DASHBOARD_TO_COLLECT_VIEW p;			
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = true;

    OPEN drivers_c;
    read_loop: LOOP 
        FETCH drivers_c INTO taxi_id_v, driver_id_v, total_amount_paid_v;

        IF done THEN
                        LEAVE read_loop;
        END IF;

        SET totalSalesByTaxiId = 0;
        SET totalGarage = 0;

        -- Contamos si tiene ventas 
        SELECT COUNT(id) INTO totalSalesByTaxiId 
        FROM SALE 
        WHERE 
            taxi_id = CONVERT(taxi_id_v USING utf8mb4) AND
            DATE_ADD(DATE(pay_date), INTERVAL 1 DAY) = CURDATE();

        -- Contamos si esta en garage	
        SELECT COUNT(id) INTO totalGarage
        FROM SERVICE_ORDER 
        WHERE 
            taxi_id = CONVERT(taxi_id_v USING utf8mb4) AND
            (CASE
                WHEN service_order_type in ('PASE_TALLER','PENDING','APPROVED','PROGRESS')
                        THEN TRUE
                WHEN service_order_type = 'FINISHED'
                        THEN  DATE(finish_date) = CURDATE()
                ELSE FALSE
            END);

        IF totalSalesByTaxiId = 0 AND totalGarage = 0 THEN        
            IF total_amount_paid_v = 0 THEN
                INSERT INTO FEE_BY_DRIVER(id, driver_id, fee_date, amount, comments, fee_status, created_by, created_on)
                VALUE(uuid(), driver_id_v, now() , 50, 'Multa automatica por sistema', 'NO_PAID', user_v, now());
            END IF;
        END IF;

    END LOOP;	
    COMMIT;

    CLOSE drivers_c;
END; //
DELIMITER ;