SET @INIT_DATE = '{init_date}';
SET @FINISH_DATE = '{finish_date}';

DELETE FROM PRO_REPORTING WHERE `YEAR` >= DATE_FORMAT(CAST(@INIT_DATE AS DATE), '%Y')
AND `MONTH` >= DATE_FORMAT(CAST(@INIT_DATE AS DATE), '%m')
AND `YEAR` <= DATE_FORMAT(CAST(@FINISH_DATE AS DATE), '%Y')
AND `MONTH` <= DATE_FORMAT(CAST(@FINISH_DATE AS DATE), '%m');

INSERT INTO PRO_REPORTING (
    PRO_UID,
    `MONTH`,
    `YEAR`,
    AVG_TIME,
    SDV_TIME,
    TOTAL_CASES_IN,
    TOTAL_CASES_OUT,
    CONFIGURED_PROCESS_TIME,
    CONFIGURED_PROCESS_COST,
    TOTAL_CASES_OPEN,
    TOTAL_CASES_OVERDUE,
    TOTAL_CASES_ON_TIME,
    PRO_COST,
    PRO_UNIT_COST
)
SELECT
    APPLICATION.PRO_UID,
    DATE_FORMAT(APPLICATION.APP_INIT_DATE, '%m') AS `MONTH`,
    DATE_FORMAT(APPLICATION.APP_INIT_DATE, '%Y') AS `YEAR`,
    AVG(APPLICATION.APP_DURATION*24) AS `AVG_TIME`,
    STD(APPLICATION.APP_DURATION*24) AS `STD_TIME`,
    COUNT(APPLICATION.APP_INIT_DATE) AS `TOTAL_CASES_IN`,
    COUNT(APPLICATION.APP_FINISH_DATE) AS `TOTAL_CASES_OUT`,
    NULL,
    NULL,
    count(if(APPLICATION.APP_FINISH_DATE != null, NULL, 1)) AS TOTAL_CASES_OPEN,
    count(if(APPLICATION.APP_DELAY_DURATION > 0, 1, NULL)) AS TOTAL_CASES_OVERDUE,
    count(if(APPLICATION.APP_DELAY_DURATION <= 0, 1, NULL)) AS TOTAL_CASES_ON_TIME,
    0,
    NULL
FROM
    APPLICATION FORCE INDEX (PRIMARY)
WHERE
    APPLICATION.APP_INIT_DATE BETWEEN CAST(@INIT_DATE AS DATETIME) AND CAST(@FINISH_DATE AS DATETIME)
GROUP BY APPLICATION.PRO_UID;

UPDATE USR_REPORTING
INNER JOIN
PROCESS
ON USR_REPORTING.PRO_UID = PROCESS.PRO_UID
SET USR_REPORTING.PRO_COST = PROCESS.PRO_COST,
USR_REPORTING.PRO_UNIT_COST = PROCESS.PRO_UNIT_COST;

#TODO task duration should be calculated with the calendar
UPDATE PRO_REPORTING
SET PRO_REPORTING.CONFIGURED_PROCESS_TIME  = (
    SELECT SUM(if (TASK.TAS_TIMEUNIT = "DAYS", (TASK.TAS_DURATION*24), (if (TASK.TAS_TIMEUNIT = "MINUTES", (TASK.TAS_DURATION/60), TASK.TAS_DURATION))))
    FROM TASK
    WHERE PRO_REPORTING.PRO_UID = TASK.PRO_UID
);

UPDATE PRO_REPORTING
SET PRO_REPORTING.CONFIGURED_PROCESS_COST  = (
    SELECT SUM(USERS.USR_COST_BY_HOUR)
    FROM TASK, TASK_USER, USERS
    WHERE TASK.PRO_UID = PRO_REPORTING.PRO_UID
    AND TASK.TAS_UID = TASK_USER.TAS_UID
    AND TASK_USER.USR_UID = USERS.USR_UID
) OR (
    SELECT SUM(USERS.USR_COST_BY_HOUR)
    FROM TASK, TASK_USER, GROUP_USER, USERS
    WHERE PRO_REPORTING.PRO_UID = TASK.PRO_UID
    AND TASK.TAS_UID = TASK_USER.TAS_UID
    AND TASK_USER.USR_UID = GROUP_USER.GRP_UID
    AND GROUP_USER.USR_UID = USERS.USR_UID
)