CREATE PROCEDURE `pr_insert_ips_rpt`(
	IN `par_incident_date` int(11),
	IN `par_vulnerability` varchar(256),
	IN `par_action_taken` varchar(256),
	IN `par_rule_desc` varchar(500),
	IN `par_rule_ref` varchar(500),
	IN `par_machine_id` varchar(45),
	IN par_username VARCHAR(512)
)
BEGIN
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	DECLARE var_GroupId INT(11) DEFAULT NULL;
	DECLARE var_md5 CHAR(64) DEFAULT NULL;
	DECLARE var_matched_id BIGINT(20) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	
	SELECT client_id, GroupId INTO var_client_id, var_GroupId FROM client_master WHERE guid=par_machine_id; 
	SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
	IF var_user_id IS NULL THEN
		INSERT INTO rpt_user_master(username) VALUES(par_username);
		SET var_user_id = (select last_insert_id());
	END IF;
	IF var_client_id IS NOT NULL THEN
	
		INSERT INTO rpt_ips_fact(incident_date,vulnerability,action_taken,rule_desc,rule_ref,client_id,user_id,GroupId) 
		VALUES(par_incident_date,par_vulnerability,par_action_taken,par_rule_desc,par_rule_ref,var_client_id,var_user_id,var_GroupId);		
		
		SET var_md5 = MD5(CONCAT(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))), var_GroupId, var_client_id, var_user_id));
		SET var_matched_id = (SELECT rowid FROM rpt_ips_chart_summary WHERE md5_match=var_md5);
		IF var_matched_id IS NOT NULL THEN
			UPDATE rpt_ips_chart_summary SET incident_count=(incident_count+1) WHERE `rowid`=var_matched_id;
		ELSE
			INSERT INTO rpt_ips_chart_summary(incident_date_only, client_id, user_id, GroupId, md5_match, incident_count) 
			VALUES(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))), var_client_id, var_user_id, var_GroupId, var_md5, 1);
		END IF;
		
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pr_insert_port_scan_rpt`;
DELIMITER $$
CREATE PROCEDURE `pr_insert_port_scan_rpt`(
	IN `par_incident_date` int(11),
	IN `par_attacker_ip` varchar(256),
	IN `par_attacker_mac` varchar(256),
	IN `par_scanports` varchar(3600),
	IN `par_action_taken` varchar(256),
	IN `par_machine_id` varchar(45)
)
BEGIN
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	DECLARE var_GroupId INT(11) DEFAULT NULL;
	DECLARE var_md5 CHAR(64) DEFAULT NULL;
	DECLARE var_matched_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	
	SELECT client_id, GroupId INTO var_client_id, var_GroupId FROM client_master WHERE guid=par_machine_id; 
	IF var_client_id IS NOT NULL THEN
		
		INSERT INTO rpt_port_scan_fact(incident_date,attacker_ip,attacker_mac,scanports,action_taken,client_id,GroupId) VALUES(par_incident_date,par_attacker_ip,par_attacker_mac,par_scanports,par_action_taken,var_client_id,var_GroupId);		
		
		SET var_md5 = MD5(CONCAT(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))), var_GroupId, var_client_id));
		SET var_matched_id = (SELECT rowid FROM rpt_port_scan_chart_summary WHERE md5_match=var_md5);
		IF var_matched_id IS NOT NULL THEN
			UPDATE rpt_port_scan_chart_summary SET incident_count=(incident_count+1) WHERE `rowid`=var_matched_id;
		ELSE
			INSERT INTO rpt_port_scan_chart_summary(incident_date_only, client_id, GroupId, md5_match, incident_count) 
			VALUES(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))), var_client_id, var_GroupId, var_md5, 1);
		END IF;
		
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pr_insert_virus_scan_rpt`;
DELIMITER $$
CREATE PROCEDURE `pr_insert_virus_scan_rpt`(
	IN `par_incident_date` int(11),
	IN `par_infected_file` varchar(17000),
	IN `par_virus_name` varchar(100),
	IN `par_action_taken` varchar(50),
	IN `par_module` varchar(256),
	IN `par_module_id` int(11),
	IN `par_user` varchar(256),
	IN `par_version` varchar(100),
	IN `par_infection_source` varchar(50),
	IN `par_machine_id` varchar(45)
)
BEGIN
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	DECLARE var_GroupId INT(11) DEFAULT NULL;
	DECLARE var_md5 CHAR(64) DEFAULT NULL;
	DECLARE var_matched_id BIGINT(20) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;

	SET time_zone = '+00:00';
	
	SELECT client_id, GroupId INTO var_client_id, var_GroupId FROM client_master WHERE guid=par_machine_id;
	SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_user LIMIT 1;
	IF var_user_id IS NULL THEN
		INSERT INTO rpt_user_master(username) VALUES(par_user);
		SET var_user_id = (select last_insert_id());
	END IF;
	
	IF var_client_id IS NOT NULL THEN
		SET var_md5 = MD5(CONCAT(par_infected_file,par_virus_name,par_action_taken,par_module,par_module_id,par_version,par_infection_source));
		SET var_matched_id = (SELECT virus_scan_id FROM rpt_virus_scan_dim WHERE md5_virus_scan=var_md5);
		IF var_matched_id IS NULL THEN
			INSERT INTO rpt_virus_scan_dim(infected_file,virus_name,action_taken,module,module_id,version,infection_source,md5_virus_scan) 
			VALUES(par_infected_file,par_virus_name,par_action_taken,par_module,par_module_id,par_version,par_infection_source,var_md5);
			SET var_matched_id = (select last_insert_id());
		END IF;
		
		INSERT INTO rpt_virus_incident_fact(virus_scan_id,incident_date,client_id,GroupId, user_id, module_id) VALUES(var_matched_id,par_incident_date,var_client_id,var_GroupId,var_user_id, par_module_id);

		SET var_md5 = MD5(CONCAT(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))), var_client_id, var_GroupId, var_user_id));
		SET var_matched_id = (SELECT rowid FROM rpt_virus_chart_summary WHERE md5_match=var_md5);
		IF var_matched_id IS NOT NULL THEN
			UPDATE rpt_virus_chart_summary SET incident_count=(incident_count+1) WHERE `rowid`=var_matched_id;
		ELSE
			INSERT INTO rpt_virus_chart_summary(incident_date_only, client_id, GroupId, user_id, md5_match, incident_count) 
			VALUES(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))), var_client_id, var_GroupId, var_user_id, var_md5, 1);
		END IF;
		
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pr_insert_vuln_affected_platfrorms`;
DELIMITER $$
CREATE PROCEDURE `pr_insert_vuln_affected_platfrorms`(
	IN `par_cve_id` VARCHAR(14),
	IN `par_platform_name` varchar(256)
)
BEGIN
	DECLARE var_md5 CHAR(64) DEFAULT NULL;
	DECLARE var_matched_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	
	SET var_md5 = MD5(CONCAT(par_cve_id, par_platform_name));
	SET var_matched_id = (SELECT rowid FROM rpt_vuln_affected_platforms_dim WHERE md5_match=var_md5);
	-- Add platform only if it doesn't exist.
	IF var_matched_id IS NULL THEN
		INSERT INTO rpt_vuln_affected_platforms_dim(cve_id, platform_name, md5_match) VALUES(par_cve_id, par_platform_name, var_md5);
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pr_insert_vuln_affected_products`;
DELIMITER $$
CREATE PROCEDURE `pr_insert_vuln_affected_products`(
	IN `par_cve_id` VARCHAR(14),
	IN `par_product_name` varchar(256)
)
BEGIN
	DECLARE var_md5 CHAR(64) DEFAULT NULL;
	DECLARE var_matched_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	
	SET var_md5 = MD5(CONCAT(par_cve_id, par_product_name));
	SET var_matched_id = (SELECT `rowid` FROM rpt_vuln_affected_products_dim WHERE md5_match=var_md5);
	-- Add platform only if it doesn't exist.
	IF var_matched_id IS NULL THEN
		INSERT INTO rpt_vuln_affected_products_dim(cve_id, product_name, md5_match) VALUES(par_cve_id, par_product_name, var_md5);
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pr_insert_vuln_references`;
DELIMITER $$
CREATE PROCEDURE `pr_insert_vuln_references`(
	IN `par_cve_id` VARCHAR(14),
	IN `par_source_name` varchar(256),
	IN `par_reference_name` varchar(5000)	
)
BEGIN
	DECLARE var_md5 CHAR(64) DEFAULT NULL;
	DECLARE var_matched_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	
	SET var_md5 = MD5(CONCAT(par_cve_id, par_source_name));
	SET var_matched_id = (SELECT rowid FROM rpt_vuln_references_dim WHERE md5_match=var_md5);
	-- Add platform only if it doesn't exist.
	IF var_matched_id IS NULL THEN
		INSERT INTO rpt_vuln_references_dim(cve_id, source_name, reference_name, md5_match) VALUES(par_cve_id, par_source_name, par_reference_name, var_md5);
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pr_insert_vuln_rpt`;
DELIMITER $$
CREATE PROCEDURE `pr_insert_vuln_rpt`(
	IN `par_cve_id` VARCHAR(14),
	IN `par_incident_date` int(11),
	IN `par_scan_type` INT(2),
	IN `par_username` varchar(512),
	IN `par_client_guid` varchar(45),
	IN `par_title` varchar(1000),	
	IN `par_def_version` int(11),
	IN `par_vendor` varchar(256),
	IN `par_description` varchar(5000),
	IN `par_last_modified` int(11),
	IN `par_score` varchar(60),
	IN `par_severity` int(2)	
)
BEGIN
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	DECLARE var_GroupId INT(11) DEFAULT NULL;
	DECLARE var_md5 CHAR(64) DEFAULT NULL;
	DECLARE var_matched_id BIGINT(20) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	DECLARE var_vendor_id BIGINT(20) DEFAULT NULL;
	DECLARE var_vuln_id BIGINT(20) DEFAULT NULL;

	SET time_zone = '+00:00';
	
	SELECT client_id, GroupId INTO var_client_id, var_GroupId FROM client_master WHERE guid=par_client_guid;	
	IF var_client_id IS NOT NULL THEN
		
		-- If username doesn't exist in rpt_user_master then add it as new user.
		SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
		IF var_user_id IS NULL THEN
			INSERT INTO rpt_user_master(username) VALUES(par_username);
			SET var_user_id = (select last_insert_id());
		END IF;
		
		-- If Vendor doesn't exist in rpt_vuln_vendor_master_dim then add it as new one.
		SET var_vendor_id = (SELECT vendor_id FROM rpt_vuln_vendor_master_dim WHERE vendor_name=par_vendor);
		IF var_vendor_id IS NULL THEN
			INSERT INTO rpt_vuln_vendor_master_dim(vendor_name) 
			VALUES(par_vendor);
			SET var_vendor_id = (select last_insert_id());
		END IF;
		
		-- If Vulnerability doesn't exist in rpt_vuln_master_dim then add it as new one.
		SET var_vuln_id = (SELECT vuln_id FROM rpt_vuln_master_dim WHERE cve_id=par_cve_id);
		IF var_vuln_id IS NULL THEN
			INSERT INTO rpt_vuln_master_dim(cve_id, vuln_title, severity, vendor_id, description, last_modified_date, score, def_version) 
			VALUES(par_cve_id, par_title, par_severity, var_vendor_id, par_description, last_modified_date, par_score, par_def_version);
			SET var_vuln_id = (select last_insert_id());
		END IF;
		
		INSERT INTO rpt_vuln_incident_fact(incident_date, user_id, scan_type, severity, vendor_id, vuln_id, cve_id, client_id, GroupId)
		VALUES(par_incident_date, var_user_id, par_scan_type, par_severity, var_vendor_id, var_vuln_id, par_cve_id, var_client_id, var_GroupId);
		
		-- Update Summary Table 1 --
		SET var_md5 = MD5(CONCAT(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))), var_GroupId, var_client_id, var_user_id, par_severity));
		SET var_matched_id = (SELECT rowid FROM rpt_vuln_severity_chart_summary WHERE md5_match=var_md5);
		IF var_matched_id IS NOT NULL THEN
			UPDATE rpt_vuln_severity_chart_summary SET incident_count=(incident_count+1) WHERE `rowid`=var_matched_id;
		ELSE
			INSERT INTO rpt_vuln_severity_chart_summary(incident_date_only, GroupId, client_id, user_id, severity, md5_match, incident_count)
			VALUES(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))), var_GroupId, var_client_id, var_user_id, par_severity, var_md5, 1);
		END IF;
		
		-- Update Summary Table 2 --
		SET var_md5 = MD5(CONCAT(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))), var_GroupId, var_client_id, var_user_id, var_vendor_id));
		SET var_matched_id = (SELECT rowid FROM rpt_vuln_vendor_chart_summary WHERE md5_match=var_md5);
		IF var_matched_id IS NOT NULL THEN		
			UPDATE rpt_vuln_vendor_chart_summary SET incident_count=(incident_count+1) WHERE `rowid`=var_matched_id;
		ELSE
			INSERT INTO rpt_vuln_vendor_chart_summary(incident_date_only, GroupId, client_id, user_id, vendor_id, md5_match, incident_count)
			VALUES(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))),var_GroupId, var_client_id, var_user_id, var_vendor_id, var_md5, 1);
		END IF;
		
		-- Update Summary Table 3 --
		SET var_md5 = MD5(CONCAT(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))), var_GroupId, var_client_id, var_user_id, var_vuln_id));
		SET var_matched_id = (SELECT rowid FROM rpt_vuln_topvuln_chart_summary WHERE md5_match=var_md5);
		IF var_matched_id IS NOT NULL THEN		
			UPDATE rpt_vuln_topvuln_chart_summary SET incident_count=(incident_count+1) WHERE `rowid`=var_matched_id;
		ELSE
			INSERT INTO rpt_vuln_topvuln_chart_summary(incident_date_only, GroupId, client_id, user_id, vuln_id, cve_id, md5_match, incident_count)
			VALUES(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))),var_GroupId, var_client_id, var_user_id, var_vuln_id, par_cve_id, var_md5, 1);
		END IF;	
		
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pr_insert_web_security_rpt`;
DELIMITER $$
CREATE PROCEDURE `pr_insert_web_security_rpt`(
	IN `par_incident_date` int(11),
	IN `par_blocked_url` varchar(1024),
	IN `par_category` varchar(256),
	IN `par_category_id` BIGINT(20),
	IN `par_client_guid` varchar(45),
	IN `par_username` VARCHAR(512)
)
BEGIN
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	DECLARE var_GroupId INT(11) DEFAULT NULL;
	DECLARE var_category_id BIGINT(20) DEFAULT NULL;
	DECLARE var_category VARCHAR(256) DEFAULT NULL;
	DECLARE var_md5 CHAR(64) DEFAULT NULL;
	DECLARE var_matched_id BIGINT(20) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;

	SET time_zone = '+00:00';
	
	SELECT client_id, GroupId INTO var_client_id, var_GroupId FROM client_master WHERE guid=par_client_guid;
	SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username = par_username LIMIT 1;
	IF var_user_id IS NULL THEN
		INSERT INTO rpt_user_master(username) VALUES(par_username);
		SET var_user_id = (select last_insert_id());
	END IF;
	
	IF var_client_id IS NOT NULL THEN
	
		SELECT websec_category_id, category INTO var_category_id, var_category FROM rpt_websec_category_dim WHERE websec_category_id=par_category_id;
		IF var_category_id IS NULL THEN
			INSERT INTO rpt_websec_category_dim(websec_category_id,category) VALUES(par_category_id,par_category);
		END IF;
		
		SET var_md5 = MD5(CONCAT(par_category_id,par_blocked_url));
		SELECT url_id INTO var_matched_id FROM rpt_websec_bolckedsites_dim WHERE website_md5=var_md5;
		
		IF var_matched_id IS NULL THEN
			INSERT INTO rpt_websec_bolckedsites_dim(website,websec_category_id,website_md5) VALUES(par_blocked_url,par_category_id,var_md5);
			SET var_matched_id = (select last_insert_id());
		END IF;
		
		INSERT INTO rpt_websec_incident_fact(incident_date,url_id,websec_category_id,client_id,user_id,GroupId) 
		VALUES(par_incident_date,var_matched_id,par_category_id,var_client_id,var_user_id,var_GroupId);
		
		SET var_md5 = MD5(CONCAT(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))), var_GroupId, var_client_id, var_user_id, par_category_id));
		SET var_matched_id = (SELECT rowid FROM rpt_websec_chart_summary WHERE md5_match=var_md5);
		IF var_matched_id IS NOT NULL THEN		
			UPDATE rpt_websec_chart_summary SET incident_count=(incident_count+1) WHERE `rowid`=var_matched_id;
		ELSE
			INSERT INTO rpt_websec_chart_summary(incident_date_only,GroupId,client_id,user_id,websec_category_id,md5_match,incident_count)
			VALUES(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))),var_GroupId,var_client_id,var_user_id,par_category_id,var_md5,1);
		END IF;
		
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `virusscan_rpt_get_chart_pr`;
DELIMITER $$
CREATE PROCEDURE `virusscan_rpt_get_chart_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN -- To Export All Reports
		SELECT DATE(from_unixtime(incident_date_only)) AS inc_date, SUM(incident_count) AS incident_count
		FROM rpt_virus_chart_summary AS a 
		GROUP BY inc_date ORDER BY a.incident_date_only;
	ELSE
		IF par_username='' THEN
			IF par_client_name <> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT DATE(from_unixtime(incident_date_only)) AS inc_date, SUM(incident_count) AS incident_count
					FROM rpt_virus_chart_summary AS a FORCE INDEX(idx_incident_date_only)
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str) AND a.GroupId=par_group_id
					GROUP BY inc_date ORDER BY a.incident_date_only;
				ELSEIF var_client_count = 1 THEN
					SELECT DATE(from_unixtime(incident_date_only)) AS inc_date, SUM(incident_count) AS incident_count
					FROM rpt_virus_chart_summary AS a FORCE INDEX(idx_incident_date_only)
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str AND a.GroupId=par_group_id
					GROUP BY inc_date ORDER BY a.incident_date_only;
				END IF;
			ELSEIF par_client_name='' AND par_group_id<>0 THEN
				SELECT DATE(from_unixtime(incident_date_only)) AS inc_date, SUM(incident_count) AS incident_count
				FROM rpt_virus_chart_summary AS a FORCE INDEX(idx_incident_date_only)
				WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.GroupId=par_group_id
				GROUP BY inc_date ORDER BY a.incident_date_only;
			ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT DATE(from_unixtime(incident_date_only)) AS inc_date, SUM(incident_count) AS incident_count
					FROM rpt_virus_chart_summary AS a FORCE INDEX(idx_incident_date_only)
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					GROUP BY inc_date ORDER BY a.incident_date_only;
				ELSEIF var_client_count = 1 THEN
					SELECT DATE(from_unixtime(incident_date_only)) AS inc_date, SUM(incident_count) AS incident_count
					FROM rpt_virus_chart_summary AS a FORCE INDEX(idx_incident_date_only)
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str
					GROUP BY inc_date ORDER BY a.incident_date_only;
				END IF;
			ELSEIF par_client_name='' AND par_group_id = 0 THEN
				SELECT DATE(from_unixtime(incident_date_only)) AS inc_date, SUM(incident_count) AS incident_count
				FROM rpt_virus_chart_summary AS a FORCE INDEX(idx_incident_date_only)
				WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				GROUP BY inc_date ORDER BY a.incident_date_only;
			END IF;
		ELSE
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username;
			IF par_client_name <> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master WHERE (par_group_id=0 OR GroupId=par_group_id) AND computer_name=par_client_name;				
				IF var_client_count > 1 THEN
					SELECT DATE(from_unixtime(incident_date_only)) AS inc_date, SUM(incident_count) AS incident_count
					FROM rpt_virus_chart_summary AS a FORCE INDEX(idx_incident_date_only)
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str) 
					AND (par_group_id=0 OR a.GroupId=par_group_id)
					AND a.user_id=var_user_id
					GROUP BY inc_date ORDER BY a.incident_date_only;
				ELSEIF var_client_count = 1 THEN
					SELECT DATE(from_unixtime(incident_date_only)) AS inc_date, SUM(incident_count) AS incident_count
					FROM rpt_virus_chart_summary AS a FORCE INDEX(idx_incident_date_only)
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str 
					AND (par_group_id=0 OR a.GroupId=par_group_id)
					AND a.user_id=var_user_id
					GROUP BY inc_date ORDER BY a.incident_date_only;
				END IF;
			ELSE
				SELECT DATE(from_unixtime(incident_date_only)) AS inc_date, SUM(incident_count) AS incident_count
				FROM rpt_virus_chart_summary AS a FORCE INDEX(idx_incident_date_only)
				WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second) 
				AND (par_group_id=0 OR a.GroupId=par_group_id)
				AND a.user_id=var_user_id
				GROUP BY inc_date ORDER BY a.incident_date_only;
			END IF;
		END IF;
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `virusscan_rpt_get_count_pr`;
DELIMITER $$
CREATE PROCEDURE `virusscan_rpt_get_count_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;	
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN -- To Export All Reports
	
		SELECT IFNULL(SUM(incident_count), 0) AS record_count FROM rpt_virus_chart_summary;
	
	ELSE
		IF par_username='' THEN
			IF par_client_name <> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_virus_chart_summary AS a FORCE INDEX(idx_incident_date_only)
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					AND a.GroupId=par_group_id;
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_virus_chart_summary AS a FORCE INDEX(idx_incident_date_only)
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str 
					AND a.GroupId=par_group_id;
				END IF;
			ELSEIF par_client_name='' AND par_group_id <> 0 THEN
				SELECT IFNULL(IFNULL(SUM(incident_count), 0), 0) AS record_count
				FROM rpt_virus_chart_summary AS a FORCE INDEX(idx_incident_date_only)
				WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.GroupId=par_group_id;
			ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_virus_chart_summary AS a FORCE INDEX(idx_incident_date_only)
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str);
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_virus_chart_summary AS a FORCE INDEX(idx_incident_date_only)
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str;
				END IF;
			ELSEIF par_client_name='' AND par_group_id = 0 THEN
				SELECT IFNULL(SUM(incident_count), 0) AS record_count
				FROM rpt_virus_chart_summary AS a FORCE INDEX(idx_incident_date_only)
				WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second);
			END IF;
		ELSE
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username;
			IF par_client_name <> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master WHERE (par_group_id=0 OR GroupId=par_group_id) AND computer_name=par_client_name;
				IF var_client_count > 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_virus_chart_summary AS a FORCE INDEX(idx_incident_date_only)
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR a.GroupId=par_group_id);
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_virus_chart_summary AS a FORCE INDEX(idx_incident_date_only)
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str 
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR a.GroupId=par_group_id);
				END IF;
			ELSE
				SELECT IFNULL(SUM(incident_count), 0) AS record_count
				FROM rpt_virus_chart_summary AS a FORCE INDEX(idx_incident_date_only)
				WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.user_id=var_user_id
				AND (par_group_id=0 OR a.GroupId=par_group_id);
			END IF;
		END IF;
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `virusscan_rpt_get_table_pr`;
DELIMITER $$
CREATE PROCEDURE `virusscan_rpt_get_table_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;	
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN -- To Export All Reports
		
		SELECT incident_date,
		infected_file,virus_name,action_taken,module,module_id,d.username,
		b.version,infection_source,t1.client_id,computer_name,domain_name,incident_date_in_seconds
		FROM
		(
			SELECT from_unixtime(incident_date) AS incident_date, client_id, virus_scan_id, GroupId, user_id, incident_date AS incident_date_in_seconds
			FROM rpt_virus_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
			ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
		) AS t1, rpt_virus_scan_dim AS b, client_master AS c, rpt_user_master AS d
		WHERE 
		t1.virus_scan_id=b.virus_scan_id AND t1.client_id=c.client_id AND t1.user_id=d.user_id
		ORDER BY incident_date DESC;
		
	ELSE
		IF par_username='' THEN
			IF par_client_name<> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT incident_date,
					infected_file,virus_name,action_taken,module,module_id,d.username,
					b.version,infection_source,t1.client_id,computer_name,domain_name,incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, client_id, virus_scan_id, GroupId, user_id, incident_date AS incident_date_in_seconds
						FROM rpt_virus_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.GroupId = par_group_id
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS t1, rpt_virus_scan_dim AS b, client_master AS c, rpt_user_master AS d
					WHERE 
					t1.virus_scan_id=b.virus_scan_id AND t1.client_id=c.client_id AND t1.user_id=d.user_id
					ORDER BY incident_date DESC;
				ELSEIF var_client_count = 1 THEN
					SELECT incident_date,
					infected_file,virus_name,action_taken,module,module_id,d.username,
					b.version,infection_source,t1.client_id,computer_name,domain_name,incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, client_id, virus_scan_id, GroupId, user_id, incident_date AS incident_date_in_seconds
						FROM rpt_virus_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str
						AND a.GroupId = par_group_id
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS t1, rpt_virus_scan_dim AS b, client_master AS c, rpt_user_master AS d
					WHERE 
					t1.virus_scan_id=b.virus_scan_id AND t1.client_id=c.client_id AND t1.user_id=d.user_id
					ORDER BY incident_date DESC;
				END IF;

			ELSEIF par_client_name='' AND par_group_id<>0 THEN
				SELECT incident_date,
				infected_file,virus_name,action_taken,module,module_id,d.username,
				b.version,infection_source,t1.client_id,computer_name,domain_name,incident_date_in_seconds
				FROM
				(
					SELECT from_unixtime(incident_date) AS incident_date, client_id, virus_scan_id, GroupId, user_id, incident_date AS incident_date_in_seconds
					FROM rpt_virus_incident_fact AS a USE INDEX(idx_incident_date, idx_GroupId)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.GroupId = par_group_id
					ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
				) AS t1, rpt_virus_scan_dim AS b, client_master AS c, rpt_user_master AS d
				WHERE 
				t1.virus_scan_id=b.virus_scan_id AND t1.client_id=c.client_id AND t1.user_id=d.user_id
				ORDER BY incident_date DESC;

			ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT incident_date,
					infected_file,virus_name,action_taken,module,module_id,d.username,
					b.version,infection_source,t1.client_id,computer_name,domain_name,incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, client_id, virus_scan_id, user_id, incident_date AS incident_date_in_seconds
						FROM rpt_virus_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						ORDER BY a.incident_date DESC
						LIMIT par_start_index,par_max_records
					) AS t1, rpt_virus_scan_dim AS b, client_master AS c, rpt_user_master AS d
					WHERE 
					t1.virus_scan_id=b.virus_scan_id AND t1.client_id=c.client_id AND t1.user_id=d.user_id
					ORDER BY incident_date DESC;
				ELSEIF var_client_count = 1 THEN
					SELECT incident_date,
					infected_file,virus_name,action_taken,module,module_id,d.username,
					b.version,infection_source,t1.client_id,computer_name,domain_name,incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, client_id, virus_scan_id, user_id, incident_date AS incident_date_in_seconds
						FROM rpt_virus_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str
						ORDER BY a.incident_date DESC
						LIMIT par_start_index,par_max_records
					) AS t1, rpt_virus_scan_dim AS b, client_master AS c, rpt_user_master AS d
					WHERE 
					t1.virus_scan_id=b.virus_scan_id AND t1.client_id=c.client_id AND t1.user_id=d.user_id
					ORDER BY incident_date DESC;
				END IF;
			ELSEIF par_client_name='' AND par_group_id = 0 THEN
				SELECT incident_date,
				infected_file,virus_name,action_taken,module,module_id,d.username,
				b.version,infection_source,t1.client_id,computer_name,domain_name,incident_date_in_seconds
				FROM
				(
					SELECT from_unixtime(incident_date) AS incident_date, client_id, virus_scan_id, user_id, incident_date AS incident_date_in_seconds
					FROM rpt_virus_incident_fact AS a FORCE INDEX(idx_incident_date) 
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					ORDER BY a.incident_date DESC
					LIMIT par_start_index,par_max_records
				) AS t1, rpt_virus_scan_dim AS b, client_master AS c, rpt_user_master AS d
				WHERE
				t1.virus_scan_id=b.virus_scan_id AND t1.client_id=c.client_id AND t1.user_id=d.user_id
				ORDER BY incident_date DESC;
			END IF;
		
		ELSE
			
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
			IF par_client_name <> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master WHERE (par_group_id=0 OR GroupId=par_group_id) AND computer_name=par_client_name;
				IF var_client_count > 1 THEN
					SELECT incident_date,
					infected_file,virus_name,action_taken,module,module_id,d.username,
					b.version,infection_source,t1.client_id,computer_name,domain_name,incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, client_id, virus_scan_id, GroupId, user_id, incident_date AS incident_date_in_seconds
						FROM rpt_virus_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.user_id=var_user_id
						AND (par_group_id=0 OR a.GroupId = par_group_id)
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS t1, rpt_virus_scan_dim AS b, client_master AS c, rpt_user_master AS d
					WHERE 
					t1.virus_scan_id=b.virus_scan_id AND t1.client_id=c.client_id AND t1.user_id=d.user_id
					ORDER BY incident_date DESC;
				ELSEIF var_client_count = 1 THEN
					SELECT incident_date,
					infected_file,virus_name,action_taken,module,module_id,d.username,
					b.version,infection_source,t1.client_id,computer_name,domain_name,incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, client_id, virus_scan_id, GroupId, user_id, incident_date AS incident_date_in_seconds
						FROM rpt_virus_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str
						AND a.user_id=var_user_id
						AND (par_group_id=0 OR a.GroupId = par_group_id)
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS t1, rpt_virus_scan_dim AS b, client_master AS c, rpt_user_master AS d
					WHERE 
					t1.virus_scan_id=b.virus_scan_id AND t1.client_id=c.client_id AND t1.user_id=d.user_id
					ORDER BY incident_date DESC;
				END IF;
			ELSE
				SELECT incident_date,
				infected_file,virus_name,action_taken,module,module_id,d.username,
				b.version,infection_source,t1.client_id,computer_name,domain_name,incident_date_in_seconds
				FROM
				(
					SELECT from_unixtime(incident_date) AS incident_date, client_id, virus_scan_id, GroupId, user_id, incident_date AS incident_date_in_seconds
					FROM rpt_virus_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR a.GroupId = par_group_id)
					ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
				) AS t1, rpt_virus_scan_dim AS b, client_master AS c, rpt_user_master AS d
				WHERE 
				t1.virus_scan_id=b.virus_scan_id AND t1.client_id=c.client_id AND t1.user_id=d.user_id
				ORDER BY incident_date DESC;
			END IF;
		END IF;
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `vuln_allvuln_rpt_get_count_pr`;
DELIMITER $$
CREATE PROCEDURE `vuln_allvuln_rpt_get_count_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN -- To Export All Reports
		SELECT IFNULL(SUM(incident_count), 0) AS record_count FROM rpt_vuln_topvuln_chart_summary;
	ELSE
		IF par_username='' THEN
			IF par_client_name<> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id, idx_GroupId)
					WHERE
					a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					AND a.GroupId = par_group_id;
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id, idx_GroupId)
					WHERE
					a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id = var_client_ids_str
					AND a.GroupId = par_group_id;
				END IF;

			ELSEIF par_client_name='' AND par_group_id<>0 THEN
				SELECT IFNULL(SUM(incident_count), 0) AS record_count
				FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_GroupId)
				WHERE
				a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.GroupId = par_group_id;

			ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id)
					WHERE
					a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str);
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id)
					WHERE
					a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id = var_client_ids_str;
				END IF;
			ELSEIF par_client_name='' AND par_group_id = 0 THEN
				SELECT IFNULL(SUM(incident_count), 0) AS record_count
				FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only)
				WHERE
				a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second);
			END IF;
		ELSE
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
			IF par_client_name<> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master WHERE (par_group_id=0 OR GroupId=par_group_id) AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id, idx_GroupId, idx_user_id)
					WHERE
					a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR GroupId=par_group_id);
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id, idx_GroupId, idx_user_id)
					WHERE
					a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id = var_client_ids_str
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR GroupId=par_group_id);
				END IF;
			ELSE
				SELECT IFNULL(SUM(incident_count), 0) AS record_count
				FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_GroupId, idx_user_id)
				WHERE
				a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.user_id=var_user_id
				AND (par_group_id=0 OR GroupId=par_group_id);
			END IF;
		END IF;
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `vuln_rpt_get_affected_platforms_pr`;
DELIMITER $$
CREATE PROCEDURE `vuln_rpt_get_affected_platforms_pr`(
	IN par_cve_id CHAR(14)
)
BEGIN

	SET time_zone = '+00:00';
	
	SELECT platform_name 
	FROM rpt_vuln_affected_platforms_dim
	WHERE cve_id = par_cve_id;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `vuln_rpt_get_affected_products_pr`;
DELIMITER $$
CREATE PROCEDURE `vuln_rpt_get_affected_products_pr`(
	IN par_cve_id CHAR(14)
)
BEGIN

	SET time_zone = '+00:00';
	
	SELECT product_name 
	FROM rpt_vuln_affected_products_dim
	WHERE cve_id = par_cve_id;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `vuln_rpt_get_references_pr`;
DELIMITER $$
CREATE PROCEDURE `vuln_rpt_get_references_pr`(
	IN par_cve_id CHAR(14)
)
BEGIN

	SET time_zone = '+00:00';
	
	SELECT CONCAT(source_name, ': ', reference_name) AS reference
	FROM rpt_vuln_references_dim
	WHERE cve_id = par_cve_id;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `vuln_rpt_get_table_pr`;
DELIMITER $$
CREATE PROCEDURE `vuln_rpt_get_table_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512),
	IN par_vendor_id INT(2),
	IN par_severity INT(2),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN -- To Export All Reports
	
		SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
		scan_type, cve_id, vuln_title, a.severity, base_metrics, 
		vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, a.rowid
		FROM
		(
			SELECT from_unixtime(incident_date) AS incident_date, 
			client_id, user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
			FROM rpt_vuln_incident_fact AS a 
			ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
		) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
		WHERE 
		a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
		ORDER BY incident_date DESC;
	
	ELSE
		IF par_username='' THEN
			IF par_vendor_id <> 0 THEN
				IF par_client_name<> '' AND par_group_id <> 0 THEN
					SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
					
					IF var_client_count > 1 THEN
						SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
						scan_type, cve_id, vuln_title, a.severity, base_metrics, 
						vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
						FROM
						(
							SELECT from_unixtime(incident_date) AS incident_date, 
							client_id,user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
							FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
							WHERE
							a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
							AND FIND_IN_SET(a.client_id, var_client_ids_str)
							AND a.GroupId = par_group_id
							AND a.vendor_id = par_vendor_id
							ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
						) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
						WHERE 
						a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
						ORDER BY incident_date DESC;
					ELSEIF var_client_count = 1 THEN
						SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
						scan_type, cve_id, vuln_title, a.severity, base_metrics, 
						vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
						FROM
						(
							SELECT from_unixtime(incident_date) AS incident_date, 
							client_id, user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
							FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
							WHERE
							a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
							AND a.client_id = var_client_ids_str
							AND a.GroupId = par_group_id
							AND a.vendor_id = par_vendor_id
							ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
						) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
						WHERE 
						a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
						ORDER BY incident_date DESC;
					END IF;

				ELSEIF par_client_name='' AND par_group_id<>0 THEN
					SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
					scan_type, cve_id, vuln_title, a.severity, base_metrics, 
					vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, 
						client_id, user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
						FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.GroupId = par_group_id
						AND a.vendor_id = par_vendor_id
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
					WHERE 
					a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
					ORDER BY incident_date DESC;

				ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
					SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
					
					IF var_client_count > 1 THEN
						SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
						scan_type, cve_id, vuln_title, a.severity, base_metrics, 
						vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
						FROM
						(
							SELECT from_unixtime(incident_date) AS incident_date, 
							client_id, user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
							FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
							WHERE
							a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
							AND FIND_IN_SET(a.client_id, var_client_ids_str)
							AND a.vendor_id = par_vendor_id
							ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
						) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
						WHERE 
						a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
						ORDER BY incident_date DESC;
					ELSEIF var_client_count = 1 THEN
						SELECT incident_date, a.client_id, a.user_id, e.username, computer_name, domain_name, 
						scan_type, cve_id, vuln_title, a.severity, base_metrics, 
						vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
						FROM
						(
							SELECT from_unixtime(incident_date) AS incident_date, 
							client_id, user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
							FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
							WHERE
							a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
							AND a.client_id = var_client_ids_str
							AND a.vendor_id = par_vendor_id
							ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
						) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
						WHERE 
						a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
						ORDER BY incident_date DESC;
					END IF;
				ELSEIF par_client_name='' AND par_group_id = 0 THEN
					SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
					scan_type, cve_id, vuln_title, a.severity, base_metrics, 
					vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, 
						client_id, user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
						FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.vendor_id = par_vendor_id
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
					WHERE 
					a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
					ORDER BY incident_date DESC;
				END IF;
			
			ELSEIF par_severity <> 0 THEN
				IF par_client_name<> '' AND par_group_id <> 0 THEN
					SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
					
					IF var_client_count > 1 THEN
						SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
						scan_type, cve_id, vuln_title, a.severity, base_metrics, 
						vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
						FROM
						(
							SELECT from_unixtime(incident_date) AS incident_date, 
							client_id, user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
							FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
							WHERE
							a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
							AND FIND_IN_SET(a.client_id, var_client_ids_str)
							AND a.GroupId = par_group_id
							AND a.severity = par_severity
							ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
						) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
						WHERE 
						a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
						ORDER BY incident_date DESC;
					ELSEIF var_client_count = 1 THEN
						SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
						scan_type, cve_id, vuln_title, a.severity, base_metrics, 
						vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
						FROM
						(
							SELECT from_unixtime(incident_date) AS incident_date, 
							client_id, user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
							FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
							WHERE
							a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
							AND a.client_id = var_client_ids_str
							AND a.GroupId = par_group_id
							AND a.severity = par_severity
							ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
						) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
						WHERE 
						a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
						ORDER BY incident_date DESC;
					END IF;

				ELSEIF par_client_name='' AND par_group_id<>0 THEN
					SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
					scan_type, cve_id, vuln_title, a.severity, base_metrics, 
					vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, 
						client_id, user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
						FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.GroupId = par_group_id
						AND a.severity = par_severity
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
					WHERE 
					a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
					ORDER BY incident_date DESC;

				ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
					SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
					
					IF var_client_count > 1 THEN
						SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
						scan_type, cve_id, vuln_title, a.severity, base_metrics, 
						vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
						FROM
						(
							SELECT from_unixtime(incident_date) AS incident_date, 
							client_id, user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
							FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
							WHERE
							a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
							AND FIND_IN_SET(a.client_id, var_client_ids_str)
							AND a.severity = par_severity
							ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
						) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
						WHERE 
						a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
						ORDER BY incident_date DESC;
					ELSEIF var_client_count = 1 THEN
						SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
						scan_type, cve_id, vuln_title, a.severity, base_metrics, 
						vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
						FROM
						(
							SELECT from_unixtime(incident_date) AS incident_date, 
							client_id, user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
							FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
							WHERE
							a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
							AND a.client_id = var_client_ids_str
							AND a.severity = par_severity
							ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
						) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
						WHERE 
						a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
						ORDER BY incident_date DESC;
					END IF;
				ELSEIF par_client_name='' AND par_group_id = 0 THEN
					SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
					scan_type, cve_id, vuln_title, a.severity, base_metrics, 
					vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, 
						client_id, user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
						FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.severity = par_severity
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
					WHERE 
					a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
					ORDER BY incident_date DESC;
				END IF;
			
			ELSE
				IF par_client_name<> '' AND par_group_id <> 0 THEN
					SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
					
					IF var_client_count > 1 THEN
						SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
						scan_type, cve_id, vuln_title, a.severity, base_metrics, 
						vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
						FROM
						(
							SELECT from_unixtime(incident_date) AS incident_date, 
							client_id, user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
							FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
							WHERE
							a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
							AND FIND_IN_SET(a.client_id, var_client_ids_str)
							AND a.GroupId = par_group_id
							ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
						) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
						WHERE 
						a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
						ORDER BY incident_date DESC;
					ELSEIF var_client_count = 1 THEN
						SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
						scan_type, cve_id, vuln_title, a.severity, base_metrics, 
						vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
						FROM
						(
							SELECT from_unixtime(incident_date) AS incident_date, 
							client_id, user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
							FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
							WHERE
							a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
							AND a.client_id = var_client_ids_str
							AND a.GroupId = par_group_id
							ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
						) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
						WHERE 
						a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
						ORDER BY incident_date DESC;
					END IF;

				ELSEIF par_client_name='' AND par_group_id<>0 THEN
					SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
					scan_type, cve_id, vuln_title, a.severity, base_metrics, 
					vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, 
						client_id, user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
						FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.GroupId = par_group_id
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
					WHERE 
					a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
					ORDER BY incident_date DESC;

				ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
					SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
					
					IF var_client_count > 1 THEN
						SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
						scan_type, cve_id, vuln_title, a.severity, base_metrics, 
						vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
						FROM
						(
							SELECT from_unixtime(incident_date) AS incident_date, 
							client_id, user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
							FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
							WHERE
							a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
							AND FIND_IN_SET(a.client_id, var_client_ids_str)
							ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
						) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
						WHERE 
						a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
						ORDER BY incident_date DESC;
					ELSEIF var_client_count = 1 THEN
						SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
						scan_type, cve_id, vuln_title, a.severity, base_metrics, 
						vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
						FROM
						(
							SELECT from_unixtime(incident_date) AS incident_date, 
							client_id, user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
							FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
							WHERE
							a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
							AND a.client_id = var_client_ids_str
							ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
						) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
						WHERE 
						a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
						ORDER BY incident_date DESC;
					END IF;
				ELSEIF par_client_name='' AND par_group_id = 0 THEN
					SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
					scan_type, cve_id, vuln_title, a.severity, base_metrics, 
					vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, 
						client_id, user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
						FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
					WHERE 
					a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
					ORDER BY incident_date DESC;
				END IF;
			END IF;
		ELSE
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
			IF par_client_name<> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master WHERE (par_group_id=0 OR GroupId=par_group_id) AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
					scan_type, cve_id, vuln_title, a.severity, base_metrics, 
					vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, 
						client_id,user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
						FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId, idx_user_id)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.user_id = var_user_id
						AND (par_group_id=0 OR a.GroupId = par_group_id)
						AND (par_vendor_id=0 OR a.vendor_id = par_vendor_id)
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
					WHERE 
					a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
					ORDER BY incident_date DESC;
				ELSEIF var_client_count = 1 THEN
					SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
					scan_type, cve_id, vuln_title, a.severity, base_metrics, 
					vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, 
						client_id, user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
						FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId, idx_user_id)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id = var_client_ids_str
						AND a.user_id = var_user_id
						AND (par_group_id=0 OR a.GroupId = par_group_id)
						AND (par_vendor_id=0 OR a.vendor_id = par_vendor_id)
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
					WHERE 
					a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
					ORDER BY incident_date DESC;
				END IF;
			ELSE
				SELECT incident_date, a.client_id, a.user_id, computer_name, e.username, domain_name, 
				scan_type, cve_id, vuln_title, a.severity, base_metrics, 
				vendor_name, description, a.vuln_id, cve_id, incident_date_in_seconds, rowid
				FROM
				(
					SELECT from_unixtime(incident_date) AS incident_date, 
					client_id,user_id, scan_type, severity, vendor_id, vuln_id, GroupId, incident_date AS incident_date_in_seconds, rowid
					FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_GroupId, idx_user_id)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.user_id = var_user_id
					AND (par_group_id=0 OR a.GroupId = par_group_id)
					AND (par_vendor_id=0 OR a.vendor_id = par_vendor_id)
					ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
				) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, rpt_user_master AS e
				WHERE 
				a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.vendor_id=d.vendor_id AND a.user_id=e.user_id
				ORDER BY incident_date DESC;
			END IF;
		END IF;	
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `vuln_rpt_get_topvuln_clients_pr`;
DELIMITER $$
CREATE PROCEDURE `vuln_rpt_get_topvuln_clients_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512),
	IN par_vuln_id INT(20),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF par_username='' THEN
		IF par_client_name<> '' AND par_group_id <> 0 THEN
			SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
			
			IF var_client_count > 1 THEN
				SELECT computer_name, e.username, domain_name, OsVersion
				FROM
				(
					SELECT DISTINCT client_id AS client_id, user_id
					FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					AND a.GroupId = par_group_id
					AND a.vuln_id = par_vuln_id
					ORDER BY a.client_id DESC LIMIT par_start_index,par_max_records
				) AS a, client_master AS c, clientos AS d, rpt_user_master AS e
				WHERE 
				a.client_id=c.client_id AND c.guid=d.Guid AND a.user_id=e.user_id
				ORDER BY a.client_id DESC;
			ELSEIF var_client_count = 1 THEN
				SELECT computer_name, e.username, domain_name, OsVersion
				FROM
				(
					SELECT DISTINCT client_id AS client_id, user_id
					FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id = var_client_ids_str
					AND a.GroupId = par_group_id
					AND a.vuln_id = par_vuln_id
					ORDER BY a.client_id DESC LIMIT par_start_index,par_max_records
				) AS a, client_master AS c, clientos AS d, rpt_user_master AS e
				WHERE 
				a.client_id=c.client_id AND c.guid=d.Guid AND a.user_id=e.user_id
				ORDER BY a.client_id DESC;
			END IF;

		ELSEIF par_client_name='' AND par_group_id<>0 THEN
			SELECT computer_name, e.username, domain_name, OsVersion
			FROM
			(
				SELECT DISTINCT client_id AS client_id, user_id
				FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
				WHERE
				a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.GroupId = par_group_id
				AND a.vuln_id = par_vuln_id
				ORDER BY a.client_id DESC LIMIT par_start_index,par_max_records
			) AS a, client_master AS c, clientos AS d, rpt_user_master AS e
			WHERE 
			a.client_id=c.client_id AND c.guid=d.Guid AND a.user_id=e.user_id
			ORDER BY a.client_id DESC;

		ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
			SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
			
			IF var_client_count > 1 THEN
				SELECT computer_name, e.username, domain_name, OsVersion
				FROM
				(
					SELECT DISTINCT client_id AS client_id, user_id
					FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					AND a.vuln_id = par_vuln_id
					ORDER BY a.client_id DESC LIMIT par_start_index,par_max_records
				) AS a, client_master AS c, clientos AS d, rpt_user_master AS e
				WHERE 
				a.client_id=c.client_id AND c.guid=d.Guid AND a.user_id=e.user_id
				ORDER BY a.client_id DESC;
			ELSEIF var_client_count = 1 THEN
				SELECT computer_name, e.username, domain_name, OsVersion
				FROM
				(
					SELECT DISTINCT client_id AS client_id, user_id
					FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id = var_client_ids_str
					AND a.vuln_id = par_vuln_id
					ORDER BY a.client_id DESC LIMIT par_start_index,par_max_records
				) AS a, client_master AS c, clientos AS d, rpt_user_master AS e
				WHERE 
				a.client_id=c.client_id AND c.guid=d.Guid AND a.user_id=e.user_id
				ORDER BY a.client_id DESC;
			END IF;
		ELSEIF par_client_name='' AND par_group_id = 0 THEN
			SELECT computer_name, e.username, domain_name, OsVersion
			FROM
			(
				SELECT DISTINCT client_id AS client_id, user_id
				FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
				WHERE
				a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.vuln_id = par_vuln_id
				ORDER BY a.client_id DESC LIMIT par_start_index,par_max_records
			) AS a, client_master AS c, clientos AS d, rpt_user_master AS e
			WHERE 
			a.client_id=c.client_id AND c.guid=d.Guid AND a.user_id=e.user_id
			ORDER BY a.client_id DESC;
		END IF;
	ELSE
		SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
		IF par_client_name<> '' THEN
			SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
			FROM client_master WHERE (par_group_id=0 OR GroupId=par_group_id) AND computer_name=par_client_name;
			IF var_client_count > 1 THEN
				SELECT computer_name, e.username, domain_name, OsVersion
				FROM
				(
					SELECT DISTINCT client_id AS client_id, user_id
					FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId, idx_user_id)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					AND a.user_id = var_user_id
					AND (par_group_id=0 OR GroupId=par_group_id)
					AND (par_vuln_id=0 OR a.vuln_id = par_vuln_id)
					ORDER BY a.client_id DESC LIMIT par_start_index,par_max_records
				) AS a, client_master AS c, clientos AS d, rpt_user_master AS e
				WHERE 
				a.client_id=c.client_id AND c.guid=d.Guid AND a.user_id=e.user_id
				ORDER BY a.client_id DESC;
			ELSEIF var_client_count = 1 THEN
				SELECT computer_name, e.username, domain_name, OsVersion
				FROM
				(
					SELECT DISTINCT client_id AS client_id, user_id
					FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId, idx_user_id)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id = var_client_ids_str
					AND a.user_id = var_user_id
					AND (par_group_id=0 OR GroupId=par_group_id)
					AND (par_vuln_id=0 OR a.vuln_id = par_vuln_id)
					ORDER BY a.client_id DESC LIMIT par_start_index,par_max_records
				) AS a, client_master AS c, clientos AS d, rpt_user_master AS e
				WHERE 
				a.client_id=c.client_id AND c.guid=d.Guid AND a.user_id=e.user_id
				ORDER BY a.client_id DESC;
			END IF;
		ELSE
			SELECT computer_name, e.username, domain_name, OsVersion
			FROM
			(
				SELECT DISTINCT client_id AS client_id, user_id
				FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_GroupId, idx_user_id)
				WHERE
				a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.user_id = var_user_id
				AND (par_group_id=0 OR GroupId=par_group_id)
				AND (par_vuln_id=0 OR a.vuln_id = par_vuln_id)
				ORDER BY a.client_id DESC LIMIT par_start_index,par_max_records
			) AS a, client_master AS c, clientos AS d, rpt_user_master AS e
			WHERE 
			a.client_id=c.client_id AND c.guid=d.Guid AND a.user_id=e.user_id
			ORDER BY a.client_id DESC;
		END IF;
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `vuln_rpt_get_vuln_details_pr`;
DELIMITER $$
CREATE PROCEDURE `vuln_rpt_get_vuln_details_pr`(
	IN par_rowid BIGINT(20),
	IN par_client_id BIGINT(20),
	IN par_user_id BIGINT(20)
)
BEGIN

	SET time_zone = '+00:00';
	IF par_client_id <> 0 THEN
		SELECT incident_date, a.client_id, computer_name, domain_name, OsVersion, 
		f.username, scan_type, cve_id, vuln_title, a.severity, base_metrics, 
		vendor_name, description, incident_date_in_seconds
		FROM
		(
			SELECT from_unixtime(incident_date) AS incident_date, 
			client_id, scan_type, severity, vendor_id, vuln_id, GroupId, user_id, incident_date AS incident_date_in_seconds
			FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
			WHERE a.`rowid` = par_rowid AND client_id=par_client_id AND a.user_id=par_user_id
		) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, clientos AS e, rpt_user_master AS f
		WHERE 
		a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.user_id=f.user_id
		AND a.vendor_id=d.vendor_id AND c.guid=e.Guid
		LIMIT 1;
	ELSE
		SELECT incident_date, a.client_id, computer_name, domain_name, OsVersion, 
		f.username, scan_type, cve_id, vuln_title, a.severity, base_metrics, 
		vendor_name, description, incident_date_in_seconds
		FROM
		(
			SELECT from_unixtime(incident_date) AS incident_date, 
			client_id, scan_type, severity, vendor_id, vuln_id, GroupId, user_id, incident_date AS incident_date_in_seconds
			FROM rpt_vuln_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
			WHERE a.`rowid` = par_rowid
		) AS a, rpt_vuln_master_dim AS b, client_master AS c, rpt_vuln_vendor_master_dim As d, clientos AS e, rpt_user_master AS f
		WHERE 
		a.vuln_id=b.vuln_id AND a.client_id=c.client_id AND a.user_id=f.user_id
		AND a.vendor_id=d.vendor_id AND c.guid=e.Guid
		LIMIT 1;
    END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `vuln_severity_rpt_get_chart_pr`;
DELIMITER $$
CREATE PROCEDURE `vuln_severity_rpt_get_chart_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN -- To Export All Reports
		SELECT 
		IFNULL((low_severity_record_count * 100) / total_record_count, 0) AS low_severity_percentage,
		IFNULL((medium_severity_record_count * 100) / total_record_count, 0) AS medium_severity_percentage,
		IFNULL((high_severity_record_count * 100) / total_record_count, 0) AS high_severity_percentage
		FROM
		(
			SELECT
			IFNULL(SUM(incident_count), 0) AS total_record_count,
			IFNULL(SUM(CASE WHEN severity = 1 THEN incident_count ELSE 0 END), 0) AS low_severity_record_count,
			IFNULL(SUM(CASE WHEN severity = 2 THEN incident_count ELSE 0 END), 0) AS medium_severity_record_count,
			IFNULL(SUM(CASE WHEN severity = 3 THEN incident_count ELSE 0 END), 0) AS high_severity_record_count
			FROM rpt_vuln_severity_chart_summary AS a
		) AS a;
	ELSE
		IF par_username='' THEN
			IF par_client_name <> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT 
					IFNULL((low_severity_record_count * 100) / total_record_count, 0) AS low_severity_percentage,
					IFNULL((medium_severity_record_count * 100) / total_record_count, 0) AS medium_severity_percentage,
					IFNULL((high_severity_record_count * 100) / total_record_count, 0) AS high_severity_percentage
					FROM
					(
						SELECT
						IFNULL(SUM(incident_count), 0) AS total_record_count,
						IFNULL(SUM(CASE WHEN severity = 1 THEN incident_count ELSE 0 END), 0) AS low_severity_record_count,
						IFNULL(SUM(CASE WHEN severity = 2 THEN incident_count ELSE 0 END), 0) AS medium_severity_record_count,
						IFNULL(SUM(CASE WHEN severity = 3 THEN incident_count ELSE 0 END), 0) AS high_severity_record_count
						FROM rpt_vuln_severity_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.GroupId=par_group_id
					) AS a;
				ELSEIF var_client_count = 1 THEN
					SELECT 
					IFNULL((low_severity_record_count * 100) / total_record_count, 0) AS low_severity_percentage,
					IFNULL((medium_severity_record_count * 100) / total_record_count, 0) AS medium_severity_percentage,
					IFNULL((high_severity_record_count * 100) / total_record_count, 0) AS high_severity_percentage
					FROM
					(
						SELECT
						IFNULL(SUM(incident_count), 0) AS total_record_count,
						IFNULL(SUM(CASE WHEN severity = 1 THEN incident_count ELSE 0 END), 0) AS low_severity_record_count,
						IFNULL(SUM(CASE WHEN severity = 2 THEN incident_count ELSE 0 END), 0) AS medium_severity_record_count,
						IFNULL(SUM(CASE WHEN severity = 3 THEN incident_count ELSE 0 END), 0) AS high_severity_record_count
						FROM rpt_vuln_severity_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str 
						AND a.GroupId=par_group_id
					) AS a;
				END IF;
			ELSEIF par_client_name='' AND par_group_id <> 0 THEN
				SELECT 
				IFNULL((low_severity_record_count * 100) / total_record_count, 0) AS low_severity_percentage,
				IFNULL((medium_severity_record_count * 100) / total_record_count, 0) AS medium_severity_percentage,
				IFNULL((high_severity_record_count * 100) / total_record_count, 0) AS high_severity_percentage
				FROM
				(
					SELECT
					IFNULL(SUM(incident_count), 0) AS total_record_count,
					IFNULL(SUM(CASE WHEN severity = 1 THEN incident_count ELSE 0 END), 0) AS low_severity_record_count,
					IFNULL(SUM(CASE WHEN severity = 2 THEN incident_count ELSE 0 END), 0) AS medium_severity_record_count,
					IFNULL(SUM(CASE WHEN severity = 3 THEN incident_count ELSE 0 END), 0) AS high_severity_record_count
					FROM rpt_vuln_severity_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.GroupId=par_group_id
				) AS a;
			ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT 
					IFNULL((low_severity_record_count * 100) / total_record_count, 0) AS low_severity_percentage,
					IFNULL((medium_severity_record_count * 100) / total_record_count, 0) AS medium_severity_percentage,
					IFNULL((high_severity_record_count * 100) / total_record_count, 0) AS high_severity_percentage
					FROM
					(
						SELECT
						IFNULL(SUM(incident_count), 0) AS total_record_count,
						IFNULL(SUM(CASE WHEN severity = 1 THEN incident_count ELSE 0 END), 0) AS low_severity_record_count,
						IFNULL(SUM(CASE WHEN severity = 2 THEN incident_count ELSE 0 END), 0) AS medium_severity_record_count,
						IFNULL(SUM(CASE WHEN severity = 3 THEN incident_count ELSE 0 END), 0) AS high_severity_record_count
						FROM rpt_vuln_severity_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
					) AS a;
				ELSEIF var_client_count = 1 THEN
					SELECT 
					IFNULL((low_severity_record_count * 100) / total_record_count, 0) AS low_severity_percentage,
					IFNULL((medium_severity_record_count * 100) / total_record_count, 0) AS medium_severity_percentage,
					IFNULL((high_severity_record_count * 100) / total_record_count, 0) AS high_severity_percentage
					FROM
					(
						SELECT
						IFNULL(SUM(incident_count), 0) AS total_record_count,
						IFNULL(SUM(CASE WHEN severity = 1 THEN incident_count ELSE 0 END), 0) AS low_severity_record_count,
						IFNULL(SUM(CASE WHEN severity = 2 THEN incident_count ELSE 0 END), 0) AS medium_severity_record_count,
						IFNULL(SUM(CASE WHEN severity = 3 THEN incident_count ELSE 0 END), 0) AS high_severity_record_count
						FROM rpt_vuln_severity_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str
					) AS a;
				END IF;
			ELSEIF par_client_name='' AND par_group_id = 0 THEN
				SELECT 
				IFNULL((low_severity_record_count * 100) / total_record_count, 0) AS low_severity_percentage,
				IFNULL((medium_severity_record_count * 100) / total_record_count, 0) AS medium_severity_percentage,
				IFNULL((high_severity_record_count * 100) / total_record_count, 0) AS high_severity_percentage
				FROM
				(
					SELECT
					IFNULL(SUM(incident_count), 0) AS total_record_count,
					IFNULL(SUM(CASE WHEN severity = 1 THEN incident_count ELSE 0 END), 0) AS low_severity_record_count,
					IFNULL(SUM(CASE WHEN severity = 2 THEN incident_count ELSE 0 END), 0) AS medium_severity_record_count,
					IFNULL(SUM(CASE WHEN severity = 3 THEN incident_count ELSE 0 END), 0) AS high_severity_record_count
					FROM rpt_vuln_severity_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				) AS a;
			END IF;
		ELSE
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
			IF par_client_name <> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master WHERE (par_group_id=0 OR GroupId=par_group_id) AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT 
					IFNULL((low_severity_record_count * 100) / total_record_count, 0) AS low_severity_percentage,
					IFNULL((medium_severity_record_count * 100) / total_record_count, 0) AS medium_severity_percentage,
					IFNULL((high_severity_record_count * 100) / total_record_count, 0) AS high_severity_percentage
					FROM
					(
						SELECT
						IFNULL(SUM(incident_count), 0) AS total_record_count,
						IFNULL(SUM(CASE WHEN severity = 1 THEN incident_count ELSE 0 END), 0) AS low_severity_record_count,
						IFNULL(SUM(CASE WHEN severity = 2 THEN incident_count ELSE 0 END), 0) AS medium_severity_record_count,
						IFNULL(SUM(CASE WHEN severity = 3 THEN incident_count ELSE 0 END), 0) AS high_severity_record_count
						FROM rpt_vuln_severity_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.user_id = var_user_id
						AND (par_group_id=0 OR a.GroupId=par_group_id)
					) AS a;
				ELSEIF var_client_count = 1 THEN
					SELECT 
					IFNULL((low_severity_record_count * 100) / total_record_count, 0) AS low_severity_percentage,
					IFNULL((medium_severity_record_count * 100) / total_record_count, 0) AS medium_severity_percentage,
					IFNULL((high_severity_record_count * 100) / total_record_count, 0) AS high_severity_percentage
					FROM
					(
						SELECT
						IFNULL(SUM(incident_count), 0) AS total_record_count,
						IFNULL(SUM(CASE WHEN severity = 1 THEN incident_count ELSE 0 END), 0) AS low_severity_record_count,
						IFNULL(SUM(CASE WHEN severity = 2 THEN incident_count ELSE 0 END), 0) AS medium_severity_record_count,
						IFNULL(SUM(CASE WHEN severity = 3 THEN incident_count ELSE 0 END), 0) AS high_severity_record_count
						FROM rpt_vuln_severity_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str 
						AND a.user_id = var_user_id
						AND (par_group_id=0 OR a.GroupId=par_group_id)
					) AS a;
				END IF;
			ELSE
				SELECT 
				IFNULL((low_severity_record_count * 100) / total_record_count, 0) AS low_severity_percentage,
				IFNULL((medium_severity_record_count * 100) / total_record_count, 0) AS medium_severity_percentage,
				IFNULL((high_severity_record_count * 100) / total_record_count, 0) AS high_severity_percentage
				FROM
				(
					SELECT
					IFNULL(SUM(incident_count), 0) AS total_record_count,
					IFNULL(SUM(CASE WHEN severity = 1 THEN incident_count ELSE 0 END), 0) AS low_severity_record_count,
					IFNULL(SUM(CASE WHEN severity = 2 THEN incident_count ELSE 0 END), 0) AS medium_severity_record_count,
					IFNULL(SUM(CASE WHEN severity = 3 THEN incident_count ELSE 0 END), 0) AS high_severity_record_count
					FROM rpt_vuln_severity_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.user_id = var_user_id
					AND (par_group_id=0 OR a.GroupId=par_group_id)
				) AS a;
			END IF;
		END IF;
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `vuln_severity_rpt_get_count_pr`;
DELIMITER $$
CREATE PROCEDURE `vuln_severity_rpt_get_count_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512),
	IN par_severity INT(2)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN -- To Export All Reports
		SELECT IFNULL(SUM(incident_count), 0) AS record_count FROM rpt_vuln_severity_chart_summary;
	ELSE
		IF par_username='' THEN
			IF par_severity <> 0 THEN
				IF par_client_name <> '' AND par_group_id <> 0 THEN
					SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
					
					IF var_client_count > 1 THEN
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_severity_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.GroupId=par_group_id
						AND a.severity = par_severity;
					ELSEIF var_client_count = 1 THEN
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_severity_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str 
						AND a.GroupId=par_group_id
						AND a.severity = par_severity;
					END IF;
				ELSEIF par_client_name='' AND par_group_id <> 0 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_severity_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.GroupId=par_group_id
					AND a.severity = par_severity;
				ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
					SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
					
					IF var_client_count > 1 THEN
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_severity_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.severity = par_severity;
					ELSEIF var_client_count = 1 THEN
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_severity_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str
						AND a.severity = par_severity;
					END IF;
				ELSEIF par_client_name='' AND par_group_id = 0 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_severity_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.severity = par_severity;
				END IF;
			
			ELSE
				IF par_client_name <> '' AND par_group_id <> 0 THEN
					SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
					
					IF var_client_count > 1 THEN
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_severity_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.GroupId=par_group_id;
					ELSEIF var_client_count = 1 THEN
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_severity_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str 
						AND a.GroupId=par_group_id;
					END IF;
				ELSEIF par_client_name='' AND par_group_id <> 0 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_severity_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.GroupId=par_group_id;
				ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
					SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
					
					IF var_client_count > 1 THEN
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_severity_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str);
					ELSEIF var_client_count = 1 THEN
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_severity_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str;
					END IF;
				ELSEIF par_client_name='' AND par_group_id = 0 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_severity_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second);
				END IF;
			END IF;
		ELSE
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
			IF par_client_name <> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master WHERE (par_group_id=0 OR GroupId=par_group_id) AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_severity_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR GroupId=par_group_id)
					AND (par_severity=0 OR a.severity = par_severity);
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_severity_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str 
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR GroupId=par_group_id)
					AND (par_severity=0 OR a.severity = par_severity);
				END IF;
			ELSE
				SELECT IFNULL(SUM(incident_count), 0) AS record_count
				FROM rpt_vuln_severity_chart_summary AS a
				WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.user_id=var_user_id
				AND (par_group_id=0 OR GroupId=par_group_id)
				AND (par_severity=0 OR a.severity = par_severity);
			END IF;
		END IF;
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `vuln_topvuln_rpt_get_chart_pr`;
DELIMITER $$
CREATE PROCEDURE `vuln_topvuln_rpt_get_chart_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_total_record_count BIGINT(20) DEFAULT 0;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN -- To Export All Reports
		SET var_total_record_count = (
			SELECT IFNULL(SUM(incident_count), 0) AS record_count
			FROM rpt_vuln_topvuln_chart_summary AS a
		);
		SELECT cve_id, incident_count, var_total_record_count AS total_record_count
		FROM
		(
			SELECT IFNULL(SUM(incident_count), 0) AS incident_count, vuln_id
			FROM rpt_vuln_topvuln_chart_summary AS a
			GROUP BY vuln_id
			ORDER BY incident_count DESC LIMIT 5
		) AS a, rpt_vuln_master_dim AS b
		WHERE a.vuln_id = b.vuln_id;
	ELSE
		IF par_username='' THEN
			IF par_client_name <> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SET var_total_record_count = (
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_topvuln_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.GroupId=par_group_id
					);
					SELECT cve_id, incident_count, var_total_record_count AS total_record_count
					FROM
					(
						SELECT IFNULL(SUM(incident_count), 0) AS incident_count, vuln_id
						FROM rpt_vuln_topvuln_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.GroupId=par_group_id
						GROUP BY vuln_id
						ORDER BY incident_count DESC LIMIT 5
					) AS a, rpt_vuln_master_dim AS b
					WHERE a.vuln_id = b.vuln_id;
				ELSEIF var_client_count = 1 THEN
					SET var_total_record_count = (
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_topvuln_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str 
						AND a.GroupId=par_group_id
					);
					SELECT cve_id, incident_count, var_total_record_count AS total_record_count
					FROM
					(
						SELECT IFNULL(SUM(incident_count), 0) AS incident_count, vuln_id
						FROM rpt_vuln_topvuln_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str 
						AND a.GroupId=par_group_id
						GROUP BY vuln_id
						ORDER BY incident_count DESC LIMIT 5
					) AS a, rpt_vuln_master_dim AS b
					WHERE a.vuln_id = b.vuln_id;
				END IF;
			ELSEIF par_client_name='' AND par_group_id <> 0 THEN
				SET var_total_record_count = (
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_topvuln_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second) 
					AND a.GroupId=par_group_id
				);
				SELECT cve_id, incident_count, var_total_record_count AS total_record_count
				FROM
				(
					SELECT IFNULL(SUM(incident_count), 0) AS incident_count, vuln_id
					FROM rpt_vuln_topvuln_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.GroupId=par_group_id
					GROUP BY vuln_id
					ORDER BY incident_count DESC LIMIT 5
				) AS a, rpt_vuln_master_dim AS b
				WHERE a.vuln_id = b.vuln_id;
			ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SET var_total_record_count = (
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_topvuln_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
					);
					SELECT cve_id, incident_count, var_total_record_count AS total_record_count
					FROM
					(
						SELECT IFNULL(SUM(incident_count), 0) AS incident_count, vuln_id
						FROM rpt_vuln_topvuln_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						GROUP BY vuln_id
						ORDER BY incident_count DESC LIMIT 5
					) AS a, rpt_vuln_master_dim AS b
					WHERE a.vuln_id = b.vuln_id;
				ELSEIF var_client_count = 1 THEN
					SET var_total_record_count = (
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_topvuln_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str
					);
					SELECT cve_id, incident_count, var_total_record_count AS total_record_count
					FROM
					(
						SELECT IFNULL(SUM(incident_count), 0) AS incident_count, vuln_id
						FROM rpt_vuln_topvuln_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str
						GROUP BY vuln_id
						ORDER BY incident_count DESC LIMIT 5
					) AS a, rpt_vuln_master_dim AS b
					WHERE a.vuln_id = b.vuln_id;
				END IF;
			ELSEIF par_client_name='' AND par_group_id = 0 THEN
				SET var_total_record_count = (
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_topvuln_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				);
				SELECT cve_id, incident_count, var_total_record_count AS total_record_count
				FROM
				(
					SELECT IFNULL(SUM(incident_count), 0) AS incident_count, vuln_id
					FROM rpt_vuln_topvuln_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					GROUP BY vuln_id
					ORDER BY incident_count DESC LIMIT 5
				) AS a, rpt_vuln_master_dim AS b
				WHERE a.vuln_id = b.vuln_id;
			END IF;
		ELSE
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
			IF par_client_name <> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master WHERE (par_group_id=0 OR GroupId=par_group_id) AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SET var_total_record_count = (
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_topvuln_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.user_id=var_user_id
						AND (par_group_id=0 OR GroupId=par_group_id)
					);
					SELECT cve_id, incident_count, var_total_record_count AS total_record_count
					FROM
					(
						SELECT IFNULL(SUM(incident_count), 0) AS incident_count, vuln_id
						FROM rpt_vuln_topvuln_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.user_id=var_user_id
						AND (par_group_id=0 OR GroupId=par_group_id)
						GROUP BY vuln_id
						ORDER BY incident_count DESC LIMIT 5
					) AS a, rpt_vuln_master_dim AS b
					WHERE a.vuln_id = b.vuln_id;
				ELSEIF var_client_count = 1 THEN
					SET var_total_record_count = (
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_topvuln_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str 
						AND a.user_id=var_user_id
						AND (par_group_id=0 OR GroupId=par_group_id)
					);
					SELECT cve_id, incident_count, var_total_record_count AS total_record_count
					FROM
					(
						SELECT IFNULL(SUM(incident_count), 0) AS incident_count, vuln_id
						FROM rpt_vuln_topvuln_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str 
						AND a.user_id=var_user_id
						AND (par_group_id=0 OR GroupId=par_group_id)
						GROUP BY vuln_id
						ORDER BY incident_count DESC LIMIT 5
					) AS a, rpt_vuln_master_dim AS b
					WHERE a.vuln_id = b.vuln_id;
				END IF;
			ELSE
				SET var_total_record_count = (
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_topvuln_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR GroupId=par_group_id)
				);
				SELECT cve_id, incident_count, var_total_record_count AS total_record_count
				FROM
				(
					SELECT IFNULL(SUM(incident_count), 0) AS incident_count, vuln_id
					FROM rpt_vuln_topvuln_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR GroupId=par_group_id)
					GROUP BY vuln_id
					ORDER BY incident_count DESC LIMIT 5
				) AS a, rpt_vuln_master_dim AS b
				WHERE a.vuln_id = b.vuln_id;
			END IF;
		END IF;
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `vuln_topvuln_rpt_get_count_pr`;
DELIMITER $$
CREATE PROCEDURE `vuln_topvuln_rpt_get_count_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN -- To Export All Reports
		SELECT IFNULL(SUM(incident_count), 0) AS record_count
		FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_vuln_id)
		GROUP BY vuln_id;
	ELSE
		IF par_username='' THEN
			IF par_client_name<> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT IFNULL(COUNT(DISTINCT vuln_id), 0) AS record_count
					FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id, idx_GroupId, idx_vuln_id)
					WHERE
					a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					AND a.GroupId = par_group_id;
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(COUNT(DISTINCT vuln_id), 0) AS record_count
					FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id, idx_GroupId, idx_vuln_id)
					WHERE
					a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id = var_client_ids_str
					AND a.GroupId = par_group_id;
				END IF;

			ELSEIF par_client_name='' AND par_group_id<>0 THEN
				SELECT IFNULL(COUNT(DISTINCT vuln_id), 0) AS record_count
				FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_GroupId, idx_vuln_id)
				WHERE
				a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.GroupId = par_group_id;

			ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT IFNULL(COUNT(DISTINCT vuln_id), 0) AS record_count
					FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id, idx_vuln_id)
					WHERE
					a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str);
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(COUNT(DISTINCT vuln_id), 0) AS record_count
					FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id, idx_vuln_id)
					WHERE
					a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id = var_client_ids_str;
				END IF;
			ELSEIF par_client_name='' AND par_group_id = 0 THEN
				SELECT IFNULL(SUM(incident_count), 0) AS record_count
				FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_vuln_id)
				WHERE
				a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second);
			END IF;
		ELSE
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
			IF par_client_name<> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master WHERE (par_group_id=0 OR GroupId=par_group_id) AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT IFNULL(COUNT(DISTINCT vuln_id), 0) AS record_count
					FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id, idx_GroupId, idx_vuln_id, idx_user_id)
					WHERE
					a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR GroupId=par_group_id);
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(COUNT(DISTINCT vuln_id), 0) AS record_count
					FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id, idx_GroupId, idx_vuln_id, idx_user_id)
					WHERE
					a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id = var_client_ids_str
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR GroupId=par_group_id);
				END IF;
			ELSE
				SELECT IFNULL(COUNT(DISTINCT vuln_id), 0) AS record_count
				FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_GroupId, idx_vuln_id, idx_user_id)
				WHERE
				a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.user_id=var_user_id
				AND (par_group_id=0 OR GroupId=par_group_id);
			END IF;
		END IF;
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `vuln_topvuln_rpt_get_table_pr`;
DELIMITER $$
CREATE PROCEDURE `vuln_topvuln_rpt_get_table_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN -- To Export All Reports
		SELECT incident_date, client_count,
		vuln_title, b.severity, base_metrics, 
		vendor_name, a.cve_id, a.vuln_id, incident_date_in_seconds
		FROM
		(
			SELECT from_unixtime(incident_date_only) AS incident_date, COUNT(DISTINCT client_id) AS client_count,
			client_id, GroupId, vuln_id, cve_id, incident_date_only AS incident_date_in_seconds
			FROM rpt_vuln_topvuln_chart_summary AS a
			GROUP BY vuln_id
			ORDER BY client_count DESC
		) AS a, rpt_vuln_master_dim AS b, rpt_vuln_vendor_master_dim As d
		WHERE 
		a.vuln_id=b.vuln_id AND b.vendor_id=d.vendor_id
		ORDER BY incident_date DESC;
	ELSE
		IF par_username='' THEN
			IF par_client_name<> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT incident_date, client_count,
					vuln_title, b.severity, base_metrics, 
					vendor_name, a.cve_id, a.vuln_id, incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date_only) AS incident_date, COUNT(DISTINCT client_id) AS client_count,
						client_id, GroupId, vuln_id, cve_id, incident_date_only AS incident_date_in_seconds
						FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id, idx_GroupId)
						WHERE
						a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.GroupId = par_group_id
						GROUP BY vuln_id
						ORDER BY client_count DESC LIMIT par_start_index,par_max_records
					) AS a, rpt_vuln_master_dim AS b, rpt_vuln_vendor_master_dim As d
					WHERE 
					a.vuln_id=b.vuln_id AND b.vendor_id=d.vendor_id
					ORDER BY incident_date DESC;
				ELSEIF var_client_count = 1 THEN
					SELECT incident_date, client_count,
					vuln_title, b.severity, base_metrics, 
					vendor_name, a.cve_id, a.vuln_id, incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date_only) AS incident_date, COUNT(DISTINCT client_id) AS client_count,
						client_id, GroupId, vuln_id, cve_id, incident_date_only AS incident_date_in_seconds
						FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id, idx_GroupId)
						WHERE
						a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id = var_client_ids_str
						AND a.GroupId = par_group_id
						GROUP BY vuln_id
						ORDER BY client_count DESC LIMIT par_start_index,par_max_records
					) AS a, rpt_vuln_master_dim AS b, rpt_vuln_vendor_master_dim As d
					WHERE 
					a.vuln_id=b.vuln_id AND b.vendor_id=d.vendor_id
					ORDER BY incident_date DESC;
				END IF;

			ELSEIF par_client_name='' AND par_group_id<>0 THEN
				SELECT incident_date, client_count,
				vuln_title, b.severity, base_metrics, 
				vendor_name, a.cve_id, a.vuln_id, incident_date_in_seconds
				FROM
				(
					SELECT from_unixtime(incident_date_only) AS incident_date, COUNT(DISTINCT client_id) AS client_count,
					client_id, GroupId, vuln_id, cve_id, incident_date_only AS incident_date_in_seconds
					FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id, idx_GroupId)
					WHERE
					a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.GroupId = par_group_id
					GROUP BY vuln_id
					ORDER BY client_count DESC LIMIT par_start_index,par_max_records
				) AS a, rpt_vuln_master_dim AS b, rpt_vuln_vendor_master_dim As d
				WHERE 
				a.vuln_id=b.vuln_id AND b.vendor_id=d.vendor_id
				ORDER BY incident_date DESC;

			ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT incident_date, client_count,
					vuln_title, b.severity, base_metrics, 
					vendor_name, a.cve_id, a.vuln_id, incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date_only) AS incident_date, COUNT(DISTINCT client_id) AS client_count,
						client_id, GroupId, vuln_id, cve_id, incident_date_only AS incident_date_in_seconds
						FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id, idx_GroupId)
						WHERE
						a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						GROUP BY vuln_id
						ORDER BY client_count DESC LIMIT par_start_index,par_max_records
					) AS a, rpt_vuln_master_dim AS b, rpt_vuln_vendor_master_dim As d
					WHERE 
					a.vuln_id=b.vuln_id AND b.vendor_id=d.vendor_id
					ORDER BY incident_date DESC;
				ELSEIF var_client_count = 1 THEN
					SELECT incident_date, client_count,
					vuln_title, b.severity, base_metrics, 
					vendor_name, a.cve_id, a.vuln_id, incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date_only) AS incident_date, COUNT(DISTINCT client_id) AS client_count,
						client_id, GroupId, vuln_id, cve_id, incident_date_only AS incident_date_in_seconds
						FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id, idx_GroupId)
						WHERE
						a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id = var_client_ids_str
						GROUP BY vuln_id
						ORDER BY client_count DESC LIMIT par_start_index,par_max_records
					) AS a, rpt_vuln_master_dim AS b, rpt_vuln_vendor_master_dim As d
					WHERE 
					a.vuln_id=b.vuln_id AND b.vendor_id=d.vendor_id
					ORDER BY incident_date DESC;
				END IF;
			ELSEIF par_client_name='' AND par_group_id = 0 THEN
				SELECT incident_date, client_count,
				vuln_title, b.severity, base_metrics, 
				vendor_name, a.cve_id, a.vuln_id, incident_date_in_seconds
				FROM
				(
					SELECT from_unixtime(incident_date_only) AS incident_date, COUNT(DISTINCT client_id) AS client_count,
					client_id, GroupId, vuln_id, cve_id, incident_date_only AS incident_date_in_seconds
					FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id, idx_GroupId)
					WHERE
					a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					GROUP BY vuln_id
					ORDER BY client_count DESC LIMIT par_start_index,par_max_records
				) AS a, rpt_vuln_master_dim AS b, rpt_vuln_vendor_master_dim As d
				WHERE 
				a.vuln_id=b.vuln_id AND b.vendor_id=d.vendor_id
				ORDER BY incident_date DESC;
			END IF;
		ELSE
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
			IF par_client_name<> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master WHERE (par_group_id OR GroupId=par_group_id) AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT incident_date, client_count,
					vuln_title, b.severity, base_metrics, 
					vendor_name, a.cve_id, a.vuln_id, incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date_only) AS incident_date, COUNT(DISTINCT client_id) AS client_count,
						client_id, GroupId, vuln_id, cve_id, incident_date_only AS incident_date_in_seconds
						FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id, idx_GroupId, idx_user_id)
						WHERE
						a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.user_id=var_user_id
						AND (par_group_id=0 OR GroupId=par_group_id)
						GROUP BY vuln_id
						ORDER BY client_count DESC LIMIT par_start_index,par_max_records
					) AS a, rpt_vuln_master_dim AS b, rpt_vuln_vendor_master_dim As d
					WHERE 
					a.vuln_id=b.vuln_id AND b.vendor_id=d.vendor_id
					ORDER BY incident_date DESC;
				ELSEIF var_client_count = 1 THEN
					SELECT incident_date, client_count,
					vuln_title, b.severity, base_metrics, 
					vendor_name, a.cve_id, a.vuln_id, incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date_only) AS incident_date, COUNT(DISTINCT client_id) AS client_count,
						client_id, GroupId, vuln_id, cve_id, incident_date_only AS incident_date_in_seconds
						FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_client_id, idx_GroupId, idx_user_id)
						WHERE
						a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id = var_client_ids_str
						AND a.user_id=var_user_id
						AND (par_group_id=0 OR GroupId=par_group_id)
						GROUP BY vuln_id
						ORDER BY client_count DESC LIMIT par_start_index,par_max_records
					) AS a, rpt_vuln_master_dim AS b, rpt_vuln_vendor_master_dim As d
					WHERE 
					a.vuln_id=b.vuln_id AND b.vendor_id=d.vendor_id
					ORDER BY incident_date DESC;
				END IF;
			ELSE
				SELECT incident_date, client_count,
				vuln_title, b.severity, base_metrics, 
				vendor_name, a.cve_id, a.vuln_id, incident_date_in_seconds
				FROM
				(
					SELECT from_unixtime(incident_date_only) AS incident_date, COUNT(DISTINCT client_id) AS client_count,
					client_id, GroupId, vuln_id, cve_id, incident_date_only AS incident_date_in_seconds
					FROM rpt_vuln_topvuln_chart_summary AS a USE INDEX(idx_incident_date_only, idx_GroupId, idx_user_id)
					WHERE
					a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR GroupId=par_group_id)
					GROUP BY vuln_id
					ORDER BY client_count DESC LIMIT par_start_index,par_max_records
				) AS a, rpt_vuln_master_dim AS b, rpt_vuln_vendor_master_dim As d
				WHERE 
				a.vuln_id=b.vuln_id AND b.vendor_id=d.vendor_id
				ORDER BY incident_date DESC;
			END IF;
		END IF;
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `vuln_vendor_rpt_get_chart_pr`;
DELIMITER $$
CREATE PROCEDURE `vuln_vendor_rpt_get_chart_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_total_record_count BIGINT(20) DEFAULT 0;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN -- To Export All Reports
		SET var_total_record_count = (
			SELECT IFNULL(SUM(incident_count), 0) AS record_count
			FROM rpt_vuln_vendor_chart_summary AS a
		);
		SELECT vendor_name, record_percentage
		FROM
		(
			SELECT ROUND((IFNULL(SUM(incident_count),0) * 100) / var_total_record_count, 2) AS record_percentage, vendor_id
			FROM rpt_vuln_vendor_chart_summary AS a
			GROUP BY a.vendor_id
			ORDER BY record_percentage DESC LIMIT 6
		) AS a, rpt_vuln_vendor_master_dim AS b
		WHERE a.vendor_id = b.vendor_id AND record_percentage > 0;
	ELSE
		IF par_username='' THEN
			IF par_client_name <> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SET var_total_record_count = (
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.GroupId=par_group_id
					);
					SELECT vendor_name, record_percentage
					FROM
					(
						SELECT ROUND((IFNULL(SUM(incident_count),0) * 100) / var_total_record_count, 2) AS record_percentage, vendor_id
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.GroupId=par_group_id
						GROUP BY a.vendor_id
						ORDER BY record_percentage DESC LIMIT 6
					) AS a, rpt_vuln_vendor_master_dim AS b
					WHERE a.vendor_id = b.vendor_id AND record_percentage > 0;
				ELSEIF var_client_count = 1 THEN
					SET var_total_record_count = (
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str 
						AND a.GroupId=par_group_id
					);
					SELECT vendor_name, record_percentage
					FROM
					(
						SELECT ROUND((IFNULL(SUM(incident_count),0) * 100) / var_total_record_count, 2) AS record_percentage, vendor_id
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str 
						AND a.GroupId=par_group_id
						GROUP BY a.vendor_id
						ORDER BY record_percentage DESC LIMIT 6
					) AS a, rpt_vuln_vendor_master_dim AS b
					WHERE a.vendor_id = b.vendor_id AND record_percentage > 0;
				END IF;
			ELSEIF par_client_name='' AND par_group_id <> 0 THEN
				SET var_total_record_count = (
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_vendor_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second) 
					AND a.GroupId=par_group_id
				);
				SELECT vendor_name, record_percentage
				FROM
				(
					SELECT ROUND((IFNULL(SUM(incident_count),0) * 100) / var_total_record_count, 2) AS record_percentage, vendor_id
					FROM rpt_vuln_vendor_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.GroupId=par_group_id
					GROUP BY a.vendor_id
					ORDER BY record_percentage DESC LIMIT 6
				) AS a, rpt_vuln_vendor_master_dim AS b
				WHERE a.vendor_id = b.vendor_id AND record_percentage > 0;
			ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SET var_total_record_count = (
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
					);
					SELECT vendor_name, record_percentage
					FROM
					(
						SELECT ROUND((IFNULL(SUM(incident_count),0) * 100) / var_total_record_count, 2) AS record_percentage, vendor_id
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						GROUP BY a.vendor_id
						ORDER BY record_percentage DESC LIMIT 6
					) AS a, rpt_vuln_vendor_master_dim AS b
					WHERE a.vendor_id = b.vendor_id AND record_percentage > 0;
				ELSEIF var_client_count = 1 THEN
					SET var_total_record_count = (
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str
					);
					SELECT vendor_name, record_percentage
					FROM
					(
						SELECT ROUND((IFNULL(SUM(incident_count),0) * 100) / var_total_record_count, 2) AS record_percentage, vendor_id
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str
						GROUP BY a.vendor_id
						ORDER BY record_percentage DESC LIMIT 6
					) AS a, rpt_vuln_vendor_master_dim AS b
					WHERE a.vendor_id = b.vendor_id AND record_percentage > 0;
				END IF;
			ELSEIF par_client_name='' AND par_group_id = 0 THEN
				SET var_total_record_count = (
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_vendor_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				);
				SELECT vendor_name, record_percentage
				FROM
				(
					SELECT ROUND((IFNULL(SUM(incident_count),0) * 100) / var_total_record_count, 2) AS record_percentage, vendor_id
					FROM rpt_vuln_vendor_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					GROUP BY a.vendor_id
					ORDER BY record_percentage DESC LIMIT 6
				) AS a, rpt_vuln_vendor_master_dim AS b
				WHERE a.vendor_id = b.vendor_id AND record_percentage > 0;
			END IF;
		ELSE
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
			IF par_client_name <> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master WHERE (par_group_id=0 OR GroupId=par_group_id) AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SET var_total_record_count = (
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.user_id=var_user_id
						AND (par_group_id=0 OR GroupId=par_group_id)
					);
					SELECT vendor_name, record_percentage
					FROM
					(
						SELECT ROUND((IFNULL(SUM(incident_count),0) * 100) / var_total_record_count, 2) AS record_percentage, vendor_id
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.user_id=var_user_id
						AND (par_group_id=0 OR GroupId=par_group_id)
						GROUP BY a.vendor_id
						ORDER BY record_percentage DESC LIMIT 6
					) AS a, rpt_vuln_vendor_master_dim AS b
					WHERE a.vendor_id = b.vendor_id AND record_percentage > 0;
				ELSEIF var_client_count = 1 THEN
					SET var_total_record_count = (
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str 
						AND a.user_id=var_user_id
						AND (par_group_id=0 OR GroupId=par_group_id)
					);
					SELECT vendor_name, record_percentage
					FROM
					(
						SELECT ROUND((IFNULL(SUM(incident_count),0) * 100) / var_total_record_count, 2) AS record_percentage, vendor_id
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str 
						AND a.user_id=var_user_id
						AND (par_group_id=0 OR GroupId=par_group_id)
						GROUP BY a.vendor_id
						ORDER BY record_percentage DESC LIMIT 6
					) AS a, rpt_vuln_vendor_master_dim AS b
					WHERE a.vendor_id = b.vendor_id AND record_percentage > 0;
				END IF;
			ELSE
				SET var_total_record_count = (
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_vendor_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR GroupId=par_group_id)
				);
				SELECT vendor_name, record_percentage
				FROM
				(
					SELECT ROUND((IFNULL(SUM(incident_count),0) * 100) / var_total_record_count, 2) AS record_percentage, vendor_id
					FROM rpt_vuln_vendor_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR GroupId=par_group_id)
					GROUP BY a.vendor_id
					ORDER BY record_percentage DESC LIMIT 6
				) AS a, rpt_vuln_vendor_master_dim AS b
				WHERE a.vendor_id = b.vendor_id AND record_percentage > 0;
			END IF;
		END IF;
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `vuln_vendor_rpt_get_count_pr`;
DELIMITER $$
CREATE PROCEDURE `vuln_vendor_rpt_get_count_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512),
	IN par_vendor_id INT(2)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN -- To Export All Reports
		SELECT IFNULL(SUM(incident_count), 0) AS record_count FROM rpt_vuln_vendor_chart_summary;
	ELSE
		IF par_username='' THEN
			IF par_vendor_id <> 0 THEN
				IF par_client_name <> '' AND par_group_id <> 0 THEN
					SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
										
					IF var_client_count > 1 THEN
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.GroupId=par_group_id
						AND a.vendor_id = par_vendor_id;
					ELSEIF var_client_count = 1 THEN
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str 
						AND a.GroupId=par_group_id
						AND a.vendor_id = par_vendor_id;
					END IF;
				ELSEIF par_client_name='' AND par_group_id <> 0 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_vendor_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.vendor_id = par_vendor_id
					AND a.GroupId=par_group_id;
				ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
					SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
						
					IF var_client_count > 1 THEN
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.vendor_id = par_vendor_id;
					ELSEIF var_client_count = 1 THEN
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str
						AND a.vendor_id = par_vendor_id;
					END IF;
				ELSEIF par_client_name='' AND par_group_id = 0 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_vendor_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.vendor_id = par_vendor_id;
				END IF;
			
			ELSE
				IF par_client_name <> '' AND par_group_id <> 0 THEN
					SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
										
					IF var_client_count > 1 THEN
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.GroupId=par_group_id;
					ELSEIF var_client_count = 1 THEN
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str 
						AND a.GroupId=par_group_id;
					END IF;
				ELSEIF par_client_name='' AND par_group_id <> 0 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_vendor_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.GroupId=par_group_id;
				ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
					SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
										
					IF var_client_count > 1 THEN
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str);
					ELSEIF var_client_count = 1 THEN
						SELECT IFNULL(SUM(incident_count), 0) AS record_count
						FROM rpt_vuln_vendor_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str;
					END IF;
				ELSEIF par_client_name='' AND par_group_id = 0 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_vendor_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second);
				END IF;
			END IF;
		ELSE
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
			IF par_client_name <> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master WHERE (par_group_id=0 OR GroupId=par_group_id) AND computer_name=par_client_name;
									
				IF var_client_count > 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_vendor_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR GroupId=par_group_id)
					AND (par_vendor_id=0 OR a.vendor_id = par_vendor_id);
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_vuln_vendor_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str 
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR GroupId=par_group_id)
					AND (par_vendor_id=0 OR a.vendor_id = par_vendor_id);
				END IF;
			ELSE
				SELECT IFNULL(SUM(incident_count), 0) AS record_count
				FROM rpt_vuln_vendor_chart_summary AS a
				WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.user_id=var_user_id
				AND (par_group_id=0 OR GroupId=par_group_id)
				AND (par_vendor_id=0 OR a.vendor_id = par_vendor_id);
			END IF;
		END IF;
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `web_security_rpt_get_chart_pr`;
DELIMITER $$
CREATE PROCEDURE `web_security_rpt_get_chart_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN -- To Export All Reports
		SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
		FROM
		(
			SELECT websec_category_id , SUM(incident_count) AS incident_count
			FROM rpt_websec_chart_summary AS a
			GROUP BY websec_category_id ORDER BY incident_count DESC LIMIT 5
		) AS t1, rpt_websec_category_dim AS b
		WHERE t1.websec_category_id=b.websec_category_id;
	ELSE
		IF par_username='' THEN
			IF par_client_name <> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
					FROM
					(
						SELECT websec_category_id , SUM(incident_count) AS incident_count
						FROM rpt_websec_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str) AND a.GroupId=par_group_id
						GROUP BY websec_category_id ORDER BY incident_count DESC LIMIT 5
					) AS t1, rpt_websec_category_dim AS b
					WHERE t1.websec_category_id=b.websec_category_id;
				ELSEIF var_client_count = 1 THEN
					SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
					FROM
					(
						SELECT websec_category_id , SUM(incident_count) AS incident_count
						FROM rpt_websec_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str AND a.GroupId=par_group_id
						GROUP BY websec_category_id ORDER BY incident_count DESC LIMIT 5
					) AS t1, rpt_websec_category_dim AS b
					WHERE t1.websec_category_id=b.websec_category_id;
				END IF;
			ELSEIF par_client_name='' AND par_group_id<>0 THEN
				SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
				FROM
				(
					SELECT websec_category_id , SUM(incident_count) AS incident_count
					FROM rpt_websec_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.GroupId=par_group_id
					GROUP BY websec_category_id ORDER BY incident_count DESC LIMIT 5
				) AS t1, rpt_websec_category_dim AS b
				WHERE t1.websec_category_id=b.websec_category_id;
			ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
					FROM
					(
						SELECT websec_category_id , SUM(incident_count) AS incident_count
						FROM rpt_websec_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						GROUP BY websec_category_id ORDER BY incident_count DESC LIMIT 5
					) AS t1, rpt_websec_category_dim AS b
					WHERE t1.websec_category_id=b.websec_category_id;
				ELSEIF var_client_count = 1 THEN
					SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
					FROM
					(
						SELECT websec_category_id , SUM(incident_count) AS incident_count
						FROM rpt_websec_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str
						GROUP BY websec_category_id ORDER BY incident_count DESC LIMIT 5
					) AS t1, rpt_websec_category_dim AS b
					WHERE t1.websec_category_id=b.websec_category_id;
				END IF;
		ELSEIF par_client_name='' AND par_group_id = 0 THEN
				SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
				FROM
				(
					SELECT websec_category_id , SUM(incident_count) AS incident_count
					FROM rpt_websec_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					GROUP BY websec_category_id ORDER BY incident_count DESC LIMIT 5
				) AS t1, rpt_websec_category_dim AS b
				WHERE t1.websec_category_id=b.websec_category_id;
			END IF;
		ELSE
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
			IF par_client_name <> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master 
				WHERE (par_group_id=0 OR GroupId=par_group_id) AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
					FROM
					(
						SELECT websec_category_id , SUM(incident_count) AS incident_count
						FROM rpt_websec_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)						
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.user_id=var_user_id
						AND (par_group_id=0 OR a.GroupId=par_group_id)
						GROUP BY websec_category_id ORDER BY incident_count DESC LIMIT 5
					) AS t1, rpt_websec_category_dim AS b
					WHERE t1.websec_category_id=b.websec_category_id;
				ELSEIF var_client_count = 1 THEN
					SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
					FROM
					(
						SELECT websec_category_id , SUM(incident_count) AS incident_count
						FROM rpt_websec_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str
						AND a.user_id=var_user_id
						AND (par_group_id=0 OR a.GroupId=par_group_id)
						GROUP BY websec_category_id ORDER BY incident_count DESC LIMIT 5
					) AS t1, rpt_websec_category_dim AS b
					WHERE t1.websec_category_id=b.websec_category_id;
				END IF;
			ELSE
				SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
				FROM
				(
					SELECT websec_category_id , SUM(incident_count) AS incident_count
					FROM rpt_websec_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR a.GroupId=par_group_id)
					GROUP BY websec_category_id ORDER BY incident_count DESC LIMIT 5
				) AS t1, rpt_websec_category_dim AS b
				WHERE t1.websec_category_id=b.websec_category_id;
			END IF;
		END IF;
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `web_security_rpt_get_count_pr`;
DELIMITER $$
CREATE PROCEDURE `web_security_rpt_get_count_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;	
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN -- To Export All Reports
		SELECT IFNULL(SUM(incident_count), 0) AS record_count FROM rpt_websec_chart_summary AS a;
	ELSE
		IF par_username='' THEN
			IF par_client_name <> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_websec_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					AND a.GroupId=par_group_id;
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_websec_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str 
					AND a.GroupId=par_group_id;
				END IF;
			ELSEIF par_client_name='' AND par_group_id <> 0 THEN
				SELECT IFNULL(SUM(incident_count), 0) AS record_count
				FROM rpt_websec_chart_summary AS a
				WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.GroupId=par_group_id;
			ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_websec_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str);
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_websec_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str;
				END IF;
			ELSEIF par_client_name='' AND par_group_id = 0 THEN
				SELECT IFNULL(SUM(incident_count), 0) AS record_count
				FROM rpt_websec_chart_summary AS a
				WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second);
			END IF;
		ELSE
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
			IF par_client_name <> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master 
				WHERE (par_group_id=0 OR GroupId=par_group_id) AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_websec_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR a.GroupId=par_group_id);
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(SUM(incident_count), 0) AS record_count
					FROM rpt_websec_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str 
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR a.GroupId=par_group_id);
				END IF;
			ELSE
				SELECT IFNULL(SUM(incident_count), 0) AS record_count
				FROM rpt_websec_chart_summary AS a
				WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.user_id=var_user_id
				AND (par_group_id=0 OR a.GroupId=par_group_id);
			END IF;
		END IF;
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `web_security_rpt_get_table_pr`;
DELIMITER $$
CREATE PROCEDURE `web_security_rpt_get_table_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;	
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN -- To Export All Reports
		SELECT incident_date, t1.client_id, computer_name, e.username, domain_name, b.website, d.category, incident_date_in_seconds
		FROM
		(
			SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, url_id, websec_category_id, GroupId, incident_date AS incident_date_in_seconds
			FROM rpt_websec_incident_fact AS a
			ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
		) AS t1, rpt_websec_bolckedsites_dim AS b, client_master AS c, rpt_websec_category_dim As d, rpt_user_master AS e
		WHERE 
		t1.url_id=b.url_id AND t1.client_id=c.client_id AND t1.websec_category_id=d.websec_category_id AND t1.user_id=e.user_id
		ORDER BY incident_date DESC;
	ELSE
		IF par_username='' THEN
			IF par_client_name<> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT incident_date, t1.client_id, computer_name, e.username, domain_name, b.website, d.category, incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, url_id, websec_category_id, GroupId, incident_date AS incident_date_in_seconds
						FROM rpt_websec_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.GroupId = par_group_id
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS t1, rpt_websec_bolckedsites_dim AS b, client_master AS c, rpt_websec_category_dim As d, rpt_user_master AS e
					WHERE 
					t1.url_id=b.url_id AND t1.client_id=c.client_id AND t1.websec_category_id=d.websec_category_id AND t1.user_id=e.user_id
					ORDER BY incident_date DESC;
				ELSEIF var_client_count = 1 THEN
					SELECT incident_date, t1.client_id, computer_name, e.username, domain_name, b.website, d.category, incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, url_id, websec_category_id, GroupId, incident_date AS incident_date_in_seconds
						FROM rpt_websec_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id = var_client_ids_str
						AND a.GroupId = par_group_id
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS t1, rpt_websec_bolckedsites_dim AS b, client_master AS c, rpt_websec_category_dim As d, rpt_user_master AS e
					WHERE 
					t1.url_id=b.url_id AND t1.client_id=c.client_id AND t1.websec_category_id=d.websec_category_id AND t1.user_id=e.user_id
					ORDER BY incident_date DESC;
				END IF;

			ELSEIF par_client_name='' AND par_group_id<>0 THEN
				SELECT incident_date, t1.client_id, computer_name, e.username, domain_name, b.website, d.category, incident_date_in_seconds
				FROM
				(
					SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, url_id, websec_category_id, GroupId, incident_date AS incident_date_in_seconds
					FROM rpt_websec_incident_fact AS a USE INDEX(idx_incident_date, idx_GroupId)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.GroupId = par_group_id
					ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
				) AS t1, rpt_websec_bolckedsites_dim AS b, client_master AS c, rpt_websec_category_dim As d, rpt_user_master AS e
				WHERE 
				t1.url_id=b.url_id AND t1.client_id=c.client_id AND t1.websec_category_id=d.websec_category_id AND t1.user_id=e.user_id
				ORDER BY incident_date DESC;

			ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT incident_date, t1.client_id, computer_name, e.username, domain_name, b.website, d.category, incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, url_id, websec_category_id, GroupId, incident_date AS incident_date_in_seconds
						FROM rpt_websec_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS t1, rpt_websec_bolckedsites_dim AS b, client_master AS c, rpt_websec_category_dim As d, rpt_user_master AS e
					WHERE 
					t1.url_id=b.url_id AND t1.client_id=c.client_id AND t1.websec_category_id=d.websec_category_id AND t1.user_id=e.user_id
					ORDER BY incident_date DESC;
				ELSEIF var_client_count = 1 THEN
					SELECT incident_date, t1.client_id, computer_name, e.username, domain_name, b.website, d.category, incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, url_id, websec_category_id, GroupId, incident_date AS incident_date_in_seconds
						FROM rpt_websec_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id = var_client_ids_str
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS t1, rpt_websec_bolckedsites_dim AS b, client_master AS c, rpt_websec_category_dim As d, rpt_user_master AS e
					WHERE 
					t1.url_id=b.url_id AND t1.client_id=c.client_id AND t1.websec_category_id=d.websec_category_id AND t1.user_id=e.user_id
					ORDER BY incident_date DESC;
				END IF;
			ELSEIF par_client_name='' AND par_group_id = 0 THEN
				SELECT incident_date, t1.client_id, computer_name, e.username, domain_name, b.website, d.category, incident_date_in_seconds
				FROM
				(
					SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, url_id, websec_category_id, GroupId, incident_date AS incident_date_in_seconds
					FROM rpt_websec_incident_fact AS a
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
				) AS t1, rpt_websec_bolckedsites_dim AS b, client_master AS c, rpt_websec_category_dim As d, rpt_user_master AS e
				WHERE 
				t1.url_id=b.url_id AND t1.client_id=c.client_id AND t1.websec_category_id=d.websec_category_id AND t1.user_id=e.user_id
				ORDER BY incident_date DESC;
			END IF;		
		ELSE
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
			IF par_client_name<> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master 
				WHERE (par_group_id=0 OR GroupId=par_group_id) AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT incident_date, t1.client_id, computer_name, e.username, domain_name, b.website, d.category, incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, url_id, websec_category_id, GroupId, incident_date AS incident_date_in_seconds
						FROM rpt_websec_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.user_id = var_user_id
						AND (par_group_id=0 OR a.GroupId = par_group_id)
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS t1, rpt_websec_bolckedsites_dim AS b, client_master AS c, rpt_websec_category_dim As d, rpt_user_master AS e
					WHERE 
					t1.url_id=b.url_id AND t1.client_id=c.client_id AND t1.websec_category_id=d.websec_category_id AND t1.user_id=e.user_id
					ORDER BY incident_date DESC;
				ELSEIF var_client_count = 1 THEN
					SELECT incident_date, t1.client_id, computer_name, e.username, domain_name, b.website, d.category, incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, url_id, websec_category_id, GroupId, incident_date AS incident_date_in_seconds
						FROM rpt_websec_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id = var_client_ids_str
						AND a.user_id = var_user_id
						AND (par_group_id=0 OR a.GroupId = par_group_id)
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS t1, rpt_websec_bolckedsites_dim AS b, client_master AS c, rpt_websec_category_dim As d, rpt_user_master AS e
					WHERE 
					t1.url_id=b.url_id AND t1.client_id=c.client_id AND t1.websec_category_id=d.websec_category_id AND t1.user_id=e.user_id
					ORDER BY incident_date DESC;
				END IF;
			ELSE
				SELECT incident_date, t1.client_id, computer_name, e.username, domain_name, b.website, d.category, incident_date_in_seconds
				FROM
				(
					SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, url_id, websec_category_id, GroupId, incident_date AS incident_date_in_seconds
					FROM rpt_websec_incident_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.user_id = var_user_id
					AND (par_group_id=0 OR a.GroupId = par_group_id)
					ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
				) AS t1, rpt_websec_bolckedsites_dim AS b, client_master AS c, rpt_websec_category_dim As d, rpt_user_master AS e
				WHERE 
				t1.url_id=b.url_id AND t1.client_id=c.client_id AND t1.websec_category_id=d.websec_category_id AND t1.user_id=e.user_id
				ORDER BY incident_date DESC;
			END IF;
		END IF;
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `vuln_rpt_get_vendor_list`;
DELIMITER $$
CREATE PROCEDURE `vuln_rpt_get_vendor_list`()
BEGIN

	SET time_zone = '+00:00';
	
	SELECT vendor_id, vendor_name FROM rpt_vuln_vendor_master_dim;
	
END$$
DELIMITER ;

-- Dashboard Store PRocedures
DROP PROCEDURE IF EXISTS `dash_asset_get_category_count_pr`;
DELIMITER $$
CREATE PROCEDURE `dash_asset_get_category_count_pr`(
IN par_start_date INT(11),
IN par_end_date INT(11),
IN par_asset_id INT(11)
)
BEGIN

	SET time_zone = '+00:00';
	
	IF ((par_end_date - par_start_date) >= (846000 * 7)) THEN
	
		-- Here value 6 is taken hard coded because asset info is display for last 7 days only(MAX)
		
		SELECT category_id, COUNT(*) AS cnt
		FROM rpt_asset_mgnt_fact FORCE INDEX(idx_incident_date)
		WHERE 
		(incident_date >= unix_timestamp(GetCurrentDate() - INTERVAL 6 DAY) AND incident_date < unix_timestamp(GetCurrentDate() + INTERVAL 1 DAY))
		AND  asset_id <> par_asset_id
		GROUP BY category_id;
		
	ELSE
	
		SELECT category_id, COUNT(*) AS cnt
		FROM rpt_asset_mgnt_fact FORCE INDEX(idx_incident_date)
		WHERE 
		(incident_date >= par_start_date AND incident_date < par_end_date)
		AND  asset_id <> par_asset_id
		GROUP BY category_id;
		
	END IF;
			
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS dash_asset_get_chart_detail_table_pr;
DELIMITER $$
CREATE PROCEDURE `dash_asset_get_chart_detail_table_pr`(
	IN par_start_date INT(11),
	IN par_end_date INT(11),
	IN par_category_id INT(1),
	IN par_asset_id INT(11)
)
BEGIN

	SET time_zone = '+00:00';
	
	SELECT a.incident_date, b.computer_name, b.str_ip_address, c.username, a.asset_name, a.details, incident_date_in_seconds
	FROM
	(
		SELECT incident_date, client_id, user_id, asset_name, details, incident_date AS incident_date_in_seconds
		FROM rpt_asset_mgnt_fact USE INDEX(idx_incident_date, idx_asset_id, idx_category_id)
		WHERE 
		(incident_date >= par_start_date AND incident_date < par_end_date)
		AND asset_id <> par_asset_id
		AND category_id = par_category_id
	) AS a, client_master b, rpt_user_master AS c
	WHERE
	a.client_id = b.client_id AND a.user_id = c.user_id
	ORDER BY incident_date DESC;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS dash_security_websec_get_chart_detail_table_pr;
DELIMITER $$
CREATE PROCEDURE `dash_security_websec_get_chart_detail_table_pr`(
IN par_start_date_only_insec INT(11),
IN par_end_date_only_insec INT(11),
IN par_category_id VARCHAR(16),
IN par_start_index INT(11),
IN par_max_records INT(11)
)
BEGIN	

	SET time_zone = '+00:00';
	
	IF 0 = POSITION("," IN par_category_id) THEN
	
		SELECT website, computer_name, domain_name, incident_date, websec_category_id
		FROM
		(
			SELECT incident_date, client_id, url_id
			FROM rpt_websec_incident_fact AS a USE INDEX(idx_incident_date, idx_websec_category_id) 
			WHERE websec_category_id = CONVERT(par_category_id, UNSIGNED INTEGER) AND
			a.incident_date >= par_start_date_only_insec AND a.incident_date <= par_end_date_only_insec
			ORDER BY a.incident_date DESC
			LIMIT par_start_index,par_max_records
		) AS a, rpt_websec_bolckedsites_dim AS b, client_master AS c 
		WHERE
		a.url_id=b.url_id AND a.client_id=c.client_id
		ORDER BY a.incident_date DESC;
		
	ELSE
	
		SELECT website, computer_name, domain_name, incident_date, websec_category_id
			FROM
			(
				SELECT incident_date, client_id, url_id
				FROM rpt_websec_incident_fact AS a USE INDEX(idx_incident_date, idx_websec_category_id) 
				WHERE NOT FIND_IN_SET(websec_category_id, par_category_id) AND
				a.incident_date >= par_start_date_only_insec AND a.incident_date <= par_end_date_only_insec
				ORDER BY a.incident_date DESC
				LIMIT par_start_index,par_max_records
			) AS a, rpt_websec_bolckedsites_dim AS b, client_master AS c 
			WHERE
			a.url_id=b.url_id AND a.client_id=c.client_id
			ORDER BY a.incident_date DESC;
			
	END IF;
	
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS dash_security_websec_get_summary_detail_table_pr;
DELIMITER $$
CREATE PROCEDURE `dash_security_websec_get_summary_detail_table_pr`(
IN par_start_date_only_insec INT(11),
IN par_end_date_only_insec INT(11),
IN par_category_id VARCHAR(16),
IN par_url varchar(1024),
IN par_start_index INT(11),
IN par_max_records INT(11)
)
BEGIN	

	DECLARE var_url_id int(11) DEFAULT NULL;

	SET time_zone = '+00:00';
		
	SET var_url_id = (SELECT url_id FROM rpt_websec_bolckedsites_dim WHERE website = par_url AND websec_category_id = par_category_id LIMIT 1);

	SELECT website, computer_name, domain_name, incident_date
	FROM
	(
		SELECT incident_date, client_id, url_id
		FROM rpt_websec_incident_fact AS a USE INDEX(idx_incident_date, idx_url_id)  
		WHERE  
		a.incident_date >= par_start_date_only_insec AND a.incident_date <= par_end_date_only_insec
		AND url_id = var_url_id
		
		ORDER BY a.incident_date DESC
		LIMIT par_start_index, par_max_records
	) AS a, rpt_websec_bolckedsites_dim AS b, client_master AS c 
	WHERE
	a.url_id=b.url_id 
	AND a.client_id=c.client_id
	ORDER BY a.incident_date DESC;
	
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS dash_security_vulnscan_get_chart_detail_table_pr;
DELIMITER $$
CREATE PROCEDURE `dash_security_vulnscan_get_chart_detail_table_pr`(
IN par_start_date_only_insec INT(11),
IN par_end_date_only_insec INT(11),
IN par_start_index INT(11),
IN par_max_records INT(11)
)
BEGIN

	SET time_zone = '+00:00';
	
	SELECT b.computer_name, b.domain_name, OsVersion, b.guid, b.str_ip_address
	FROM
	(
		SELECT DISTINCT client_id 
		FROM  rpt_vuln_incident_fact FORCE INDEX(idx_incident_date)
		WHERE
		incident_date >= par_start_date_only_insec AND incident_date <= par_end_date_only_insec
		ORDER BY incident_date DESC
		LIMIT par_start_index, par_max_records
	) AS a, client_master AS b, clientos AS c
	WHERE
	a.client_id = b.client_id
	AND b.guid = c.guid;
	
	
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS dash_security_vulnscan_get_summary_detail_table_pr;
DELIMITER $$
CREATE PROCEDURE `dash_security_vulnscan_get_summary_detail_table_pr`(
IN par_start_date_only_insec INT(11),
IN par_end_date_only_insec INT(11),
IN par_cve_id char(14),
IN par_start_index INT(11),
IN par_max_records INT(11)
)
BEGIN

	DECLARE var_vuln_id BIGINT(20) DEFAULT NULL;
	
	SET var_vuln_id = (SELECT vuln_id FROM rpt_vuln_master_dim WHERE cve_id = par_cve_id LIMIT 1);
	
	SET time_zone = '+00:00';
	
	SELECT a.cve_id, b.computer_name, b.domain_name, '-' AS OsVersion, a.incident_date, b.str_ip_address
	FROM
	(
		SELECT cve_id, incident_date, client_id
		FROM  rpt_vuln_incident_fact USE INDEX(idx_incident_date, idx_vuln_id)
		WHERE
		incident_date >= par_start_date_only_insec AND incident_date <= par_end_date_only_insec
		AND vuln_id = var_vuln_id
		ORDER BY incident_date DESC
		LIMIT par_start_index, par_max_records
	) AS a, client_master AS b
	WHERE
	a.client_id = b.client_id
	ORDER BY incident_date DESC;
	
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS dash_compliance_appctrl_get_chart_detail_table_pr;
DELIMITER $$
CREATE PROCEDURE `dash_compliance_appctrl_get_chart_detail_table_pr`(
	IN par_start_date_only_insec INT(11),
	IN par_end_date_only_insec INT(11),
	IN par_category_id VARCHAR(16),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN

	SET time_zone = '+00:00';
	
	IF 0 = POSITION("," IN par_category_id) THEN
	
		SELECT a.application_name, b.computer_name, c.username, a.incident_date, a.app_category_id, b.str_ip_address
		FROM
		(
			SELECT incident_date, client_id, a.user_id, application_name, app_category_id
			FROM rpt_appcon_oa_fact USE INDEX(idx_incident_date, idx_app_category_id)
			WHERE 
			(incident_date >= par_start_date_only_insec AND incident_date < par_end_date_only_insec)
			AND app_category_id = CONVERT(par_category_id, UNSIGNED INTEGER) 
			ORDER BY incident_date DESC
			LIMIT par_start_index,par_max_records
		) AS a, client_master AS b, rpt_user_master AS c
		WHERE
		a.client_id = b.client_id AND a.user_id = c.user_id
		ORDER BY incident_date DESC;
		
	ELSE
	
		SELECT a.application_name, b.computer_name, c.username, a.incident_date, a.app_category_id, b.str_ip_address
		FROM
		(
			SELECT incident_date, client_id, a.user_id, application_name, app_category_id
			FROM rpt_appcon_oa_fact USE INDEX(idx_incident_date, idx_app_category_id)
			WHERE 
			(incident_date >= par_start_date_only_insec AND incident_date < par_end_date_only_insec)
			AND NOT FIND_IN_SET(app_category_id, par_category_id)
			ORDER BY incident_date DESC
			LIMIT par_start_index,par_max_records
		) AS a, client_master AS b, rpt_user_master AS c
		WHERE
		a.client_id = b.client_id AND a.user_id = c.user_id
		ORDER BY incident_date DESC;
		
	END IF;
	
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS dash_compliance_appctrl_get_summary_detail_table_pr;
DELIMITER $$
CREATE PROCEDURE `dash_compliance_appctrl_get_summary_detail_table_pr`(
IN par_start_date_only_insec INT(11),
IN par_end_date_only_insec INT(11),
IN par_guid varchar(45),
IN par_user_name varchar(45),
IN par_start_index INT(11),
IN par_max_records INT(11)
)
BEGIN

	DECLARE var_client_id bigint(20) DEFAULT NULL;
	DECLARE var_user_id bigint(20) DEFAULT NULL;

	SET time_zone = '+00:00';
		
	SET var_client_id = (SELECT client_id FROM client_master WHERE guid = par_guid limit 1);
	SET var_user_id = (SELECT user_id FROM rpt_user_master WHERE username = par_user_name limit 1);

	SELECT a.application_name, b.computer_name, c.username, a.incident_date, b.domain_name, a.app_category_name
	FROM
	(
		SELECT application_name, client_id, user_id, incident_date, app_category_name
		FROM rpt_appcon_oa_fact USE INDEX(idx_incident_date, idx_user_id)
		WHERE 
		(incident_date >= par_start_date_only_insec AND incident_date < par_end_date_only_insec)
		AND user_id = var_user_id 
		AND client_id = var_client_id
		ORDER BY incident_date DESC
		LIMIT par_start_index, par_max_records
	) AS a, client_master AS b, rpt_user_master AS c
	WHERE
	a.client_id = b.client_id AND a.user_id = c.user_id
	ORDER BY incident_date DESC;
	
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS dash_compliance_devctrl_get_chart_detail_table_pr;
DELIMITER $$
CREATE PROCEDURE `dash_compliance_devctrl_get_chart_detail_table_pr`(
IN par_start_date_only_insec INT(11),
IN par_end_date_only_insec INT(11),
IN par_device_type_id VARCHAR(16),
IN par_start_index INT(11),
IN par_max_records INT(11)
)
BEGIN
	
	SET time_zone = '+00:00';
	
	IF 0 = POSITION("," IN par_device_type_id) THEN
	
		SELECT b.device_name, b.manufacturer, c.computer_name, d.username, b.serial_number, a.incident_date, c.str_ip_address
		FROM
		(
			SELECT incident_date, client_id, device_id, user_id
			FROM rpt_device_control_fact USE INDEX(idx_incident_date, idx_device_type_id)
			WHERE 
			(incident_date >= par_start_date_only_insec AND incident_date < par_end_date_only_insec)
			AND device_type_id = CONVERT(par_device_type_id, UNSIGNED INTEGER)
			ORDER BY incident_date DESC
			LIMIT par_start_index,par_max_records
		) AS a, rpt_device_master_dim AS b, client_master AS c, rpt_user_master AS d
		WHERE
		a.device_id = b.device_id
		AND a.client_id = c.client_id
		AND a.user_id = d.user_id
		ORDER BY incident_date DESC;
		
	ELSE
	
		SELECT b.device_name, b.manufacturer, c.computer_name, d.username, b.serial_number, a.incident_date, c.str_ip_address
		FROM
		(
			SELECT incident_date, client_id, device_id, user_id
			FROM rpt_device_control_fact USE INDEX(idx_incident_date, idx_device_type_id)
			WHERE 
			(incident_date >= par_start_date_only_insec AND incident_date < par_end_date_only_insec)
			AND NOT FIND_IN_SET(device_type_id, par_device_type_id)
			ORDER BY incident_date DESC
			LIMIT par_start_index,par_max_records
		) AS a, rpt_device_master_dim AS b, client_master AS c, rpt_user_master AS d
		WHERE
		a.device_id = b.device_id
		AND a.client_id = c.client_id
		AND a.user_id = d.user_id
		ORDER BY incident_date DESC;
		
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS dash_compliance_devctrl_get_summary_detail_table_pr;
DELIMITER $$
CREATE PROCEDURE `dash_compliance_devctrl_get_summary_detail_table_pr`(
IN par_start_date_only_insec INT(11),
IN par_end_date_only_insec INT(11),
IN par_guid varchar(45),
IN par_user_name varchar(45),
IN par_start_index INT(11),
IN par_max_records INT(11)
)
BEGIN	

	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	
	-- get client id and user id for filter on fact table
	
	SET var_client_id = (SELECT client_id FROM client_master where guid = par_guid LIMIT 1);
	SET var_user_id = (SELECT user_id FROM rpt_user_master where username = par_user_name LIMIT 1);
	
	SELECT b.device_name, b.manufacturer, c.computer_name, par_user_name, b.serial_number, a.incident_date, c.domain_name, a.action_id 
	FROM
	(
		SELECT action_id, incident_date, device_id, client_id
		FROM rpt_device_control_fact AS a USE INDEX(idx_incident_date, idx_user_id, idx_client_id)
		WHERE 
		incident_date >= par_start_date_only_insec AND incident_date < par_end_date_only_insec
		AND user_id = var_user_id 
		AND client_id = var_client_id		 
		ORDER BY incident_date DESC
		LIMIT par_start_index, par_max_records
	) AS a, rpt_device_master_dim AS b, client_master AS c
	WHERE 
	a.device_id = b.device_id 
	AND a.client_id = c.client_id 
	ORDER BY a.incident_date DESC;
	
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS dash_network_health_get_chart_detail_count_pr;
DELIMITER $$
CREATE PROCEDURE `dash_network_health_get_chart_detail_count_pr`(
IN par_start_date_insec INT(11),
IN par_netchart_mod_type INT(11)
)
BEGIN

	DECLARE var_virus_count INT(11) DEFAULT NULL;
	DECLARE var_malicious_count INT(11) DEFAULT NULL;
	DECLARE var_phishing_count INT(11) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	
	IF 1 = par_netchart_mod_type THEN
	
		SET var_virus_count = (SELECT SUM(incident_count) FROM rpt_virus_chart_summary WHERE incident_date_only = unix_timestamp(from_unixtime(par_start_date_insec, '%Y-%m-%d'))); 
		SET var_malicious_count = (SELECT SUM(incident_count) FROM rpt_websec_chart_summary WHERE incident_date_only = unix_timestamp(from_unixtime(par_start_date_insec, '%Y-%m-%d')) AND websec_category_id = 2); 

		select (IFNULL(var_virus_count, 0) + IFNULL(var_malicious_count, 0)) AS total_count;
		
	ELSEIF 3 = par_netchart_mod_type THEN
	
		SET var_phishing_count = (SELECT SUM(incident_count) as total_count FROM rpt_websec_chart_summary WHERE incident_date_only = unix_timestamp(from_unixtime(par_start_date_insec, '%Y-%m-%d')) AND websec_category_id = 3); 
		
		select IFNULL(var_phishing_count, 0) AS total_count;
		
	END IF;
	
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS dash_network_health_get_chart_detail_table_pr;
DELIMITER $$
CREATE PROCEDURE `dash_network_health_get_chart_detail_table_pr`(
IN par_start_date_insec INT(11),
IN par_end_date_insec INT(11),
IN par_netchart_mod_type INT(11),
IN par_start_index INT(11),
IN par_max_records INT(11)
)
BEGIN

	DECLARE var_virus_count INT(11) DEFAULT NULL;
	DECLARE var_malicious_count INT(11) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	
	IF 1 = par_netchart_mod_type THEN
		
		SELECT * 
		FROM
		(
	
			SELECT incident_date, computer_name, infected_file, virus_name AS attack_name, action_taken, '1' AS charttype, b.module ,domain_name
			FROM
			(
				SELECT incident_date, client_id, virus_scan_id
				FROM rpt_virus_incident_fact AS a USE INDEX(idx_incident_date) 
				WHERE
				a.incident_date >= unix_timestamp(from_unixtime(par_start_date_insec, '%Y-%m-%d')) AND a.incident_date <= unix_timestamp(from_unixtime(par_end_date_insec, '%Y-%m-%d') + interval 1 day - interval 1 second)
			) AS a, rpt_virus_scan_dim AS b, client_master AS c 
			WHERE
			a.virus_scan_id=b.virus_scan_id AND a.client_id=c.client_id

			UNION ALL
			
			SELECT incident_date, computer_name, '-' AS infected_file, b.website AS attack_name, 'Blocked' AS action_taken, websec_category_id AS charttype, '-' AS module, domain_name
			FROM
			(
				SELECT incident_date, client_id, websec_incident_id, url_id
				FROM rpt_websec_incident_fact AS a USE INDEX(idx_incident_date, idx_websec_category_id) 
				WHERE
				a.incident_date >= unix_timestamp(from_unixtime(par_start_date_insec, '%Y-%m-%d')) AND a.incident_date <= unix_timestamp(from_unixtime(par_end_date_insec, '%Y-%m-%d') + interval 1 day - interval 1 second)
				AND websec_category_id = 2 
			) AS a, rpt_websec_bolckedsites_dim AS b, client_master AS c 
			WHERE
			a.url_id=b.url_id AND a.client_id=c.client_id
			
		) AS temp 
		ORDER BY temp.incident_date  DESC
		LIMIT par_start_index,par_max_records;
		
	ELSEIF 3 = par_netchart_mod_type THEN
	
		SELECT incident_date, computer_name, b.website AS attack_name, 'Blocked' AS action_taken, websec_category_id AS charttype
			FROM
			(
				SELECT incident_date, client_id, websec_incident_id, url_id
				FROM rpt_websec_incident_fact AS a USE INDEX(idx_incident_date, idx_websec_category_id) 
				WHERE
				a.incident_date >= unix_timestamp(from_unixtime(par_start_date_insec, '%Y-%m-%d')) AND a.incident_date <= unix_timestamp(from_unixtime(par_end_date_insec, '%Y-%m-%d') + interval 1 day - interval 1 second)
				AND websec_category_id = 3 
				ORDER BY a.incident_date DESC
				LIMIT par_start_index,par_max_records
			) AS a, rpt_websec_bolckedsites_dim AS b, client_master AS c 
			WHERE
			a.url_id=b.url_id AND a.client_id=c.client_id
			ORDER BY a.incident_date  DESC;
		
	END IF;
	
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS dash_network_health_get_summary_detail_count_pr;
DELIMITER $$
CREATE PROCEDURE `dash_network_health_get_summary_detail_count_pr`(
	IN par_start_date_only_insec INT(11),
	IN par_end_date_only_insec INT(11),
	IN par_netchart_mod_id INT(11),
	IN par_attack_name varchar(1024)
)
BEGIN
	
	DECLARE var_url_id bigint(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	
	IF 1 = par_netchart_mod_id THEN
	
		SELECT count(*) AS total_count
		FROM rpt_virus_incident_fact USE INDEX(idx_incident_date, idx_virus_scan_id)
		WHERE 
		incident_date >= par_start_date_only_insec AND incident_date < par_end_date_only_insec
		AND virus_scan_id IN 
		(
			SELECT virus_scan_id 
			FROM rpt_virus_scan_dim USE INDEX(idx_virus_name) 
			WHERE virus_name = par_attack_name
		);
	
	ELSE
	
		-- AS the ID recieved in par_netchart_mod_id is the actual category id which stored in report table
		-- So it can e used directly for processing
		
		SET var_url_id = (SELECT url_id FROM rpt_websec_bolckedsites_dim WHERE websec_category_id = par_netchart_mod_id AND website = par_attack_name LIMIT 1);
		
		SELECT count(*) AS total_count
		FROM rpt_websec_incident_fact USE INDEX(idx_incident_date, idx_url_id)
		WHERE 
		incident_date >= par_start_date_only_insec AND incident_date < par_end_date_only_insec
		AND url_id = var_url_id;
	
	END IF;
	
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS dash_network_health_get_summary_detail_table_pr;
DELIMITER $$
CREATE PROCEDURE `dash_network_health_get_summary_detail_table_pr`(
	IN par_start_date_only_insec INT(11),
	IN par_end_date_only_insec INT(11),
	IN par_netchart_mod_id INT(11),
	IN par_attack_name varchar(1024),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN
	
	DECLARE var_url_id bigint(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	
	IF 1 = par_netchart_mod_id THEN
	
		SELECT a.incident_date, c.computer_name, b.infected_file, b.virus_name, b.action_taken, '1' AS charttype, module, c.domain_Name
		FROM
		(
			SELECT incident_date, client_id, virus_scan_id
			FROM rpt_virus_incident_fact USE INDEX(idx_incident_date, idx_virus_scan_id)
			WHERE 
			incident_date >= par_start_date_only_insec AND incident_date < par_end_date_only_insec
			AND virus_scan_id IN (SELECT virus_scan_id FROM rpt_virus_scan_dim WHERE virus_name = par_attack_name)
			ORDER BY incident_date DESC 
			LIMIT par_start_index, par_max_records
		) AS a, rpt_virus_scan_dim AS b, client_master AS c
		WHERE
		a.client_id = c.client_id
		AND a.virus_scan_id = b.virus_scan_id
		ORDER BY a.incident_date DESC ;
	
	ELSEIF 2 = par_netchart_mod_id THEN
	
		SET var_url_id = (SELECT url_id FROM rpt_websec_bolckedsites_dim WHERE websec_category_id = par_netchart_mod_id AND website = par_attack_name LIMIT 1);
		
		SELECT a.incident_date, c.computer_name, '-' AS 'infected_file', b.website, 'Blocked' AS 'action_taken', b.websec_category_id AS charttype, '-' AS 'module', c.domain_Name
		FROM
		(
			SELECT incident_date, client_id
			FROM rpt_websec_incident_fact USE INDEX(idx_incident_date, idx_url_id)
			WHERE 
			incident_date >= par_start_date_only_insec AND incident_date < par_end_date_only_insec
			AND url_id = var_url_id
			ORDER BY incident_date DESC 
			LIMIT par_start_index, par_max_records
		) AS a, rpt_websec_bolckedsites_dim AS b, client_master AS c
		WHERE
		b.url_id = var_url_id
		AND a.client_id = c.client_id
		ORDER BY a.incident_date DESC ;
		
	ELSEIF 3 = par_netchart_mod_id THEN
	
		SET var_url_id = (SELECT url_id FROM rpt_websec_bolckedsites_dim WHERE websec_category_id = par_netchart_mod_id AND website = par_attack_name LIMIT 1);
		
		SELECT a.incident_date, c.computer_name, b.website, 'Blocked' AS 'action_taken', b.websec_category_id AS charttype, c.domain_Name
		FROM
		(
			SELECT incident_date, client_id
			FROM rpt_websec_incident_fact USE INDEX(idx_incident_date, idx_url_id)
			WHERE 
			incident_date >= par_start_date_only_insec AND incident_date < par_end_date_only_insec
			AND url_id = var_url_id
			ORDER BY incident_date DESC 
			LIMIT par_start_index, par_max_records
		) AS a, rpt_websec_bolckedsites_dim AS b, client_master AS c
		WHERE
		b.url_id = var_url_id
		AND a.client_id = c.client_id
		ORDER BY a.incident_date DESC ;
	
	END IF;
	
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS dash_security_dlp_oa_get_chart_detail_table_pr;
DELIMITER $$
CREATE PROCEDURE dash_security_dlp_oa_get_chart_detail_table_pr(
IN par_start_date_only_in_sec INT(11),
IN par_end_date_only_in_sec INT(11),
IN par_content_type_id INT(11),
IN par_start_index INT(11),
IN par_max_records INT(11)
)
BEGIN

	SET time_zone = '+00:00';
	
	SELECT a.incident_date, b.computer_name, b.domain_name, c.username, a.file_path, b.str_ip_address
	FROM
	(
		SELECT incident_date, client_id, user_id, file_path
		FROM rpt_dlp_oa_fact USE INDEX(idx_incident_date, idx_content_type_id)
		WHERE
		(incident_date >= par_start_date_only_in_sec AND incident_date < par_end_date_only_in_sec)
		AND content_type_id = par_content_type_id
		ORDER BY incident_date DESC 
		LIMIT par_start_index, par_max_records
	) AS a, client_master AS b, rpt_user_master AS c
	WHERE
	a.client_id = b.client_id
	AND a.user_id = c.user_id
	ORDER BY incident_date DESC;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS dash_security_dlp_oa_get_summary_detail_table_pr;
DELIMITER $$
CREATE PROCEDURE dash_security_dlp_oa_get_summary_detail_table_pr(
	IN par_start_date_only_in_sec INT(11),
	IN par_end_date_only_in_sec INT(11),
	IN par_guid varchar(45),
	IN par_username varchar(512),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN

	DECLARE var_user_id bigint(20) DEFAULT NULL;
	DECLARE var_client_id bigint(20) DEFAULT NULL;
	DECLARE var_domain_name text DEFAULT NULL;
	
	SET time_zone = '+00:00';
	
	
	SELECT client_id, domain_name INTO var_client_id, var_domain_name FROM client_master WHERE guid = par_guid limit 1;
	SET var_user_id = (SELECT user_id FROM rpt_user_master WHERE username = par_username LIMIT 1);

	SELECT incident_date, file_path, content_type, channel_type, action_taken, var_domain_name, IFNULL(sender, "") AS sender, IFNULL(receiver, "") AS receiver, IFNULL(subject, "") AS subject
	FROM rpt_dlp_oa_fact USE INDEX(idx_incident_date, idx_client_id, idx_user_id)
	WHERE
	(incident_date >= par_start_date_only_in_sec AND incident_date < par_end_date_only_in_sec)
	AND client_id = var_client_id
	AND user_id = var_user_id
	ORDER BY incident_date DESC 
	LIMIT par_start_index, par_max_records;
	
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS tuneup_rpt_get_chart_pr;
DELIMITER $$
CREATE DEFINER=`qhepsroot`@`%` PROCEDURE `tuneup_rpt_get_chart_pr`(
	IN par_group_id int(11)
)
BEGIN

	DECLARE var_tuned_in_7 int(11) DEFAULT NULL;
	DECLARE var_tuned_in_15 int(11) DEFAULT NULL;
	DECLARE var_not_tuned int(11) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	
	IF par_group_id > 0 THEN
		SET var_tuned_in_7 = 
			(
				SELECT COUNT(*) AS tuned_in_7
				FROM client_master AS a, clientav AS b
				WHERE 
				a.guid = b.guid 
				AND a.GroupId = par_group_id
				AND (a.Client_Status <> 8 AND (a.Client_Type & 8) = 8)
				AND unix_timestamp(DATE_FORMAT(from_unixtime(b.LastTuneUpDate), '%Y-%m-%d')) > unix_timestamp((GetCurrentDate() + interval -7 day))
			);
				
		SET var_tuned_in_15 = 
			(
				SELECT COUNT(*)  AS tuned_in_15
				FROM client_master AS a, clientav AS b
				WHERE 
				a.guid = b.guid 
				AND a.GroupId = par_group_id
				AND (a.Client_Status <> 8 AND (a.Client_Type & 8) = 8)
				AND unix_timestamp(DATE_FORMAT(from_unixtime(b.LastTuneUpDate), '%Y-%m-%d')) > unix_timestamp((GetCurrentDate() + INTERVAL -15 DAY))
			);
			
		SET var_not_tuned = 
			(
						
				SELECT COUNT(*) AS not_tuned
				FROM client_master AS a, clientav AS b
				where 
				a.guid = b.guid 
				AND a.GroupId = par_group_id
				AND (a.Client_Status <> 8 AND (a.Client_Type & 8) = 8)
				AND unix_timestamp(DATE_FORMAT(from_unixtime(b.LastTuneUpDate), '%Y-%m-%d')) <= unix_timestamp((GetCurrentDate() + INTERVAL -15 DAY))

			);
	ELSE
		SET var_tuned_in_7 = 
			(
				SELECT COUNT(*) AS tuned_in_7
				FROM client_master AS a, clientav AS b
				WHERE 
				a.guid = b.guid 			
				AND (a.Client_Status <> 8 AND (a.Client_Type & 8) = 8)
				AND unix_timestamp(DATE_FORMAT(from_unixtime(b.LastTuneUpDate), '%Y-%m-%d')) > unix_timestamp((GetCurrentDate() + interval -7 day))
			);
				
		SET var_tuned_in_15 = 
			(
				SELECT COUNT(*)  AS tuned_in_15
				FROM client_master AS a, clientav AS b
				WHERE 
				a.guid = b.guid 			
				AND (a.Client_Status <> 8 AND (a.Client_Type & 8) = 8)
				AND unix_timestamp(DATE_FORMAT(from_unixtime(b.LastTuneUpDate), '%Y-%m-%d')) > unix_timestamp((GetCurrentDate() + INTERVAL -15 DAY))
			);
			
		SET var_not_tuned = 
			(
						
				SELECT COUNT(*) AS not_tuned
				FROM client_master AS a, clientav AS b
				where 
				a.guid = b.guid             
				AND (a.Client_Status <> 8 AND (a.Client_Type & 8) = 8)
				AND unix_timestamp(DATE_FORMAT(from_unixtime(b.LastTuneUpDate), '%Y-%m-%d')) <= unix_timestamp((GetCurrentDate() + INTERVAL -15 DAY))

			);
	END IF;

	SELECT var_tuned_in_7 AS tuned_in_7, var_tuned_in_15 AS tuned_in_15, var_not_tuned AS not_tuned;

END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS tuneup_rpt_get_count_pr;
DELIMITER $$
CREATE DEFINER=`qhepsroot`@`%` PROCEDURE `tuneup_rpt_get_count_pr`(
	IN par_group_id int(11)
)
BEGIN

	-- As in case of tuneup LastTuneupdate is in UTC instead of local, Here time zone is set to 'SYSTEM'
	SET time_zone = 'SYSTEM';
	IF par_group_id > 0 THEN -- To handle '-1' groupId from Export All Reports
		SELECT COUNT(*) AS record_count
		FROM client_master AS a, clientav AS b
		WHERE 
		a.guid = b.guid 
		AND a.GroupId = par_group_id
		AND	(a.client_status <> 8 AND (a.client_type & 8) = 8)
		AND 0 < b.LastTuneUpDate;
	ELSE
		SELECT COUNT(*) AS record_count
		FROM client_master AS a, clientav AS b
		WHERE 
		a.guid = b.guid 		
		AND	(a.client_status <> 8 AND (a.client_type & 8) = 8)
		AND 0 < b.LastTuneUpDate;
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS tuneup_rpt_get_table_pr;
DELIMITER $$
CREATE DEFINER=`qhepsroot`@`%` PROCEDURE `tuneup_rpt_get_table_pr`(
	IN par_group_id int(11),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN

	-- As in case of tuneup LastTuneupdate is in UTC instead of local, Here time zone is set to 'SYSTEM'
	SET time_zone = 'SYSTEM';
	IF par_group_id = -1 THEN -- To Export All Reports
		SELECT from_unixtime(b.LastTuneUpDate) as incident_date, a.computer_name, a.domain_name,
		((unix_timestamp(DATE(now()))-unix_timestamp(DATE_FORMAT(from_unixtime(b.LastTuneUpDate), '%Y-%m-%d'))) / 86400) AS last_performed,
        IF ('last_performed' > 15, 3, 4) as tuneup_status, b.LastTuneUpDate AS incident_date_in_seconds
		FROM client_master AS a, clientav AS b
		WHERE 
		a.guid = b.guid
		AND	(a.client_status <> 8 AND (a.client_type & 8) = 8)
		AND 0 < b.LastTuneUpDate
		ORDER BY b.LastTuneUpDate DESC LIMIT par_start_index,par_max_records;
	ELSEIF par_group_id <> 0 THEN
		SELECT from_unixtime(b.LastTuneUpDate) as incident_date, a.computer_name, a.domain_name,
		((unix_timestamp(DATE(now()))-unix_timestamp(DATE_FORMAT(from_unixtime(b.LastTuneUpDate), '%Y-%m-%d'))) / 86400) AS last_performed,
        IF ('last_performed' > 15, 3, 4) as tuneup_status, b.LastTuneUpDate AS incident_date_in_seconds
		FROM client_master AS a, clientav AS b
		WHERE 
		a.guid = b.guid 
		AND a.GroupId = par_group_id
		AND	(a.client_status <> 8 AND (a.client_type & 8) = 8)
		AND 0 < b.LastTuneUpDate
		ORDER BY b.LastTuneUpDate DESC
		LIMIT par_start_index, par_max_records;
	ELSE
		SELECT from_unixtime(b.LastTuneUpDate) as incident_date, a.computer_name, a.domain_name, 
		((unix_timestamp(DATE(now()))-unix_timestamp(DATE_FORMAT(from_unixtime(b.LastTuneUpDate), '%Y-%m-%d'))) / 86400) AS last_performed,
	    IF ('last_performed' > 15, 3, 4) as tuneup_status, b.LastTuneUpDate AS incident_date_in_seconds
		FROM client_master AS a, clientav AS b
		WHERE 
		a.guid = b.guid 		
		AND	(a.client_status <> 8 AND (a.client_type & 8) = 8)
		AND 0 < b.LastTuneUpDate
		ORDER BY b.LastTuneUpDate DESC
		LIMIT par_start_index, par_max_records;
	END IF;

END $$
DELIMITER ;



CREATE OR REPLACE VIEW dash_view AS
SELECT incident_date, sod, name, sum(namecnt) as namecnt, COUNT(DISTINCT m_id) AS machcnt, charttype, orgtype
FROM dash_chart
GROUP BY sod, name;

-- START : Event Logs --

DROP PROCEDURE IF EXISTS `eventlogs_rpt_get_table_pr`;
DELIMITER $$
CREATE PROCEDURE `eventlogs_rpt_get_table_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_category_id INT(11),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN -- To Export All Reports
	
		SELECT from_unixtime(log_date) AS log_date, log_type, message, log_date AS log_date_in_seconds FROM event_log ORDER BY log_date DESC LIMIT par_start_index,par_max_records;
		
	ELSE
	
		IF par_category_id <> 0 THEN
		
			SELECT from_unixtime(log_date) AS log_date, log_type, message, log_date AS log_date_in_seconds
			FROM event_log AS a
			WHERE
			a.log_date >= unix_timestamp(par_start_date) AND a.log_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
			AND a.log_type = par_category_id
			ORDER BY log_date DESC LIMIT par_start_index,par_max_records;

		ELSEIF par_category_id = 0 THEN
		
			SELECT from_unixtime(log_date) AS log_date, log_type, message, log_date AS log_date_in_seconds
			FROM event_log AS a
			WHERE
			a.log_date >= unix_timestamp(par_start_date) AND a.log_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
			ORDER BY log_date DESC LIMIT par_start_index,par_max_records;
			
		END IF;
		
	END IF;
	
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `eventlogs_rpt_get_count_pr`;
DELIMITER $$
CREATE PROCEDURE `eventlogs_rpt_get_count_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_category INT(11)
)
BEGIN
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN -- To Export All Reports
	
		SELECT IFNULL(COUNT(*), 0) AS record_count FROM event_log;
		
	ELSE
	
		IF par_category <> 0 THEN
			SELECT IFNULL(COUNT(*), 0) AS record_count
			FROM event_log AS a
			WHERE
			a.log_date >= unix_timestamp(par_start_date) AND a.log_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
			AND a.log_type = par_category;
		ELSE
			SELECT IFNULL(COUNT(*), 0) AS record_count
			FROM event_log AS a
			WHERE
			a.log_date >= unix_timestamp(par_start_date) AND a.log_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second);
		END IF;
		
	END IF;
END$$
DELIMITER ;


-- END : Event Logs --

-- START : Event Notifications --


-- EVT_INFO_VIRUS_FOUND

DROP PROCEDURE IF EXISTS evt_notification_get_virus_found_pr;
DELIMITER $$
CREATE PROCEDURE evt_notification_get_virus_found_pr(
IN par_guid VARCHAR(45)
)
BEGIN
	
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	DECLARE var_virus_incident_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00'; 
	
	SET var_client_id = (SELECT client_id from client_master WHERE guid = par_guid);
	SET var_virus_incident_id = (SELECT MAX(virus_incident_id) AS virus_incident_id FROM rpt_virus_incident_fact WHERE client_id = var_client_id
	AND module_id <> 8021);
	
	SELECT b.virus_name, c.computer_name, c.domain_name, b.infected_file, a.incident_date, b.action_taken, b.module, d.username, c.str_ip_address
	FROM
	(
	SELECT client_id, incident_date, virus_scan_id, user_id
	FROM rpt_virus_incident_fact 
	WHERE 
	virus_incident_id = var_virus_incident_id
	) AS a, rpt_virus_scan_dim AS b, client_master AS c, rpt_user_master AS d
	WHERE
	a.virus_scan_id = b.virus_scan_id
	AND a.client_id = c.client_id
	AND a.user_id = d.user_id;
	
END $$
DELIMITER ;

-- EVT_INFO_RANSOMWARE_FOUND

DROP PROCEDURE IF EXISTS evt_notification_get_ransomware_found_pr;
DELIMITER $$
CREATE PROCEDURE evt_notification_get_ransomware_found_pr(
IN par_guid VARCHAR(45),
IN par_module_id INT(11)
)
BEGIN
	
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	DECLARE var_virus_incident_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00'; 
	
	SET var_client_id = (SELECT client_id from client_master WHERE guid = par_guid);
	SET var_virus_incident_id = (SELECT MAX(virus_incident_id) AS virus_incident_id FROM rpt_virus_incident_fact WHERE client_id = var_client_id AND module_id = par_module_id);
	
	SELECT b.virus_name, c.computer_name, c.domain_name, b.infected_file, a.incident_date, b.action_taken, b.module, d.username, c.str_ip_address
	FROM
	(
	SELECT client_id, incident_date, virus_scan_id, user_id
	FROM rpt_virus_incident_fact 
	WHERE 
	virus_incident_id = var_virus_incident_id
	) AS a, rpt_virus_scan_dim AS b, client_master AS c, rpt_user_master AS d
	WHERE
	a.virus_scan_id = b.virus_scan_id
	AND a.client_id = c.client_id
	AND a.user_id = d.user_id;
	
END $$
DELIMITER ;

-- EVT_INFO_VIRUS_FOUND_IN_MEMORY
DROP PROCEDURE IF EXISTS evt_notification_get_virus_found_in_memory_pr;
DELIMITER $$
CREATE PROCEDURE evt_notification_get_virus_found_in_memory_pr(
IN par_guid VARCHAR(45)
)
BEGIN
	
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	DECLARE var_virus_incident_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00'; 
	
	SET var_client_id = (SELECT client_id from client_master WHERE guid = par_guid);
	SET var_virus_incident_id = (
									SELECT MAX(virus_incident_id) AS virus_incident_id 
									FROM rpt_virus_incident_fact AS a, rpt_virus_scan_dim AS b 
									WHERE 
									a.client_id = var_client_id
									AND b.module_id = 8007
								);
	
	SELECT b.virus_name, c.computer_name, c.domain_name, b.infected_file, a.incident_date, b.action_taken, b.module, d.username, c.str_ip_address
	FROM
	(
	SELECT client_id, incident_date, virus_scan_id, user_id
	FROM rpt_virus_incident_fact 
	WHERE 
	virus_incident_id = var_virus_incident_id
	) AS a, rpt_virus_scan_dim AS b, client_master AS c, rpt_user_master AS d
	WHERE
	a.virus_scan_id = b.virus_scan_id
	AND a.client_id = c.client_id
	AND a.user_id = d.user_id;
	
END $$
DELIMITER ;

-- EVT_INFO_VIRUS_OUTBREAK
DROP PROCEDURE IF EXISTS evt_notification_get_virus_found_outbreak_pr;
DELIMITER $$
CREATE PROCEDURE evt_notification_get_virus_found_outbreak_pr(
IN par_X_min_back int(11)
)
BEGIN
	
	DECLARE var_virus_count INT(11) DEFAULT NULL;
	DECLARE var_machine_count INT(11) DEFAULT NULL;
	
	SET time_zone = '+00:00'; 
	
	-- VIRSCAN_MODULE_VIRUS_PROTECTION				8001
	-- VIRSCAN_MODULE_EMAIL_PROTECTION				8002
	-- VIRSCAN_MODULE_MEMORY_SCAN					8007

	
	SET var_virus_count = (
	SELECT COUNT(b.virus_name) AS virus_count
	FROM rpt_virus_incident_fact AS a, rpt_virus_scan_dim AS b 
	WHERE
	(unix_timestamp(convert_tz(now(), '+0:0', 'system') ) >= a.incident_date AND unix_timestamp(date_sub(convert_tz(now(), '+0:0', 'system'), interval par_X_min_back minute)) <= a.incident_date)
	AND a.virus_scan_id = b.virus_scan_id
	AND (b.module_id = 8001
	OR b.module_id = 8002
	OR b.module_id = 8007)
	);
	
	
	SET var_machine_count = (
	SELECT COUNT(DISTINCT a.client_id) AS virus_count
	FROM rpt_virus_incident_fact AS a, rpt_virus_scan_dim AS b 
	WHERE
	(unix_timestamp(convert_tz(now(), '+0:0', 'system') ) >= a.incident_date AND unix_timestamp(date_sub(convert_tz(now(), '+0:0', 'system'), interval par_X_min_back minute)) <= a.incident_date)
	AND a.virus_scan_id = b.virus_scan_id
	AND (b.module_id = 8001
	OR b.module_id = 8002
	OR b.module_id = 8007)
	);
	
	SELECT var_virus_count AS virus_count, var_machine_count AS machine_count;
	
END $$
DELIMITER ;

-- EVT_INFO_INTRUSION_PREVENTION
DROP PROCEDURE IF EXISTS evt_notification_get_ips_pr;
DELIMITER $$
CREATE PROCEDURE evt_notification_get_ips_pr(
IN par_guid varchar(45)
)
BEGIN
	
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	DECLARE var_ips_id BIGINT(20) DEFAULT NULL;
		
	SET time_zone = '+00:00'; 
	
	SET var_client_id = (SELECT client_id from client_master WHERE guid = par_guid);
	SET var_ips_id = (SELECT MAX(ips_id) AS ips_id FROM rpt_ips_fact WHERE client_id = var_client_id);
	
	SELECT b.computer_name, a.vulnerability, a.rule_desc, a.rule_ref, b.domain_name, a.incident_date, c.username, b.str_ip_address
	FROM rpt_ips_fact AS a, client_master AS b, rpt_user_master AS c
	WHERE 
	a.ips_id = var_ips_id
	AND a.client_id = b.client_id
	AND a.user_id = c.user_id;
	
END $$
DELIMITER ;

-- EVT_INFO_PORT_SCAN
DROP PROCEDURE IF EXISTS evt_notification_get_port_scan_pr;
DELIMITER $$
CREATE PROCEDURE evt_notification_get_port_scan_pr(
IN par_guid varchar(45)
)
BEGIN
	
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	DECLARE var_port_scan_id BIGINT(20) DEFAULT NULL;
		
	SET time_zone = '+00:00'; 
	
	SET var_client_id = (SELECT client_id from client_master WHERE guid = par_guid);
	SET var_port_scan_id = (SELECT MAX(port_scan_id) AS port_scan_id FROM rpt_port_scan_fact WHERE client_id = var_client_id);
	
	SELECT b.computer_name, a.attacker_ip, a.attacker_mac, a.scanports, a.action_taken
	FROM rpt_port_scan_fact AS a, client_master AS b
	WHERE 
	a.port_scan_id = var_port_scan_id
	AND a.client_id = b.client_id;
	
END $$
DELIMITER ;

-- EVT_INFO_APP_CONTROL
DROP PROCEDURE IF EXISTS evt_notification_get_app_ctrl_pr;
DELIMITER $$
CREATE PROCEDURE evt_notification_get_app_ctrl_pr(
IN par_guid varchar(45)
)
BEGIN
	
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	DECLARE var_rowid BIGINT(11) DEFAULT NULL;
		
	SET time_zone = '+00:00'; 
	
	SET var_client_id = (SELECT client_id from client_master WHERE guid = par_guid);
	SET var_rowid = (SELECT MAX(rowid) AS rowid FROM rpt_appcon_oa_fact WHERE client_id = var_client_id);
	
	SELECT b.computer_name, a.application_name, c.username, b.str_ip_address, b.domain_name, a.incident_date
	FROM rpt_appcon_oa_fact AS a, client_master AS b, rpt_user_master AS c
	WHERE 
	a.rowid = (SELECT MAX(rowid) AS rowid FROM rpt_appcon_oa_fact WHERE client_id = var_client_id)
	AND a.client_id = b.client_id
	AND a.user_id = c.user_id;
	
END $$
DELIMITER ;

-- EVT_INFO_DEVICE_CONTROL
DROP PROCEDURE IF EXISTS evt_notification_get_device_ctrl_pr;
DELIMITER $$
CREATE PROCEDURE evt_notification_get_device_ctrl_pr(
IN par_guid varchar(45)
)
BEGIN
	
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	DECLARE var_rowid BIGINT(20) DEFAULT NULL;
		
	SET time_zone = '+00:00'; 
	
	SET var_client_id = (SELECT client_id from client_master WHERE guid = par_guid);
	SET var_rowid = (SELECT MAX(rowid) AS rowid FROM rpt_device_control_fact WHERE client_id = var_client_id AND IsNotify = FALSE);
	
	SELECT b.guid, b.computer_name, c.device_name, a.action_id, d.username, b.str_ip_address, b.domain_name, a.incident_date
	FROM rpt_device_control_fact AS a, client_master AS b, rpt_device_master_dim AS c, rpt_user_master AS d
	WHERE 
	a.rowid = var_rowid
	AND a.device_id = c.device_id
	AND a.client_id = b.client_id
	AND a.user_id = d.user_id;
	
	UPDATE rpt_device_control_fact SET IsNotify = TRUE WHERE rowid = var_rowid;
	
END $$
DELIMITER ;

-- EVT_INFO_DATA_LEAK_PREV

DROP PROCEDURE IF EXISTS evt_notification_get_dlp_oa_pr;
DELIMITER $$
CREATE PROCEDURE evt_notification_get_dlp_oa_pr(
IN par_guid varchar(45)
)
BEGIN
	
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	DECLARE var_rowid BIGINT(20) DEFAULT NULL;
		
	SET time_zone = '+00:00'; 
	
	SET var_client_id = (SELECT client_id from client_master WHERE guid = par_guid);
	SET var_rowid = (SELECT MAX(rowid) AS rowid FROM rpt_dlp_oa_fact WHERE client_id = var_client_id);
	
	SELECT b.guid, b.computer_name, a.content_type, a.channel_type_id, a.channel_type, a.channel_details, a.matched_item, a.file_path, a.action_taken, a.sender, a.receiver, a.subject, c.username, b.str_ip_address, b.domain_name, a.incident_date
	FROM rpt_dlp_oa_fact AS a, client_master AS b, rpt_user_master AS c
	WHERE 
	a.rowid = var_rowid
	AND a.client_id = b.client_id
	AND a.user_id = c.user_id;
	
END $$
DELIMITER ;

-- EVT_INFO_ASSET_MGMT

--	ASSET_MGMT_CATEGORY_ALL = 0
--	ASSET_MGMT_CATEGORY_SOFTWARE = 1
--	ASSET_MGMT_CATEGORY_HARDWARE = 2

DROP PROCEDURE IF EXISTS evt_notification_get_asset_mgmt_pr;
DELIMITER $$
CREATE PROCEDURE evt_notification_get_asset_mgmt_pr(
IN par_guid varchar(45)
)
BEGIN
	
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	DECLARE var_rowid BIGINT(11) DEFAULT NULL;
		
	SET time_zone = '+00:00'; 
	
	SET var_client_id = (SELECT client_id from client_master WHERE guid = par_guid);
	SET var_rowid = (SELECT MAX(rowid) AS rowid FROM rpt_asset_mgnt_fact WHERE client_id = var_client_id AND category_id = 2);
	
	SELECT b.guid, b.computer_name, a.asset_name, a.details, a.asset_id, c.username, b.domain_name
	FROM rpt_asset_mgnt_fact AS a, client_master AS b, rpt_user_master AS c
	WHERE 
	a.rowid = var_rowid
	AND a.client_id = b.client_id
	AND a.user_id = c.user_id
	AND a.asset_id <> 0
	AND a.asset_id <> 8
	AND a.asset_id <> 7
	AND a.asset_id <> 13;
	
END $$
DELIMITER ;

-- END : Event Notifications --

-- START : DELETE REPORTS --

DROP PROCEDURE IF EXISTS delete_rpt_by_days_pr;
DELIMITER $$
CREATE PROCEDURE delete_rpt_by_days_pr(
IN par_X_days_back int(11),
IN par_report_type int(11)
)
BEGIN 

	IF 0 = par_report_type THEN
	
		-- VIRUS SCAN
		DELETE FROM rpt_virus_incident_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_virus_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- ANTI MALWARE
		DELETE FROM rpt_anti_malware_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_anti_malware_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- WEB SECURITY
		DELETE FROM rpt_websec_incident_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_websec_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- DEVICE CONTROL
		DELETE FROM rpt_device_control_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_device_chart_summary_1 WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		DELETE FROM rpt_device_chart_summary_2 WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- DATA LEAK PREVENTION (ON ACCESS)
		DELETE FROM rpt_dlp_oa_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_dlp_oa_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		DELETE FROM rpt_dlp_oa_application_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		DELETE FROM rpt_dlp_oa_content_type_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;

		-- DATA LEAK PREVENTION (ON DEMAND)
		DELETE FROM rpt_dlp_od_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_dlp_od_summarized_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > scan_start_date;

		-- APPLICATION CONTROL (ON ACCESS)
		DELETE FROM rpt_appcon_oa_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_appcon_oa_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- APPLICATION CONTROL (ON DEMAND)
		DELETE FROM rpt_appcon_od_summarized_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		
		-- INSTRUCTION PREVENTION
		DELETE FROM rpt_ips_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_ips_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- PORT SCAN
		DELETE FROM rpt_port_scan_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_port_scan_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- DDOS
		DELETE FROM rpt_ddos_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_ddos_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- FIREWALL
		DELETE FROM rpt_firewall_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		
		-- VULNERABILITY SCAN
		DELETE FROM rpt_vuln_incident_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_vuln_severity_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		DELETE FROM rpt_vuln_topvuln_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		DELETE FROM rpt_vuln_vendor_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- FILE ACTIVITY MONITOR
		DELETE FROM rpt_fam_incident_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_fam_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		DELETE FROM rpt_fam_extn_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- ASSET MANAGEMENT
		DELETE FROM rpt_asset_mgnt_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_asset_mgnt_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- PATCH SCAN
		DELETE FROM rpt_patch_management_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_patch_all_records_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		DELETE FROM rpt_patch_clientwise_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		DELETE FROM rpt_patch_patchwise_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- FIREWALL WIFI
		DELETE FROM rpt_wifi_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_wifi_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- EVENT LOG
		DELETE FROM event_log WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > log_date;
		
	ELSEIF 1 = par_report_type THEN
	
		-- VIRUS SCAN
		DELETE FROM rpt_virus_incident_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_virus_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- ANTI MALWARE
		DELETE FROM rpt_anti_malware_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_anti_malware_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- WEB SECURITY
		DELETE FROM rpt_websec_incident_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_websec_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- DEVICE CONTROL
		DELETE FROM rpt_device_control_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_device_chart_summary_1 WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		DELETE FROM rpt_device_chart_summary_2 WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- DATA LEAK PREVENTION (ON ACCESS)
		DELETE FROM rpt_dlp_oa_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_dlp_oa_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		DELETE FROM rpt_dlp_oa_application_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		DELETE FROM rpt_dlp_oa_content_type_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;

		-- DATA LEAK PREVENTION (ON DEMAND)
		DELETE FROM rpt_dlp_od_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_dlp_od_summarized_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > scan_start_date;

		-- APPLICATION CONTROL (ON ACCESS)
		DELETE FROM rpt_appcon_oa_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_appcon_oa_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- APPLICATION CONTROL (ON DEMAND)
		DELETE FROM rpt_appcon_od_summarized_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		
		-- INSTRUCTION PREVENTION
		DELETE FROM rpt_ips_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_ips_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- PORT SCAN
		DELETE FROM rpt_port_scan_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_port_scan_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- DDOS
		DELETE FROM rpt_ddos_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_ddos_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- FIREWALL
		DELETE FROM rpt_firewall_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		
		-- VULNERABILITY SCAN
		DELETE FROM rpt_vuln_incident_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_vuln_severity_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		DELETE FROM rpt_vuln_topvuln_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		DELETE FROM rpt_vuln_vendor_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- FILE ACTIVITY MONITOR
		DELETE FROM rpt_fam_incident_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_fam_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		DELETE FROM rpt_fam_extn_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- ASSET MANAGEMENT
		DELETE FROM rpt_asset_mgnt_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_asset_mgnt_chart_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- PATCH SCAN
		DELETE FROM rpt_patch_management_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_patch_all_records_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		DELETE FROM rpt_patch_clientwise_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		DELETE FROM rpt_patch_patchwise_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
		-- FIREWALL WIFI
		DELETE FROM rpt_wifi_fact WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date;
		DELETE FROM rpt_wifi_summary WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > incident_date_only;
		
	ELSEIF 2 = par_report_type THEN
	
		DELETE FROM event_log WHERE unix_timestamp(GetCurrentDate() - INTERVAL par_X_days_back DAY) > log_date;
		
	END IF;
		
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS delete_all_rpt_pr;
DELIMITER $$
CREATE PROCEDURE delete_all_rpt_pr(
IN par_report_type int(11)
)
BEGIN 
	
	IF 0 = par_report_type THEN
	
		TRUNCATE TABLE rpt_anti_malware_chart_summary;
		TRUNCATE TABLE rpt_anti_malware_fact;
		TRUNCATE TABLE rpt_app_category_master;
		TRUNCATE TABLE rpt_appcon_oa_chart_summary;
		TRUNCATE TABLE rpt_appcon_oa_fact;
		TRUNCATE TABLE rpt_appcon_od_fact;
		TRUNCATE TABLE rpt_appcon_od_summarized_fact;
		TRUNCATE TABLE rpt_asset_mgnt_chart_summary;
		TRUNCATE TABLE rpt_asset_mgnt_fact;
		TRUNCATE TABLE rpt_ddos_fact;
		TRUNCATE TABLE rpt_ddos_chart_summary;
		TRUNCATE TABLE rpt_device_chart_summary_1;
		TRUNCATE TABLE rpt_device_chart_summary_2;
		TRUNCATE TABLE rpt_device_control_fact;
		TRUNCATE TABLE rpt_device_master_dim;
		TRUNCATE TABLE rpt_dlp_application_master_dim;
		TRUNCATE TABLE rpt_dlp_oa_application_summary;
		TRUNCATE TABLE rpt_dlp_oa_content_type_summary;
		TRUNCATE TABLE rpt_dlp_oa_fact;
		TRUNCATE TABLE rpt_dlp_oa_summary;
		TRUNCATE TABLE rpt_dlp_od_chart_summary;
		TRUNCATE TABLE rpt_dlp_od_fact;
		TRUNCATE TABLE rpt_dlp_od_summarized_fact;
		TRUNCATE TABLE event_log;
		TRUNCATE TABLE rpt_fam_chart_summary;
		TRUNCATE TABLE rpt_fam_extn_summary;
		TRUNCATE TABLE rpt_fam_file_master_dim;
		TRUNCATE TABLE rpt_fam_incident_fact;
		TRUNCATE TABLE rpt_firewall_fact;
		TRUNCATE TABLE rpt_ips_fact;
		TRUNCATE TABLE rpt_ips_chart_summary;
		TRUNCATE TABLE rpt_port_scan_fact;
		TRUNCATE TABLE rpt_port_scan_chart_summary;
		TRUNCATE TABLE rpt_tuneup_fact;
		TRUNCATE TABLE rpt_virus_chart_summary;
		TRUNCATE TABLE rpt_virus_incident_fact;
		TRUNCATE TABLE rpt_virus_scan_dim;
		TRUNCATE TABLE rpt_vuln_affected_platforms_dim;
		TRUNCATE TABLE rpt_vuln_affected_products_dim;
		TRUNCATE TABLE rpt_vuln_incident_fact;
		TRUNCATE TABLE rpt_vuln_master_dim;
		TRUNCATE TABLE rpt_vuln_references_dim;
		TRUNCATE TABLE rpt_vuln_severity_chart_summary;
		TRUNCATE TABLE rpt_vuln_topvuln_chart_summary;
		TRUNCATE TABLE rpt_vuln_vendor_chart_summary;
		TRUNCATE TABLE rpt_vuln_vendor_master_dim;
		TRUNCATE TABLE rpt_websec_bolckedsites_dim;
		TRUNCATE TABLE rpt_websec_category_dim;
		TRUNCATE TABLE rpt_websec_chart_summary;
		TRUNCATE TABLE rpt_websec_incident_fact;
		TRUNCATE TABLE rpt_patch_all_records_summary;
		TRUNCATE TABLE rpt_patch_clientwise_summary;
		TRUNCATE TABLE rpt_patch_management_fact;
		TRUNCATE TABLE rpt_patch_patchwise_summary;
		TRUNCATE TABLE rpt_wifi_fact;
		TRUNCATE TABLE rpt_wifi_summary;
		
		TRUNCATE TABLE web_security_optm; 
		TRUNCATE TABLE dlp_optm_chart; 
		TRUNCATE TABLE dlp_optm_summary; 
		TRUNCATE TABLE devctrl_optm_chart;
		TRUNCATE TABLE devctrl_optm_summary; 
		TRUNCATE TABLE appctrl_optm_chart; 
		TRUNCATE TABLE appctrl_optm_summary; 
		TRUNCATE TABLE vulnscan_optm_summary;
		TRUNCATE TABLE dash_chart; 
		TRUNCATE TABLE dash_summary; 
		TRUNCATE TABLE dash_top_attacks; 
		TRUNCATE TABLE dash_threat_meter;
		TRUNCATE TABLE dashboard_cloud;
	
		UPDATE cld_delete_rpt_status SET delete_status = 1;
		
	ELSEIF 1 = par_report_type THEN
	
		TRUNCATE TABLE rpt_anti_malware_chart_summary;
		TRUNCATE TABLE rpt_anti_malware_fact;
		TRUNCATE TABLE rpt_app_category_master;
		TRUNCATE TABLE rpt_appcon_oa_chart_summary;
		TRUNCATE TABLE rpt_appcon_oa_fact;
		TRUNCATE TABLE rpt_appcon_od_fact;
		TRUNCATE TABLE rpt_appcon_od_summarized_fact;
		TRUNCATE TABLE rpt_asset_mgnt_chart_summary;
		TRUNCATE TABLE rpt_asset_mgnt_fact;
		TRUNCATE TABLE rpt_ddos_fact;
		TRUNCATE TABLE rpt_device_chart_summary_1;
		TRUNCATE TABLE rpt_device_chart_summary_2;
		TRUNCATE TABLE rpt_device_control_fact;
		TRUNCATE TABLE rpt_device_master_dim;
		TRUNCATE TABLE rpt_dlp_application_master_dim;
		TRUNCATE TABLE rpt_dlp_oa_application_summary;
		TRUNCATE TABLE rpt_dlp_oa_content_type_summary;
		TRUNCATE TABLE rpt_dlp_oa_fact;
		TRUNCATE TABLE rpt_dlp_oa_summary;
		TRUNCATE TABLE rpt_dlp_od_chart_summary;
		TRUNCATE TABLE rpt_dlp_od_fact;
		TRUNCATE TABLE rpt_dlp_od_summarized_fact;
		TRUNCATE TABLE rpt_fam_chart_summary;
		TRUNCATE TABLE rpt_fam_extn_summary;
		TRUNCATE TABLE rpt_fam_file_master_dim;
		TRUNCATE TABLE rpt_fam_incident_fact;
		TRUNCATE TABLE rpt_firewall_fact;
		TRUNCATE TABLE rpt_ips_fact;
		TRUNCATE TABLE rpt_port_scan_fact;
		TRUNCATE TABLE rpt_tuneup_fact;
		TRUNCATE TABLE rpt_virus_chart_summary;
		TRUNCATE TABLE rpt_virus_incident_fact;
		TRUNCATE TABLE rpt_virus_scan_dim;
		TRUNCATE TABLE rpt_vuln_affected_platforms_dim;
		TRUNCATE TABLE rpt_vuln_affected_products_dim;
		TRUNCATE TABLE rpt_vuln_incident_fact;
		TRUNCATE TABLE rpt_vuln_master_dim;
		TRUNCATE TABLE rpt_vuln_references_dim;
		TRUNCATE TABLE rpt_vuln_severity_chart_summary;
		TRUNCATE TABLE rpt_vuln_topvuln_chart_summary;
		TRUNCATE TABLE rpt_vuln_vendor_chart_summary;
		TRUNCATE TABLE rpt_vuln_vendor_master_dim;
		TRUNCATE TABLE rpt_websec_bolckedsites_dim;
		TRUNCATE TABLE rpt_websec_category_dim;
		TRUNCATE TABLE rpt_websec_chart_summary;
		TRUNCATE TABLE rpt_websec_incident_fact;
		TRUNCATE TABLE rpt_patch_all_records_summary;
		TRUNCATE TABLE rpt_patch_clientwise_summary;
		TRUNCATE TABLE rpt_patch_management_fact;
		TRUNCATE TABLE rpt_patch_patchwise_summary;
		TRUNCATE TABLE rpt_wifi_fact;
		TRUNCATE TABLE rpt_wifi_summary;
		
		TRUNCATE TABLE web_security_optm; 
		TRUNCATE TABLE dlp_optm_chart; 
		TRUNCATE TABLE dlp_optm_summary; 
		TRUNCATE TABLE devctrl_optm_chart;
		TRUNCATE TABLE devctrl_optm_summary; 
		TRUNCATE TABLE appctrl_optm_chart; 
		TRUNCATE TABLE appctrl_optm_summary; 
		TRUNCATE TABLE vulnscan_optm_summary;
		TRUNCATE TABLE dash_chart; 
		TRUNCATE TABLE dash_summary; 
		TRUNCATE TABLE dash_top_attacks; 
		TRUNCATE TABLE dash_threat_meter;
		TRUNCATE TABLE dashboard_cloud;
		
		UPDATE cld_delete_rpt_status SET delete_status = 1;
	
	ELSEIF 2 = par_report_type THEN
	
		TRUNCATE TABLE event_log;
		
	END IF;
	
	
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS delete_server_event_log_rpt_pr;
DELIMITER $$
CREATE PROCEDURE delete_server_event_log_rpt_pr(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_category INT(11)
)
BEGIN	
	IF par_category <> 0 THEN
		DELETE FROM event_log 
		WHERE
		log_date >= unix_timestamp(par_start_date) AND log_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
		AND log_type = par_category;
	ELSE
		DELETE FROM event_log
		WHERE
		log_date >= unix_timestamp(par_start_date) AND log_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second);
	END IF;
END$$
DELIMITER ;

-- END : DELETE REPORTS --

DROP PROCEDURE IF EXISTS `dlp_od_rpt_get_real_count_pr`;
DELIMITER $$
CREATE PROCEDURE `dlp_od_rpt_get_real_count_pr`( -- Used to show other matched_item in chart
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512),
	IN par_content_type_id INT(11)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	
	IF par_username = '' THEN
		IF par_content_type_id = 2 THEN
		
			IF par_client_name<> '' AND par_group_id <> 0 THEN
			
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT IFNULL(SUM(confident_data_inc_count), 0) AS record_count					
					FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id, idx_GroupId)
					WHERE
					a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					AND a.GroupId = par_group_id;
					
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(SUM(confident_data_inc_count), 0) AS record_count					
					FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id, idx_GroupId)
					WHERE
					a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id = var_client_ids_str
					AND a.GroupId = par_group_id;
				END IF;

			ELSEIF par_client_name='' AND par_group_id<>0 THEN
			
				SELECT IFNULL(SUM(confident_data_inc_count), 0) AS record_count
						
				FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_GroupId)
				WHERE
				a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.GroupId = par_group_id;

			ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
			
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT IFNULL(SUM(confident_data_inc_count), 0) AS record_count					
					FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id)
					WHERE
					a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str);
					
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(SUM(confident_data_inc_count), 0) AS record_count					
					FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id)
					WHERE
					a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str;
				END IF;
			ELSEIF par_client_name='' AND par_group_id = 0 THEN
			
				SELECT IFNULL(SUM(confident_data_inc_count), 0) AS record_count
						
				FROM rpt_dlp_od_summarized_fact AS a FORCE INDEX(idx_scan_start_date) 
				WHERE
				a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second);
				
			END IF;
		
		ELSEIF par_content_type_id = 3 THEN
		
			IF par_client_name<> '' AND par_group_id <> 0 THEN
			
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT IFNULL(SUM(data_dictionary_inc_count), 0) AS record_count					
					FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id, idx_GroupId)
					WHERE
					a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					AND a.GroupId = par_group_id;
					
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(SUM(data_dictionary_inc_count), 0) AS record_count					
					FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id, idx_GroupId)
					WHERE
					a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id = var_client_ids_str
					AND a.GroupId = par_group_id;
				END IF;

			ELSEIF par_client_name='' AND par_group_id<>0 THEN
			
				SELECT IFNULL(SUM(data_dictionary_inc_count), 0) AS record_count
						
				FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_GroupId)
				WHERE
				a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.GroupId = par_group_id;

			ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
			
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT IFNULL(SUM(data_dictionary_inc_count), 0) AS record_count					
					FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id)
					WHERE
					a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str);
					
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(SUM(data_dictionary_inc_count), 0) AS record_count					
					FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id)
					WHERE
					a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str;
				END IF;
			ELSEIF par_client_name='' AND par_group_id = 0 THEN
			
				SELECT IFNULL(SUM(data_dictionary_inc_count), 0) AS record_count
						
				FROM rpt_dlp_od_summarized_fact AS a FORCE INDEX(idx_scan_start_date) 
				WHERE
				a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second);
				
			END IF;
		
		ELSE
		
			IF par_client_name<> '' AND par_group_id <> 0 THEN
			
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT (IFNULL(SUM(confident_data_inc_count), 0) + IFNULL(SUM(data_dictionary_inc_count), 0)) AS record_count					
					FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id, idx_GroupId)
					WHERE
					a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					AND a.GroupId = par_group_id;
					
				ELSEIF var_client_count = 1 THEN
					SELECT (IFNULL(SUM(confident_data_inc_count), 0) + IFNULL(SUM(data_dictionary_inc_count), 0)) AS record_count					
					FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id, idx_GroupId)
					WHERE
					a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id = var_client_ids_str
					AND a.GroupId = par_group_id;
				END IF;

			ELSEIF par_client_name='' AND par_group_id<>0 THEN
			
				SELECT (IFNULL(SUM(confident_data_inc_count), 0) + IFNULL(SUM(data_dictionary_inc_count), 0)) AS record_count					
				FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_GroupId)
				WHERE
				a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.GroupId = par_group_id;

			ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
			
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT (IFNULL(SUM(confident_data_inc_count), 0) + IFNULL(SUM(data_dictionary_inc_count), 0)) AS record_count					
					FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id)
					WHERE
					a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str);
					
				ELSEIF var_client_count = 1 THEN
					SELECT (IFNULL(SUM(confident_data_inc_count), 0) + IFNULL(SUM(data_dictionary_inc_count), 0)) AS record_count					
					FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id)
					WHERE
					a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str;
				END IF;
			ELSEIF par_client_name='' AND par_group_id = 0 THEN
			
				SELECT (IFNULL(SUM(confident_data_inc_count), 0) + IFNULL(SUM(data_dictionary_inc_count), 0)) AS record_count
						
				FROM rpt_dlp_od_summarized_fact AS a FORCE INDEX(idx_scan_start_date) 
				WHERE
				a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second);
				
			END IF;
		
		END IF;
		
	ELSE

		SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username = par_username LIMIT 1;
		
		IF par_content_type_id = 2 THEN
			IF par_client_name<> '' THEN
			
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master 
				WHERE (par_group_id = 0 OR GroupId=par_group_id )
				AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT IFNULL(SUM(confident_data_inc_count), 0) AS record_count					
					FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id, idx_user_id, idx_GroupId)
					WHERE
					a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					AND (par_group_id = 0 OR a.GroupId=par_group_id )
					AND a.user_id = var_user_id;
					
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(SUM(confident_data_inc_count), 0) AS record_count					
					FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id, idx_user_id, idx_GroupId)
					WHERE
					a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id = var_client_ids_str
					AND (par_group_id = 0 OR a.GroupId=par_group_id )
					AND a.user_id = var_user_id;
				END IF;
				
			ELSE
			
				SELECT IFNULL(SUM(confident_data_inc_count), 0) AS record_count					
				FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id, idx_user_id, idx_GroupId)
				WHERE
				a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND (par_group_id = 0 OR a.GroupId=par_group_id )
				AND a.user_id = var_user_id;
			
			END IF;
			
		ELSEIF par_content_type_id = 3 THEN
		
			IF par_client_name<> '' THEN
			
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master 
				WHERE (par_group_id = 0 OR GroupId=par_group_id )
				AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT IFNULL(SUM(data_dictionary_inc_count), 0) AS record_count					
					FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id, idx_user_id, idx_GroupId)
					WHERE
					a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					AND (par_group_id = 0 OR a.GroupId=par_group_id )
					AND a.user_id = var_user_id;
					
				ELSEIF var_client_count = 1 THEN
					SELECT IFNULL(SUM(data_dictionary_inc_count), 0) AS record_count					
					FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id, idx_user_id, idx_GroupId)
					WHERE
					a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id = var_client_ids_str
					AND (par_group_id = 0 OR a.GroupId=par_group_id )
					AND a.user_id = var_user_id;
				END IF;
			ELSE
			
				SELECT IFNULL(SUM(data_dictionary_inc_count), 0) AS record_count					
				FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id, idx_user_id, idx_GroupId)
				WHERE
				a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND (par_group_id = 0 OR a.GroupId=par_group_id )
				AND a.user_id = var_user_id;
					
			END IF;
		
		ELSE
		
			IF par_client_name<> '' THEN
			
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master 
				WHERE (par_group_id = 0 OR GroupId=par_group_id )
				AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT (IFNULL(SUM(confident_data_inc_count), 0) + IFNULL(SUM(data_dictionary_inc_count), 0)) AS record_count					
					FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id, idx_user_id, idx_GroupId)
					WHERE
					a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					AND (par_group_id = 0 OR a.GroupId=par_group_id )
					AND a.user_id = var_user_id;
					
				ELSEIF var_client_count = 1 THEN
					SELECT (IFNULL(SUM(confident_data_inc_count), 0) + IFNULL(SUM(data_dictionary_inc_count), 0)) AS record_count					
					FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id, idx_user_id, idx_GroupId)
					WHERE
					a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id = var_client_ids_str
					AND (par_group_id = 0 OR a.GroupId=par_group_id )
					AND a.user_id = var_user_id;
				END IF;
				
			ELSE
			
				SELECT (IFNULL(SUM(confident_data_inc_count), 0) + IFNULL(SUM(data_dictionary_inc_count), 0)) AS record_count					
				FROM rpt_dlp_od_summarized_fact AS a USE INDEX(idx_scan_start_date, idx_client_id, idx_user_id, idx_GroupId)
				WHERE
				a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND (par_group_id = 0 OR a.GroupId=par_group_id )
				AND a.user_id = var_user_id;
					
			END IF;
		
		END IF;
		
	END IF;
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `dlp_od_rpt_get_chart_details_table_for_other_pr`;
DELIMITER $$
CREATE PROCEDURE `dlp_od_rpt_get_chart_details_table_for_other_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512),
	IN par_other_item_id VARCHAR(255),
	IN par_content_type_id INT(11),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN -- To Export All Reports
		SELECT 
		incident_date, computer_name, d.username, str_ip_address, domain_name, file_type, file_path, incident_date_in_seconds
		FROM
		(
			SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, content_type_id, file_type, 
			file_path, incident_date AS incident_date_in_seconds
			
			FROM rpt_dlp_od_fact AS a
			ORDER BY a.incident_date DESC
		) AS a, client_master AS c, rpt_user_master AS d
		WHERE 
		a.client_id=c.client_id
		AND a.user_id=d.user_id
		ORDER BY incident_date DESC;
	ELSE
		IF par_username = '' THEN
			IF par_client_name<> '' AND par_group_id <> 0 THEN
			
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT 
					incident_date, computer_name, d.username, str_ip_address, domain_name, file_type, file_path, incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, content_type_id, file_type, 
						file_path, incident_date AS incident_date_in_seconds
						
						FROM rpt_dlp_od_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId, idx_content_type_id, idx_matched_item_id)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.GroupId = par_group_id
						AND a.content_type_id = par_content_type_id
						AND NOT FIND_IN_SET(a.matched_item_id, par_other_item_id)
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, client_master AS c, rpt_user_master AS d
					WHERE 
					a.client_id=c.client_id
					AND a.user_id=d.user_id
					ORDER BY incident_date DESC;
				ELSEIF var_client_count = 1 THEN
					SELECT 
					incident_date, computer_name, d.username, str_ip_address, domain_name, file_type, file_path, incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, content_type_id, file_type, 
						file_path, incident_date AS incident_date_in_seconds
						
						FROM rpt_dlp_od_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId, idx_content_type_id, idx_matched_item_id)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id = var_client_ids_str
						AND a.GroupId = par_group_id
						AND a.content_type_id = par_content_type_id
						AND NOT FIND_IN_SET(a.matched_item_id, par_other_item_id)
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, client_master AS c, rpt_user_master AS d
					WHERE 
					a.client_id=c.client_id
					AND a.user_id=d.user_id
					ORDER BY incident_date DESC;
				END IF;

			ELSEIF par_client_name='' AND par_group_id<>0 THEN
			
				SELECT 
				incident_date, computer_name, d.username, str_ip_address, domain_name, file_type, file_path, incident_date_in_seconds
				FROM
				(
					SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, content_type_id, file_type, 
					file_path, incident_date AS incident_date_in_seconds
					
					FROM rpt_dlp_od_fact AS a USE INDEX(idx_incident_date, idx_GroupId, idx_content_type_id, idx_matched_item_id)				
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.GroupId = par_group_id
					AND a.content_type_id = par_content_type_id
					AND NOT FIND_IN_SET(a.matched_item_id, par_other_item_id)
					ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
				) AS a, client_master AS c, rpt_user_master AS d
				WHERE 
				a.client_id=c.client_id
				AND a.user_id=d.user_id
				ORDER BY incident_date DESC;

			ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
			
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT 
					incident_date, computer_name, d.username, str_ip_address, domain_name, file_type, file_path, incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, content_type_id, file_type, 
						file_path, incident_date AS incident_date_in_seconds
						
						FROM rpt_dlp_od_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_content_type_id, idx_matched_item_id)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.content_type_id = par_content_type_id
						AND NOT FIND_IN_SET(a.matched_item_id, par_other_item_id)
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, client_master AS c, rpt_user_master AS d
					WHERE 
					a.client_id=c.client_id
					AND a.user_id=d.user_id
					ORDER BY incident_date DESC;
				ELSEIF var_client_count = 1 THEN
					SELECT 
					incident_date, computer_name, d.username, str_ip_address, domain_name, file_type, file_path, incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, content_type_id, file_type, 
						file_path, incident_date AS incident_date_in_seconds
						
						FROM rpt_dlp_od_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_content_type_id, idx_matched_item_id)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str
						AND a.content_type_id = par_content_type_id
						AND NOT FIND_IN_SET(a.matched_item_id, par_other_item_id)
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, client_master AS c, rpt_user_master AS d
					WHERE 
					a.client_id=c.client_id
					AND a.user_id=d.user_id
					ORDER BY incident_date DESC;
				END IF;
			ELSEIF par_client_name='' AND par_group_id = 0 THEN
			
				SELECT 
				incident_date, computer_name, d.username, str_ip_address, domain_name, file_type, file_path, incident_date_in_seconds
				FROM
				(
					SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, content_type_id, file_type, 
					file_path, incident_date AS incident_date_in_seconds
					
					FROM rpt_dlp_od_fact AS a USE INDEX(idx_incident_date, idx_content_type_id, idx_matched_item_id)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.content_type_id = par_content_type_id
					AND NOT FIND_IN_SET(a.matched_item_id, par_other_item_id)
					ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
				) AS a, client_master AS c, rpt_user_master AS d
				WHERE 
				a.client_id=c.client_id
				AND a.user_id=d.user_id
				ORDER BY incident_date DESC;
				
			END IF;
		
		ELSE
			
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username = par_username LIMIT 1;
			
			IF par_client_name<> '' THEN
			
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master 
				WHERE (par_group_id = 0 OR GroupId=par_group_id) AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT 
					incident_date, computer_name, d.username, str_ip_address, domain_name, file_type, file_path, incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, content_type_id, file_type, 
						file_path, incident_date AS incident_date_in_seconds
						
						FROM rpt_dlp_od_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_user_id, idx_GroupId, idx_content_type_id, idx_matched_item_id)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND (par_group_id = 0 OR a.GroupId = par_group_id)
						AND a.user_id = var_user_id
						AND a.content_type_id = par_content_type_id
						AND NOT FIND_IN_SET(a.matched_item_id, par_other_item_id)
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, client_master AS c, rpt_user_master AS d
					WHERE 
					a.client_id=c.client_id
					AND a.user_id=d.user_id
					ORDER BY incident_date DESC;
					
				ELSEIF var_client_count = 1 THEN
					SELECT 
					incident_date, computer_name, d.username, str_ip_address, domain_name, file_type, file_path, incident_date_in_seconds
					FROM
					(
						SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, content_type_id, file_type, 
						file_path, incident_date AS incident_date_in_seconds
						
						FROM rpt_dlp_od_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_user_id, idx_GroupId, idx_content_type_id, idx_matched_item_id)
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id = var_client_ids_str
						AND (par_group_id = 0 OR a.GroupId = par_group_id)
						AND a.user_id = var_user_id
						AND a.content_type_id = par_content_type_id
						AND NOT FIND_IN_SET(a.matched_item_id, par_other_item_id)
						ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, client_master AS c, rpt_user_master AS d
					WHERE 
					a.client_id=c.client_id
					AND a.user_id=d.user_id
					ORDER BY incident_date DESC;
				END IF;
				
			ELSE
			
				SELECT 
				incident_date, computer_name, d.username, str_ip_address, domain_name, file_type, file_path, incident_date_in_seconds
				FROM
				(
					SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, content_type_id, file_type, 
					file_path, incident_date AS incident_date_in_seconds
					
					FROM rpt_dlp_od_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_user_id, idx_GroupId, idx_content_type_id, idx_matched_item_id)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_group_id = 0 OR a.GroupId = par_group_id)
					AND a.user_id = var_user_id
					AND a.content_type_id = par_content_type_id
					AND NOT FIND_IN_SET(a.matched_item_id, par_other_item_id)
					ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
				) AS a, client_master AS c, rpt_user_master AS d
				WHERE 
				a.client_id=c.client_id
				AND a.user_id=d.user_id
				ORDER BY incident_date DESC;
				
			END IF;
			
		END IF;
		
	END IF;
	
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS manage_pdf_summary_rpt_get_table_pr;
DELIMITER $$
CREATE PROCEDURE manage_pdf_summary_rpt_get_table_pr(
	IN par_scan_info_id char(38)
)
BEGIN

	SELECT incident_date AS incident_date_in_seconds, computer_name, domain_name
	FROM
	(
		SELECT client_id, incident_date
		FROM rpt_appcon_od_summarized_fact
		WHERE scan_info_id = par_scan_info_id
		LIMIT 1
	) AS a, client_master AS b
	WHERE a.client_id = b.client_id;
	
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS vuln_rpt_get_references_pr_pdf;
DELIMITER $$
CREATE PROCEDURE `vuln_rpt_get_references_pr_pdf`(
	IN par_cve_id CHAR(14)
)
BEGIN
	SET time_zone = '+00:00';
	
	SELECT source_name, reference_name
	FROM rpt_vuln_references_dim
	WHERE cve_id = par_cve_id;
END $$
DELIMITER ;


DROP EVENT IF EXISTS evt_optimizetables_pr;

DELIMITER $$
CREATE EVENT IF NOT EXISTS evt_optimizetables_pr
ON SCHEDULE EVERY 1 WEEK 
STARTS str_to_date( DATE_FORMAT(now(), '%Y%m%d 0000'), '%Y%m%d %H%i' ) + INTERVAL 1 WEEK
ON COMPLETION PRESERVE ENABLE
DO 
BEGIN
	
	-- VIRUS SCAN
	OPTIMIZE TABLE rpt_virus_incident_fact;
	OPTIMIZE TABLE rpt_virus_chart_summary;
	
	-- ANTI MALWARE
	OPTIMIZE TABLE rpt_anti_malware_fact;
	OPTIMIZE TABLE rpt_anti_malware_chart_summary;
	
	-- WEB SECURITY
	OPTIMIZE TABLE rpt_websec_incident_fact;
	OPTIMIZE TABLE rpt_websec_chart_summary;
	
	-- DEVICE CONTROL
	OPTIMIZE TABLE rpt_device_control_fact;
	OPTIMIZE TABLE rpt_device_chart_summary_1;
	OPTIMIZE TABLE rpt_device_chart_summary_2;
	
	-- DATA LEAK PREVENTION (ON ACCESS)
	OPTIMIZE TABLE rpt_dlp_oa_fact;
	OPTIMIZE TABLE rpt_dlp_oa_summary;
	OPTIMIZE TABLE rpt_dlp_oa_application_summary;
	OPTIMIZE TABLE rpt_dlp_oa_content_type_summary;

	-- DATA LEAK PREVENTION (ON DEMAND)
	OPTIMIZE TABLE rpt_dlp_od_fact;
	OPTIMIZE TABLE rpt_dlp_od_summarized_fact;

	-- APPLICATION CONTROL (ON ACCESS)
	OPTIMIZE TABLE rpt_appcon_oa_fact;
	OPTIMIZE TABLE rpt_appcon_oa_chart_summary;
	
	-- APPLICATION CONTROL (ON DEMAND)
	OPTIMIZE TABLE rpt_appcon_od_summarized_fact;
	
	-- INSTRUCTION PREVENTION
	OPTIMIZE TABLE rpt_ips_fact;
	
	-- PORT SCAN
	OPTIMIZE TABLE rpt_port_scan_fact;
	
	-- DDOS
	OPTIMIZE TABLE rpt_ddos_fact;
	
	-- FIREWALL
	OPTIMIZE TABLE rpt_firewall_fact;
	
	-- VULNERABILITY SCAN
	OPTIMIZE TABLE rpt_vuln_incident_fact;
	OPTIMIZE TABLE rpt_vuln_severity_chart_summary;
	OPTIMIZE TABLE rpt_vuln_topvuln_chart_summary;
	OPTIMIZE TABLE rpt_vuln_vendor_chart_summary;
	
	-- FILE ACTIVITY MONITOR
	OPTIMIZE TABLE rpt_fam_incident_fact;
	OPTIMIZE TABLE rpt_fam_chart_summary;
	OPTIMIZE TABLE rpt_fam_extn_summary;
	
	-- ASSET MANAGEMENT
	OPTIMIZE TABLE rpt_asset_mgnt_fact;
	OPTIMIZE TABLE rpt_asset_mgnt_chart_summary;
	
	-- EVENT LOG
	OPTIMIZE TABLE event_log;
	
END $$
DELIMITER ;

-- For asyncronous policy distribution, to update client status as per applied policy

DROP PROCEDURE IF EXISTS policy_update_policy_status;
DELIMITER $$
CREATE PROCEDURE policy_update_policy_status(
IN par_client_guid CHAR(38),
IN par_policy_guid CHAR(38),
IN par_policy_status INT(2)
)
BEGIN

	DECLARE var_policy_guid CHAR(38) DEFAULT NULL;
	SET var_policy_guid = 
	(
		SELECT guid FROM policy WHERE policyid = 
		(
			SELECT policyid FROM groups WHERE groupid = 
			(
				SELECT groupid FROM client_master WHERE guid = par_client_guid LIMIT 1
			) 
			LIMIT 1
		)
	);
	
	IF var_policy_guid = par_policy_guid THEN
	
		UPDATE client_master SET policy_status = par_policy_status WHERE guid = par_client_guid;
		
	END IF;
	
	
END $$
DELIMITER ;

-- Following 3 procedures merged from Sagar

DROP PROCEDURE IF EXISTS dlp_od_rpt_get_chart_pr_pdf;
DELIMITER $$
CREATE PROCEDURE dlp_od_rpt_get_chart_pr_pdf(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512),
	IN par_content_type_id INT(11)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN 
		SELECT matched_item_id, scan_info_id, matched_item, SUM(incident_count) AS incident_count
		FROM rpt_dlp_od_chart_summary AS a
		GROUP BY matched_item_id ORDER BY incident_count DESC;
	ELSE
		IF par_username = '' THEN
			IF par_client_name <> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT matched_item_id, scan_info_id, matched_item, SUM(incident_count) AS incident_count
					FROM rpt_dlp_od_chart_summary AS a
					WHERE a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str) AND a.GroupId=par_group_id AND a.content_type_id=par_content_type_id
					GROUP BY matched_item_id ORDER BY incident_count DESC;
				ELSEIF var_client_count = 1 THEN
					SELECT matched_item_id, scan_info_id, matched_item, SUM(incident_count) AS incident_count
					FROM rpt_dlp_od_chart_summary AS a
					WHERE a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str AND a.GroupId=par_group_id AND a.content_type_id=par_content_type_id
					GROUP BY matched_item_id ORDER BY incident_count DESC;
				END IF;
				
			ELSEIF par_client_name='' AND par_group_id<>0 THEN

				SELECT matched_item_id, scan_info_id, matched_item, SUM(incident_count) AS incident_count
				FROM rpt_dlp_od_chart_summary AS a
				WHERE a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.GroupId=par_group_id AND a.content_type_id=par_content_type_id
				GROUP BY matched_item_id ORDER BY incident_count DESC;
				
			ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT matched_item_id, scan_info_id, matched_item, SUM(incident_count) AS incident_count
					FROM rpt_dlp_od_chart_summary AS a
					WHERE a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str) AND a.content_type_id=par_content_type_id
					GROUP BY matched_item_id ORDER BY incident_count DESC;
				ELSEIF var_client_count = 1 THEN
					SELECT matched_item_id, scan_info_id, matched_item, SUM(incident_count) AS incident_count
					FROM rpt_dlp_od_chart_summary AS a
					WHERE a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str AND a.content_type_id=par_content_type_id
					GROUP BY matched_item_id ORDER BY incident_count DESC;
				END IF;
				
			ELSEIF par_client_name='' AND par_group_id = 0 THEN
				SELECT matched_item_id, scan_info_id, matched_item, SUM(incident_count) AS incident_count
				FROM rpt_dlp_od_chart_summary AS a
				WHERE a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.content_type_id=par_content_type_id
				GROUP BY matched_item_id ORDER BY incident_count DESC;
			END IF;
		
		ELSE

			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username = par_username LIMIT 1;
			
			IF par_client_name <> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master 
				WHERE (par_group_id = 0 OR GroupId=par_group_id) AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT matched_item_id, scan_info_id, matched_item, SUM(incident_count) AS incident_count
					FROM rpt_dlp_od_chart_summary AS a
					WHERE a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str) 
					AND (par_group_id = 0 OR a.GroupId=par_group_id )
					AND a.content_type_id=par_content_type_id
					AND a.user_id=var_user_id
					GROUP BY matched_item_id ORDER BY incident_count DESC;
				ELSEIF var_client_count = 1 THEN
					SELECT matched_item_id, scan_info_id, matched_item, SUM(incident_count) AS incident_count
					FROM rpt_dlp_od_chart_summary AS a
					WHERE a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str 
					AND (par_group_id = 0 OR a.GroupId=par_group_id )
					AND a.content_type_id=par_content_type_id
					AND a.user_id=var_user_id
					GROUP BY matched_item_id ORDER BY incident_count DESC;
				END IF;
			
			ELSE
			
				SELECT matched_item_id, scan_info_id, matched_item, SUM(incident_count) AS incident_count
				FROM rpt_dlp_od_chart_summary AS a
				WHERE a.scan_start_date >= unix_timestamp(par_start_date) AND a.scan_start_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND (par_group_id = 0 OR a.GroupId=par_group_id )
				AND a.content_type_id=par_content_type_id
				AND a.user_id=var_user_id
				GROUP BY matched_item_id ORDER BY incident_count DESC;
				
			END IF;
		END IF;
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS appcon_oa_rpt_get_chart_pr_pdf;
DELIMITER $$
CREATE PROCEDURE appcon_oa_rpt_get_chart_pr_pdf(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN 
		SELECT app_category_name , SUM(incident_count) AS incident_count
		FROM rpt_appcon_oa_chart_summary AS a
		GROUP BY app_category_id ORDER BY incident_count DESC;
	ELSE
		IF par_username = '' THEN
			IF par_client_name <> '' AND par_group_id <> 0 THEN
			
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT app_category_name , SUM(incident_count) AS incident_count
					FROM rpt_appcon_oa_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str) AND a.GroupId=par_group_id
					GROUP BY app_category_id ORDER BY incident_count DESC;
				ELSEIF var_client_count = 1 THEN
					SELECT app_category_name , SUM(incident_count) AS incident_count
					FROM rpt_appcon_oa_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str AND a.GroupId=par_group_id
					GROUP BY app_category_id ORDER BY incident_count DESC;
				END IF;
				
			ELSEIF par_client_name='' AND par_group_id<>0 THEN
			
				SELECT app_category_name , SUM(incident_count) AS incident_count
				FROM rpt_appcon_oa_chart_summary AS a
				WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND a.GroupId=par_group_id
				GROUP BY app_category_id ORDER BY incident_count DESC;
					
			ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
			
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT app_category_name , SUM(incident_count) AS incident_count
					FROM rpt_appcon_oa_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					GROUP BY app_category_id ORDER BY incident_count DESC;
				ELSEIF var_client_count = 1 THEN
					SELECT app_category_name , SUM(incident_count) AS incident_count
					FROM rpt_appcon_oa_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str
					GROUP BY app_category_id ORDER BY incident_count DESC;
				END IF;
				
			ELSEIF par_client_name='' AND par_group_id = 0 THEN

				SELECT app_category_name , SUM(incident_count) AS incident_count
				FROM rpt_appcon_oa_chart_summary AS a
				WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				GROUP BY app_category_id ORDER BY incident_count DESC;
			END IF;
		ELSE
		
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username = par_username LIMIT 1;
			
			IF par_client_name <> '' THEN
			
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master 
				WHERE (par_group_id = 0 OR GroupId=par_group_id) AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT app_category_name , SUM(incident_count) AS incident_count
					FROM rpt_appcon_oa_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND FIND_IN_SET(a.client_id, var_client_ids_str) 
					AND (par_group_id = 0 OR GroupId=par_group_id)
					AND a.user_id = var_user_id
					GROUP BY app_category_id ORDER BY incident_count DESC;
				ELSEIF var_client_count = 1 THEN
					SELECT app_category_name , SUM(incident_count) AS incident_count
					FROM rpt_appcon_oa_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.client_id=var_client_ids_str 
					AND (par_group_id = 0 OR GroupId=par_group_id)
					AND a.user_id = var_user_id
					GROUP BY app_category_id ORDER BY incident_count DESC;
				END IF;
				
			ELSE
			
				SELECT app_category_name , SUM(incident_count) AS incident_count
				FROM rpt_appcon_oa_chart_summary AS a
				WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second) 
				AND (par_group_id = 0 OR GroupId=par_group_id)
				AND a.user_id = var_user_id
				GROUP BY app_category_id ORDER BY incident_count DESC;
			END IF;
		END IF;
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS web_security_rpt_get_chart_pr_pdf;
DELIMITER $$
CREATE PROCEDURE web_security_rpt_get_chart_pr_pdf(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN 
		SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
		FROM
		(
			SELECT websec_category_id , SUM(incident_count) AS incident_count
			FROM rpt_websec_chart_summary AS a
			GROUP BY websec_category_id ORDER BY incident_count DESC
		) AS t1, rpt_websec_category_dim AS b
		WHERE t1.websec_category_id=b.websec_category_id;
	ELSE
		IF par_username='' THEN
			IF par_client_name <> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
					FROM
					(
						SELECT websec_category_id , SUM(incident_count) AS incident_count
						FROM rpt_websec_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str) AND a.GroupId=par_group_id
						GROUP BY websec_category_id ORDER BY incident_count DESC
					) AS t1, rpt_websec_category_dim AS b
					WHERE t1.websec_category_id=b.websec_category_id;
				ELSEIF var_client_count = 1 THEN
					SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
					FROM
					(
						SELECT websec_category_id , SUM(incident_count) AS incident_count
						FROM rpt_websec_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str AND a.GroupId=par_group_id
						GROUP BY websec_category_id ORDER BY incident_count DESC
					) AS t1, rpt_websec_category_dim AS b
					WHERE t1.websec_category_id=b.websec_category_id;
				END IF;
			ELSEIF par_client_name='' AND par_group_id<>0 THEN
				SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
				FROM
				(
					SELECT websec_category_id , SUM(incident_count) AS incident_count
					FROM rpt_websec_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.GroupId=par_group_id
					GROUP BY websec_category_id ORDER BY incident_count DESC
				) AS t1, rpt_websec_category_dim AS b
				WHERE t1.websec_category_id=b.websec_category_id;
			ELSEIF par_client_name <> '' AND par_group_id = 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
					FROM
					(
						SELECT websec_category_id , SUM(incident_count) AS incident_count
						FROM rpt_websec_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						GROUP BY websec_category_id ORDER BY incident_count DESC
					) AS t1, rpt_websec_category_dim AS b
					WHERE t1.websec_category_id=b.websec_category_id;
				ELSEIF var_client_count = 1 THEN
					SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
					FROM
					(
						SELECT websec_category_id , SUM(incident_count) AS incident_count
						FROM rpt_websec_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str
						GROUP BY websec_category_id ORDER BY incident_count DESC
					) AS t1, rpt_websec_category_dim AS b
					WHERE t1.websec_category_id=b.websec_category_id;
				END IF;
		ELSEIF par_client_name='' AND par_group_id = 0 THEN
				SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
				FROM
				(
					SELECT websec_category_id , SUM(incident_count) AS incident_count
					FROM rpt_websec_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					GROUP BY websec_category_id ORDER BY incident_count DESC
				) AS t1, rpt_websec_category_dim AS b
				WHERE t1.websec_category_id=b.websec_category_id;
			END IF;
		ELSE
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
			IF par_client_name <> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str 
				FROM client_master 
				WHERE (par_group_id=0 OR GroupId=par_group_id) AND computer_name=par_client_name;
				
				IF var_client_count > 1 THEN
					SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
					FROM
					(
						SELECT websec_category_id , SUM(incident_count) AS incident_count
						FROM rpt_websec_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						AND a.user_id=var_user_id
						AND (par_group_id=0 OR a.GroupId=par_group_id)
						GROUP BY websec_category_id ORDER BY incident_count DESC
					) AS t1, rpt_websec_category_dim AS b
					WHERE t1.websec_category_id=b.websec_category_id;
				ELSEIF var_client_count = 1 THEN
					SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
					FROM
					(
						SELECT websec_category_id , SUM(incident_count) AS incident_count
						FROM rpt_websec_chart_summary AS a
						WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND a.client_id=var_client_ids_str
						AND a.user_id=var_user_id
						AND (par_group_id=0 OR a.GroupId=par_group_id)
						GROUP BY websec_category_id ORDER BY incident_count DESC
					) AS t1, rpt_websec_category_dim AS b
					WHERE t1.websec_category_id=b.websec_category_id;
				END IF;
			ELSE
				SELECT b.category, t1.incident_count, t1.websec_category_id As category_id
				FROM
				(
					SELECT websec_category_id , SUM(incident_count) AS incident_count
					FROM rpt_websec_chart_summary AS a
					WHERE a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.user_id=var_user_id
					AND (par_group_id=0 OR a.GroupId=par_group_id)
					GROUP BY websec_category_id ORDER BY incident_count DESC
				) AS t1, rpt_websec_category_dim AS b
				WHERE t1.websec_category_id=b.websec_category_id;
			END IF;
		END IF;
	END IF;
END $$
DELIMITER ;

CREATE TABLE IF NOT EXISTS `rpt_dlp_matched_item_master` (
  `mached_item_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `matched_item` varchar(500) DEFAULT NULL,
  PRIMARY KEY (`mached_item_id`),
  KEY `idx_matched_item` (`matched_item`(255))
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT='This table is only to maintain matched_item_id and only in case of category is 3 ( User Defined Dictionary ).';

DROP PROCEDURE IF EXISTS virusscan_rpt_get_latest_virus_incident;
DELIMITER $$
CREATE PROCEDURE `virusscan_rpt_get_latest_virus_incident`(
	IN par_guid CHAR(40)
)
BEGIN
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
    SET var_client_id = (SELECT client_id FROM client_master WHERE guid= par_guid LIMIT 1);
    
    IF var_client_id IS NOT NULL THEN
		SELECT virus_name, incident_date AS incident_date_in_seconds
        FROM
		(
			SELECT virus_scan_id, incident_date FROM rpt_virus_incident_fact
            WHERE client_id = var_client_id 
            ORDER BY incident_date DESC LIMIT 1
		) AS a,  rpt_virus_scan_dim as b    
        WHERE a.virus_scan_id = b.virus_scan_id;       
       
    END IF;	
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS update_client_status;
DELIMITER $$
CREATE PROCEDURE update_client_status(
IN par_client_guid CHAR(38),
IN par_client_status INT(2)
)
BEGIN
	
		UPDATE client_master SET client_status = par_client_status WHERE guid = par_client_guid;	
	
END $$
DELIMITER ;


--
-- Patch scan tables
--

CREATE TABLE IF NOT EXISTS `pm_server_info` (
  `pm_server_guid` CHAR(40) NOT NULL ,
  `pm_server` TEXT DEFAULT NULL,
  `pm_server_name` varchar(260) DEFAULT NULL,
  `port` int(11) DEFAULT NULL,
  `ssl_enable` int(11) DEFAULT NULL,
  `parent_server_type` int(11) DEFAULT NULL,
  `parent_server` CHAR(40) DEFAULT NULL,
  `download_patch` int(11) DEFAULT NULL,
  `patch_severity` int(11) DEFAULT NULL,
  `filter_anchor` varchar(260) DEFAULT NULL COMMENT 'Anchor for Patch Filters Synchronization with PMS',
  `status` int(11) DEFAULT NULL,
  `status_update_time` integer DEFAULT 0,  
  `proxy_status` int(11) DEFAULT NULL,
  `proxy_server` varchar(260) DEFAULT NULL,
  `proxy_port` int(11) DEFAULT NULL,
  `proxy_authentication` int(11) DEFAULT NULL,
  `proxy_username` varchar(260) DEFAULT NULL,
  `proxy_password` varbinary(260) DEFAULT NULL,
  `sync_anchor` varchar(260) DEFAULT NULL COMMENT 'Anchor for Patch Metadata Synchronization with PMS',
  `last_sync_status` INT(11) DEFAULT 0 COMMENT '0: Not Sync, 1: In Progress, 2: Success',
  `pm_server_local_ip` TEXT DEFAULT ''  COMMENT 'Local Hostname or IP of PMS',
  PRIMARY KEY (`pm_server_guid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into pm_server_info values('default', 'default', '', 8080, 0, 0, '', 0, 0, '0', 0, 0, 0, '', 0, 0, '', AES_ENCRYPT('','sqeps'), '0', 0, '');

CREATE TABLE IF NOT EXISTS `pm_schd_patch_sync_info` (
  `pm_server_guid` CHAR(40) NOT NULL ,
  `enable_schedule` int(11) DEFAULT NULL,
  `frequency` int(11) DEFAULT NULL,
  `week_day` int(11) DEFAULT NULL,
  `month_day` int(11) DEFAULT NULL,
  `start_hr` int(11) DEFAULT NULL,
  `start_min` int(11) DEFAULT NULL,
  `last_sync_date` int(11) DEFAULT NULL,
  PRIMARY KEY (`pm_server_guid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into pm_schd_patch_sync_info values('default', 0, 0, 1, 1, 0, 0, 0);

CREATE TABLE IF NOT EXISTS `pm_products` (
  `product_guid` CHAR(40) NOT NULL ,
  `product_name` TEXT DEFAULT NULL,
  `parent_guid` CHAR(40) DEFAULT NULL,
  `product_type` TEXT DEFAULT NULL,
  PRIMARY KEY (`product_guid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `pm_patch_categories_master` (
	`category_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
	`category_guid` CHAR(40) NOT NULL,
	`category_name` text,  
	PRIMARY KEY (`category_guid`),
	UNIQUE KEY `idx_category_id` (`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `pm_languages` (
  `language_id` int(11) NOT NULL ,
  `language` TEXT DEFAULT NULL,
  PRIMARY KEY (`language_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `pm_sync_products` (
  `product_guid` CHAR(40) NOT NULL ,
  `pm_server_guid` CHAR(40) NOT NULL ,
  PRIMARY KEY (`product_guid`, `pm_server_guid`),
  FOREIGN KEY (`product_guid`) REFERENCES `pm_products` (`product_guid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `pm_sync_categories` (
  `category_guid` CHAR(40) NOT NULL ,
  `pm_server_guid` CHAR(40) NOT NULL ,
  PRIMARY KEY (`category_guid`, `pm_server_guid`),
  FOREIGN KEY (`category_guid`) REFERENCES `pm_patch_categories_master` (`category_guid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `pm_sync_languages` (
  `language_id` int(11) NOT NULL ,
  `pm_server_guid` CHAR(40) NOT NULL ,
  PRIMARY KEY (`language_id`, `pm_server_guid`),
  FOREIGN KEY (`language_id`) REFERENCES `pm_languages` (`language_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `pm_patch_scan_settings` (
  `scan_mode` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into pm_patch_scan_settings values(1);

CREATE TABLE IF NOT EXISTS `rpt_merging_task` (
  `task_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
  `client_guid` CHAR(40) NOT NULL,
  `emergency_id` INT(11) DEFAULT NULL,  
  `rpt_data` BLOB,  
  `retry_count` INT(11) DEFAULT 0, 
  PRIMARY KEY (`task_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- Tables for Patch Management --
CREATE TABLE IF NOT EXISTS `pm_patch_master` (
  `patch_id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `patch_guid` CHAR(40) NOT NULL,
  `patch_revision` int(11) DEFAULT NULL COMMENT 'There can be one or more revisions of one patch_id',
  `patch_title` varchar(1024) DEFAULT NULL,
  `patch_desc` TEXT DEFAULT NULL,
  `category_id` bigint(20) UNSIGNED DEFAULT NULL,
  `category` varchar(45) DEFAULT NULL,
  `severity_id` int(11) DEFAULT NULL COMMENT '0: Low, 1: Moderate, 2: Important, 3: Critical, 4: Unspecified',
  `kb_article_no` varchar(16) DEFAULT NULL COMMENT 'Knowledge Base Id',
  `application_name` varchar(1024) DEFAULT NULL,
  `application_family` varchar(1024) DEFAULT NULL,
  `application_id` BIGINT(20) DEFAULT NULL,
  `bulletin_id` varchar(25) DEFAULT NULL,
  `loc_lang` varchar(45) DEFAULT NULL, -- Hard coded
  `vendor` varchar(1024) DEFAULT NULL,
  `superseded` TEXT DEFAULT NULL, -- List of JSon objects (comma sep string)
  `superseding` TEXT DEFAULT NULL, -- List of JSon objects (comma sep string)
  `ref_links` TEXT DEFAULT NULL,
  `eula_accept_required` INT(11) DEFAULT NULL,
  `eula_url` TEXT DEFAULT NULL,
  `eula_agreement` TEXT DEFAULT NULL,
  `eula_accepted` BIT(1) DEFAULT FALSE,
  `eula_downloaded` BIT(1) DEFAULT FALSE,
  `max_download_size` BIGINT(20) UNSIGNED DEFAULT NULL COMMENT 'in bytes',
  `vulnerabilities_targeted` varchar(1024) DEFAULT NULL COMMENT 'List of CVE ids',
  PRIMARY KEY (`patch_id`),
  UNIQUE KEY `idx_patch_guid` (`patch_guid`,`patch_revision`),
  KEY `idx_severity_id` (`severity_id`),
  KEY `idx_eula_accept_required` (`eula_accept_required`)  
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='This table is used to store Patch information locally. Info updated from PM Server.';

CREATE TABLE IF NOT EXISTS `pm_patch_scan_fact` (
  `rowid` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `scan_type` int(11) DEFAULT NULL COMMENT '1: On Demand, 2: Schedule',
  `incident_date` int(20) DEFAULT NULL,
  `patch_id` bigint(20) DEFAULT NULL COMMENT 'Patch_id from pm_patch_master',
  `client_id` bigint(20) DEFAULT NULL COMMENT 'client_id for reference in client_master',
  `pmserver_id` CHAR(40) DEFAULT NULL COMMENT 'Patch Management Server Id',
  `pmserver_name` varchar(255) DEFAULT NULL COMMENT 'Patch Management Server Name',
  `group_id` bigint(20) DEFAULT NULL,
  `category_id` bigint(20) UNSIGNED DEFAULT NULL,
  `severity_id` int(11) DEFAULT NULL COMMENT '0: Low, 1: Moderate, 2: Important, 3: Critical, 4: Unspecified',
  `restart_required` INT(11) DEFAULT NULL, -- from client 0=Never reboots, 1=Alwarys Reboots, 2=May reboot
  `eula_accepted` BIT(1) DEFAULT FALSE,
  `application_id` BIGINT(20) DEFAULT NULL,
  `kb_article_no` varchar(16) DEFAULT NULL, -- Knowledge Base Id
  `bulletin_id` varchar(25) DEFAULT NULL,
  `installation_status` int(11) DEFAULT NULL 
  COMMENT 'NULL: no action performed till now\n 1: Notification Sending\n 
  2: Patch download notification sent\n 
  3: Patch download failed\n 
  4: Patch download success\n 
  5: Patch install notification sent\n 
  6: Patch install notification queued (in case of client is offline)\n 
  7: Patch install failed\n 
  8: Patch install success',
  `status_error_code` int(11) DEFAULT NULL,
  `notification_time` DATETIME DEFAULT NULL,
  `is_patch_selected4installation` BIT(1) DEFAULT FALSE, 
  `is_client_selected4installation` BIT(1) DEFAULT TRUE, 
  PRIMARY KEY (`rowid`),
  KEY `idx_scan_type` (`scan_type`),
  KEY `idx_incident_date` (`incident_date`),
  KEY `idx_patch_id` (`patch_id`),
  KEY `idx_client_id` (`client_id`),
  KEY `idx_pmserver_id` (`pmserver_id`),
  KEY `idx_group_id` (`group_id`),
  KEY `idx_category_id` (`category_id`),
  KEY `idx_severity_id` (`severity_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- This table is used for temporary storage of scan data comming from Roaming clients and whos metadata is not available in pm_patch_master.
CREATE TABLE IF NOT EXISTS `pm_patch_scan_with_no_metadata` (
  `rowid` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `install_result` int(11) DEFAULT NULL,
  `incident_date` int(20) DEFAULT NULL,
  `patch_guid` CHAR(40) NOT NULL,
  `patch_revision` int(11),
  `restart_required` INT(11) DEFAULT NULL, -- from client 0=Never reboots, 1=Alwarys Reboots, 2=May reboot
  `client_guid` CHAR(40) NOT NULL,
  `pmserver_id` CHAR(40) DEFAULT NULL COMMENT 'Patch Management Server Id',  
  `scan_type` int(11) DEFAULT NULL COMMENT '1: On Demand, 2: Schedule',
  PRIMARY KEY (`rowid`),
  KEY `idx_patch_guid` (`patch_guid`),
  KEY `idx_patch_revision` (`patch_revision`),
  KEY `idx_client_guid` (`client_guid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `pm_patch_download_status_dim` (
  `patch_id` bigint(20) DEFAULT NULL COMMENT 'Patch_id from pm_patch_master',
  `pmserver_id` CHAR(40) NOT NULL,
  `pmserver_name` varchar(255) DEFAULT NULL COMMENT 'Patch Management Server Name',
  -- `download_status` int(11) DEFAULT FALSE COMMENT '0 : Not Downloaded\n1 : Notification Queued\n2 : Notification Sent\n3 : Download Success\n4: Download Failed',
  `download_status` BIT(1) DEFAULT FALSE,
  PRIMARY KEY (`patch_id`,`pmserver_id`),
  KEY `idx_patch_id` (`patch_id`),
  KEY `idx_pmserver_id` (`pmserver_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='This tables stores the status of wheather a patch is downloaded on its respective PM Server.';

CREATE TABLE IF NOT EXISTS `pm_application_master` (
	`application_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
	`application_name` TEXT,
	PRIMARY KEY (`application_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `rpt_patch_clientwise_summary` (
	`rowid` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
	`incident_date_only` int(20) DEFAULT NULL,
	`client_id` bigint(20) DEFAULT NULL,
	`severity_id` int(11) DEFAULT NULL COMMENT '0: Low, 1: Moderate, 2: Important, 3: Critical, 4: Unspecified',
	`group_id` bigint(20) DEFAULT NULL,
	`missing_count` bigint(20) DEFAULT 0,
	`install_count` bigint(20) DEFAULT 0,
	`md5_match` char(64) DEFAULT NULL,
	PRIMARY KEY (`rowid`),
	KEY `idx_incident_date_only` (`incident_date_only`),
	KEY `idx_client_id` (`client_id`),
	KEY `idx_severity_id` (`severity_id`),
	KEY `idx_group_id` (`group_id`),
	KEY `idx_md5_match` (`md5_match`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `rpt_patch_patchwise_summary` (
	`rowid` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
	`incident_date_only` int(20) DEFAULT NULL,
	`patch_id` bigint(20) DEFAULT NULL,
	`severity_id` int(11) DEFAULT NULL COMMENT '0: Low, 1: Moderate, 2: Important, 3: Critical, 4: Unspecified',
	`group_id` bigint(20) DEFAULT NULL,
	`missing_client_count` bigint(20) DEFAULT 0,
	`install_client_count` bigint(20) DEFAULT 0,
	`md5_match` char(64) DEFAULT NULL,
	PRIMARY KEY (`rowid`),
	KEY `idx_incident_date_only` (`incident_date_only`),
	KEY `idx_patch_id` (`patch_id`),
	KEY `idx_severity_id` (`severity_id`),
	KEY `idx_group_id` (`group_id`),
	KEY `idx_md5_match` (`md5_match`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `rpt_patch_management_fact` (
	`rowid` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
	`incident_date` int(20) DEFAULT NULL,
	`patch_id` bigint(20) UNSIGNED NOT NULL,
	`severity_id` int(11) DEFAULT NULL COMMENT '0: Low, 1: Moderate, 2: Important, 3: Critical, 4: Unspecified',
	`client_id` bigint(20) DEFAULT NULL,
	`group_id` bigint(20) DEFAULT NULL,
	`is_installed` int(1) DEFAULT 0,
	`installation_errorcode` int(11) DEFAULT NULL COMMENT '0: Success, Non-zero: Failed',
	`scan_type_id` int(2) DEFAULT NULL,
	`md5_match` char(64) DEFAULT NULL,
	PRIMARY KEY (`rowid`),
	KEY `idx_incident_date` (`incident_date`),
	KEY `idx_patch_id` (`patch_id`),
	KEY `idx_severity_id` (`severity_id`),
	KEY `idx_client_id` (`client_id`),
	KEY `idx_group_id` (`group_id`),
	KEY `idx_is_installed` (`is_installed`),
	KEY `idx_md5_match` (`md5_match`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `pm_patch_od_install_settings` (
	`auto_restart` int(11) DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `pm_patch_od_install_settings`(`auto_restart`) VALUES(0);

DROP PROCEDURE IF EXISTS `pr_get_group_list_byparentid`;
DELIMITER $$
CREATE PROCEDURE `pr_get_group_list_byparentid`(
	IN par_parent_group_id INT(11)
)
BEGIN
	IF par_parent_group_id = -1 THEN
		SELECT GroupId AS group_id, 
		GroupName AS group_name,
		ParentGrpId AS parent_group_id,
		PolicyId AS policy_id,
		GroupGUID AS group_guid,
		(SELECT PolicyId FROM policy WHERE PolicyId = gr1.PolicyId) AS policy_Name,
		(SELECT count(gr2.GroupId) FROM groups AS gr2 WHERE gr2.ParentGrpId = gr1.GroupId AND gr2.GroupId <> gr1.GroupId) AS sub_groups,
		(SELECT count(GroupId) FROM acsync WHERE GroupId = gr1.GroupId) AS sync_status
		FROM groups AS gr1;
	ELSE
		SELECT GroupId AS group_id, 
		GroupName AS group_name,
		ParentGrpId AS parent_group_id,
		PolicyId AS policy_id,
		GroupGUID AS group_guid,
		(SELECT PolicyId FROM policy WHERE PolicyId = gr1.PolicyId) AS policy_Name,
		(SELECT count(gr2.GroupId) FROM groups AS gr2 WHERE gr2.ParentGrpId = gr1.GroupId AND gr2.GroupId <> gr1.GroupId) AS sub_groups,
		(SELECT count(GroupId) FROM acsync WHERE GroupId = gr1.GroupId) AS sync_status
		FROM groups AS gr1
		WHERE ParentGrpId = par_parent_group_id AND GroupId <> par_parent_group_id;
	END IF;
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pr_insert_patch_metadata_clnt`;
DELIMITER $$
CREATE PROCEDURE `pr_insert_patch_metadata_clnt`(
	IN `par_patch_guid` CHAR(40),
	IN `par_patch_revision` int(11),
	IN `par_patch_title` varchar(1024),
	IN `par_patch_desc` TEXT,
	IN `par_category` varchar(45),
	IN `par_severity_id` int(11),
	IN `par_kb_article_no` varchar(16), -- Knowledge Base Id
	IN `par_application` varchar(1024),
	IN `par_application_family` varchar(1024),
	IN `par_bulletin_id` varchar(25),
	IN `par_vendor` varchar(1024),
	IN `par_superseded` TEXT, -- List of JSon objects (comma sep string)
	IN `par_superseding` TEXT, -- List of JSon objects (comma sep string)
	IN `par_ref_links` TEXT,
	IN `par_eula_accept_required` INT(11),
	IN `par_eula_url` TEXT,	
	IN `par_max_download_size` BIGINT(20) UNSIGNED,
	IN `par_vulnerabilities_targeted` varchar(1024)
)
BEGIN
	DECLARE var_category_id BIGINT(20) DEFAULT NULL;
	DECLARE var_application_id BIGINT(20) DEFAULT NULL;
	DECLARE var_matched_id BIGINT(20) DEFAULT NULL;	
	
	SET time_zone = '+00:00';
	
	SELECT category_id INTO var_category_id FROM pm_patch_categories_master WHERE category_name = par_category LIMIT 1;
	-- IF var_category_id IS NULL THEN
	--	INSERT INTO pm_patch_categories_master(category_name) VALUES(par_category);
	--	SET var_category_id = (select last_insert_id());
	-- END IF;
	
	SELECT application_id INTO var_application_id FROM pm_application_master WHERE application_name = par_application LIMIT 1;
	IF var_application_id IS NULL THEN
		INSERT INTO pm_application_master(application_name) VALUES(par_application);
		SET var_application_id = (select last_insert_id());
	END IF;
	
	SET var_matched_id = (SELECT patch_id FROM pm_patch_master WHERE patch_guid = par_patch_guid AND patch_revision = par_patch_revision LIMIT 1);
	IF var_matched_id IS NOT NULL THEN
		UPDATE pm_patch_master
		SET
		`patch_title` = par_patch_title,
		`patch_desc` = par_patch_desc,
		`category_id` = var_category_id,
		`category` = par_category,
		`severity_id` = par_severity_id,
		`kb_article_no` = par_kb_article_no,
		`application_name` = par_application,
		`application_family` = par_application_family,
		`application_id` = var_application_id,
		`bulletin_id` = par_bulletin_id,
		`vendor` = par_vendor,
		`superseded` = par_superseded,
		`superseding` = par_superseding,
		`ref_links` = par_ref_links,
		`eula_accept_required` = par_eula_accept_required,
		`eula_url` = par_eula_url,
		`max_download_size` = par_max_download_size,
		`vulnerabilities_targeted` = par_vulnerabilities_targeted
		WHERE patch_guid = par_patch_guid AND patch_revision = par_patch_revision;
		
		-- SELECT var_matched_id AS patch_id; -- return patch_id
		
	ELSE
		INSERT INTO pm_patch_master (
			`patch_guid`,
			`patch_revision`,
			`patch_title`,
			`patch_desc`,
			`category_id`,
			`category`,
			`severity_id`,
			`kb_article_no`,
			`application_name`,
			`application_family`,
			`application_id`,
			`bulletin_id`,
			`vendor`,
			`superseded`,
			`superseding`,
			`ref_links`,
			`eula_accept_required`,
			`eula_url`,
			`max_download_size`,
			`vulnerabilities_targeted`
		)
		VALUES
		(
			par_patch_guid,
			par_patch_revision,
			par_patch_title,
			par_patch_desc,
			var_category_id,
			par_category,
			par_severity_id,
			par_kb_article_no,
			par_application,
			par_application_family,
			var_application_id,
			par_bulletin_id,
			par_vendor,
			par_superseded,
			par_superseding,
			par_ref_links,
			par_eula_accept_required,
			par_eula_url,
			par_max_download_size,
			par_vulnerabilities_targeted
		);
		
		-- SELECT last_insert_id() AS patch_id; -- return patch_id
		
	END IF;
		
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pm_delete_patch_scan_by_client_id_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_delete_patch_scan_by_client_id_pr`(
	IN `par_client_guid` CHAR(40)
)
BEGIN

	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	SELECT client_id INTO var_client_id FROM client_master WHERE guid=par_client_guid;
	
	IF var_client_id IS NOT NULL THEN
		DELETE FROM pm_patch_scan_fact WHERE client_id = var_client_id;
	END IF;
	-- Delete data from temp table
	DELETE FROM pm_patch_scan_with_no_metadata WHERE client_guid = par_client_guid;
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pr_insert_patch_scan_clnt_rpt`;
DELIMITER $$
CREATE PROCEDURE `pr_insert_patch_scan_clnt_rpt`(
	IN `par_pm_action` INT(11), -- 1 = Scan, 2 = Install
	IN `par_install_result` INT(11),
	IN `par_incident_date` int(11),
	IN `par_patch_guid` CHAR(40),
	IN `par_patch_revision` int(11),
	IN `par_restart_required` INT(11), -- from client 0=Never reboots, 1=Always Reboots, 2=May reboot
	IN `par_client_guid` CHAR(40),
	IN `par_pmserver_id` char(40),
	IN `par_scan_type` int(11) -- 1: On Demand, 2: Schedule
)
BEGIN
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	DECLARE var_group_id INT(11) DEFAULT NULL;
	DECLARE var_patch_id BIGINT(20) DEFAULT NULL;
	DECLARE var_md5 CHAR(64) DEFAULT NULL;
	DECLARE var_matched_id BIGINT(20) DEFAULT NULL;
	DECLARE var_severity_id INT(11) DEFAULT NULL;
	DECLARE var_is_installed INT(1) DEFAULT NULL;
	DECLARE var_installation_errorcode INT(1) DEFAULT NULL;
	DECLARE var_scan_type INT(11) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	
	SET var_is_installed = 0;
	SET var_installation_errorcode = 0;
	
	SELECT client_id, GroupId INTO var_client_id, var_group_id FROM client_master WHERE guid=par_client_guid LIMIT 1;
	
	IF var_client_id IS NOT NULL THEN
	
		SELECT patch_id INTO var_patch_id FROM pm_patch_master WHERE patch_guid = par_patch_guid AND patch_revision = par_patch_revision LIMIT 1;
		IF var_patch_id IS NOT NULL THEN

			IF par_pm_action = 1 THEN -- Scan Action
				-- Check if patch entry for specified client is already exists.
				SET var_scan_type = (SELECT scan_type FROM pm_patch_scan_fact WHERE patch_id = var_patch_id AND client_id = var_client_id);
				
				IF var_scan_type IS NULL THEN -- Entry not exists then insert it.
					INSERT INTO pm_patch_scan_fact (
						`scan_type`,
						`incident_date`,
						`patch_id`,
						`client_id`,
						`pmserver_id`,
						`group_id`,
						`category_id`,
						`severity_id`,
						`restart_required`,
						`eula_accepted`,
						`application_id`,
						`kb_article_no`,
						`bulletin_id`,
						`installation_status`
					)
					SELECT 
					par_scan_type,
					par_incident_date,
					patch_id,
					var_client_id,
					par_pmserver_id,
					var_group_id,
					`category_id`,
					`severity_id`,
					par_restart_required,
					`eula_accepted`,
					`application_id`,
					`kb_article_no`,
					`bulletin_id`,
					0
					FROM pm_patch_master
					WHERE patch_guid = par_patch_guid AND patch_revision = par_patch_revision;
				
				ELSEIF par_scan_type = 2 AND var_scan_type = 1 THEN -- If exists and scan_type of new entry is SCHEDULE and old is ON-DEMAND then replace old entry 
					UPDATE pm_patch_scan_fact 
					SET
					`scan_type` = par_scan_type,
					`incident_date` = par_incident_date,
					`pmserver_id` = par_pmserver_id,
					`group_id` = var_group_id
					WHERE patch_id = var_patch_id AND client_id = var_client_id;
				-- Else skip the entry.
				END IF;
				
				-- Add a record in pm_patch_download_status_dim table
				SET var_matched_id = (SELECT patch_id FROM pm_patch_download_status_dim WHERE patch_id = var_patch_id AND pmserver_id = par_pmserver_id);
				IF var_matched_id IS NULL THEN
					INSERT INTO pm_patch_download_status_dim(patch_id, pmserver_id) VALUES(var_patch_id, par_pmserver_id);
				END IF;
				
			ELSE -- Install Action
				IF par_install_result = 0 THEN -- [Installation Success]
					
					SET var_is_installed = 1;
				
					UPDATE pm_patch_scan_fact SET incident_date = par_incident_date, scan_type = par_scan_type, installation_status = 8, status_error_code = par_install_result 
					WHERE patch_id = var_patch_id AND client_id = var_client_id;
					
				ELSE -- Non-Zero value means ErrorCode [Installation Failed]
					
					SET var_is_installed = 0;
				
					UPDATE pm_patch_scan_fact SET incident_date = par_incident_date, scan_type = par_scan_type, installation_status = 7, status_error_code = par_install_result 
					WHERE patch_id = var_patch_id AND client_id = var_client_id;
					
				END IF;
				SET var_installation_errorcode = par_install_result; -- Assigend only in case of installation. Default is 0 in Scan case.
			END IF;				
			
			-- Fill reports tables
			
			SET var_severity_id = (SELECT severity_id FROM pm_patch_master WHERE patch_guid = par_patch_guid AND patch_revision = par_patch_revision);
			
			-- Fact Table
			SET var_md5 = MD5(CONCAT(DATE(FROM_UNIXTIME(par_incident_date)), var_patch_id, var_severity_id, var_client_id, var_group_id, var_is_installed, par_scan_type));
			SET var_matched_id = (SELECT rowid FROM rpt_patch_management_fact WHERE md5_match=var_md5);
			IF var_matched_id IS NOT NULL THEN
			
				UPDATE rpt_patch_management_fact SET incident_date = par_incident_date, installation_errorcode = var_installation_errorcode WHERE `rowid` = var_matched_id;
			
			ELSE
				INSERT INTO rpt_patch_management_fact(incident_date, patch_id, severity_id, client_id, group_id, is_installed, installation_errorcode, scan_type_id, md5_match) 
				VALUES(par_incident_date, var_patch_id, var_severity_id, var_client_id, var_group_id, var_is_installed, var_installation_errorcode, par_scan_type, var_md5);
				
				-- Clientwise Summary
				SET var_md5 = MD5(CONCAT(DATE(FROM_UNIXTIME(par_incident_date)), var_severity_id, var_client_id, var_group_id));
				SET var_matched_id = (SELECT rowid FROM rpt_patch_clientwise_summary WHERE md5_match=var_md5);
				
				IF var_matched_id IS NOT NULL THEN				
					IF var_is_installed = 1 THEN
						UPDATE rpt_patch_clientwise_summary SET install_count = (install_count + 1) WHERE `rowid` = var_matched_id;
					ELSE
						UPDATE rpt_patch_clientwise_summary SET missing_count = (missing_count + 1) WHERE `rowid` = var_matched_id;
					END IF;
				ELSE
					IF var_is_installed = 1 THEN
						INSERT INTO rpt_patch_clientwise_summary(incident_date_only, severity_id, client_id, group_id, install_count, md5_match) 
						VALUES(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))), var_severity_id, var_client_id, var_group_id, 1, var_md5);
					ELSE
						INSERT INTO rpt_patch_clientwise_summary(incident_date_only, severity_id, client_id, group_id, missing_count, md5_match) 
						VALUES(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))), var_severity_id, var_client_id, var_group_id, 1, var_md5);
					END IF;
				END IF;
				
				-- Patchwise Summary
				SET var_md5 = MD5(CONCAT(DATE(FROM_UNIXTIME(par_incident_date)), var_patch_id, var_severity_id, var_group_id));
				SET var_matched_id = (SELECT rowid FROM rpt_patch_patchwise_summary WHERE md5_match=var_md5);
				IF var_matched_id IS NOT NULL THEN					
					IF var_is_installed = 1 THEN
						UPDATE rpt_patch_patchwise_summary SET install_client_count = (install_client_count + 1) WHERE `rowid` = var_matched_id;
					ELSE
						UPDATE rpt_patch_patchwise_summary SET missing_client_count = (missing_client_count + 1) WHERE `rowid` = var_matched_id;
					END IF;
				ELSE
					IF var_is_installed = 1 THEN
						INSERT INTO rpt_patch_patchwise_summary(incident_date_only, patch_id, severity_id, group_id, install_client_count, md5_match) 
						VALUES(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))), var_patch_id, var_severity_id, var_group_id, 1, var_md5);
					ELSE
						INSERT INTO rpt_patch_patchwise_summary(incident_date_only, patch_id, severity_id, group_id, missing_client_count, md5_match) 
						VALUES(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))), var_patch_id, var_severity_id, var_group_id, 1, var_md5);
					END IF;
					
				END IF;
				
				-- Add/Update rpt_patch_all_records_summary
				SET var_md5 = MD5(CONCAT(DATE(FROM_UNIXTIME(par_incident_date)), var_client_id, var_group_id, var_severity_id));
				SET var_matched_id = (SELECT rowid FROM rpt_patch_all_records_summary WHERE md5_match=var_md5);				
				IF var_matched_id IS NOT NULL THEN
					IF par_pm_action = 1 THEN
						UPDATE rpt_patch_all_records_summary SET missing_count = (missing_count + 1) WHERE `rowid` = var_matched_id;
					ELSE
						IF var_is_installed = 1 THEN
							UPDATE rpt_patch_all_records_summary SET install_count = (install_count + 1) WHERE `rowid` = var_matched_id;
						END IF;
					END IF;
				ELSE
					IF par_pm_action = 1 THEN
						INSERT INTO rpt_patch_all_records_summary(incident_date_only, client_id, group_id, severity_id, missing_count, md5_match) 
						VALUES(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))), var_client_id, var_group_id, var_severity_id, 1, var_md5);
					ELSE
						IF var_is_installed = 1 THEN
							INSERT INTO rpt_patch_all_records_summary(incident_date_only, client_id, group_id, severity_id, install_count, md5_match) 
							VALUES(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))), var_client_id, var_group_id, var_severity_id, 1, var_md5);
						END IF;
					END IF;
				END IF;
			END IF;
			
		ELSE -- If metadata is not present then insert this patch to table [pm_patch_scan_with_no_metadata]
			SELECT `rowid` INTO var_patch_id FROM pm_patch_scan_with_no_metadata 
			WHERE patch_guid = par_patch_guid 
			AND patch_revision = par_patch_revision 
			AND client_guid = par_client_guid
			LIMIT 1;
			
			IF var_patch_id IS NULL THEN -- Insert only if not exists
				INSERT INTO `pm_patch_scan_with_no_metadata`(
					`install_result`,
					`incident_date`,
					`patch_guid`,
					`patch_revision`,
					`restart_required`,
					`client_guid`,
					`pmserver_id`,
					`scan_type`
				)
				VALUES(
					par_install_result,
					par_incident_date,
					par_patch_guid,
					par_patch_revision,
					par_restart_required,
					par_client_guid,
					par_pmserver_id,
					par_scan_type
				);
			END IF;
		
		END IF;
		
	END IF;

END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pm_get_not_downloaded_patches_for_schedule_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_get_not_downloaded_patches_for_schedule_pr`(
	IN `par_client_guid` VARCHAR(40),
	IN `par_severity_id` INT(11)
)
BEGIN
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	SELECT client_id INTO var_client_id FROM client_master WHERE guid=par_client_guid;
	
	IF par_severity_id = 4 THEN -- [4 = Unspecified Severity]
		SELECT c.patch_guid, c.patch_revision, a.pmserver_id
		FROM pm_patch_scan_fact AS a, pm_patch_download_status_dim AS b, pm_patch_master AS c
		WHERE a.patch_id = b.patch_id AND a.patch_id = c.patch_id
		AND a.client_id = var_client_id
		AND a.scan_type = 2 -- Only Scheduled Scan
		AND b.download_status = FALSE
		AND a.installation_status <> 2 -- skip 'download notification sent' patches.
		GROUP BY a.patch_id, a.pmserver_id;
		
		-- Select Patches after sending to download
		UPDATE pm_patch_scan_fact SET is_patch_selected4installation = TRUE 
		WHERE 
		a.client_id = var_client_id
		AND a.scan_type = 2 -- Only Scheduled Scan
		AND b.download_status = FALSE
		AND a.installation_status <> 2; -- skip 'download notification sent' patches.;
	ELSE
		SELECT c.patch_guid, c.patch_revision, a.pmserver_id
		FROM pm_patch_scan_fact AS a, pm_patch_download_status_dim AS b, pm_patch_master AS c
		WHERE a.patch_id = b.patch_id AND a.patch_id = c.patch_id
		AND a.client_id = var_client_id
		AND a.scan_type = 2 -- Only Scheduled Scan	
		AND a.severity_id >= par_severity_id
		AND b.download_status = FALSE
		AND a.installation_status <> 2 -- skip 'download notification sent' patches.
		GROUP BY a.patch_id, a.pmserver_id;
		
		-- Select Patches after sending to download
		UPDATE pm_patch_scan_fact SET is_patch_selected4installation = TRUE 
		WHERE 
		a.client_id = var_client_id
		AND a.scan_type = 2 -- Only Scheduled Scan	
		AND a.severity_id >= par_severity_id	
		AND b.download_status = FALSE
		AND a.installation_status <> 2; -- skip 'download notification sent' patches.;
	END IF;
	
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pm_get_not_downloaded_patches_ondemand_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_get_not_downloaded_patches_ondemand_pr`()
BEGIN

	SELECT a.patch_id, c.patch_guid, c.patch_revision, a.pmserver_id, d.pm_server, d.status AS pms_status
	FROM pm_patch_scan_fact AS a, pm_patch_download_status_dim AS b, pm_patch_master AS c, pm_server_info AS d, client_master AS e
	WHERE a.patch_id = b.patch_id AND a.patch_id = c.patch_id AND a.pmserver_id = d.pm_server_guid AND a.client_id = e.client_id
	AND a.scan_type = 1 -- Only On-Demand Scan
	AND (a.installation_status IS NULL OR a.installation_status = 0 OR a.installation_status = 1 OR a.installation_status = 3) -- to skip installed patches
	AND a.is_patch_selected4installation = TRUE
	AND (b.download_status = FALSE AND (e.client_status & 32) <> 32) -- Skip Roaming Clients [Patch is not required to be downlaoded for RP Client].
	GROUP BY a.patch_id, a.pmserver_id;
	
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pm_update_patch_download_status_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_update_patch_download_status_pr`(
	IN `par_pmserver_id` CHAR(40),
	IN `par_patch_guid` CHAR(40),
	IN `par_patch_revision` INT(11),
	IN `par_download_status` INT(11),
	IN `par_error_code` INT(11)
)
BEGIN

	DECLARE var_patch_id BIGINT(20) DEFAULT NULL;
	SET time_zone = '+00:00';
	
	SET var_patch_id = (SELECT patch_id FROM pm_patch_master WHERE patch_guid = par_patch_guid AND patch_revision = par_patch_revision);
	
	IF var_patch_id IS NOT NULL THEN
	
		UPDATE pm_patch_scan_fact 
		SET installation_status = par_download_status, status_error_code = par_error_code 
		WHERE patch_id = var_patch_id 
		AND pmserver_id = par_pmserver_id
		-- AND is_patch_selected4installation = TRUE
		AND is_client_selected4installation = TRUE;
		
		IF par_download_status = 4 THEN -- if download successful
			UPDATE pm_patch_download_status_dim 
			SET download_status = TRUE 
			WHERE patch_id = var_patch_id AND pmserver_id = par_pmserver_id;
		END IF;
	END IF;
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pm_get_patchlist_for_install_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_get_patchlist_for_install_pr`(
	IN par_severity_id INT(11),
	IN par_category_id INT(11),
	IN par_restart_required INT(11),
	IN par_client_name VARCHAR(45),
	IN par_eula_accepted INT(1),
	IN par_application_name VARCHAR(255),
	IN par_group_id BIGINT(20),
	IN par_show_subgroup_patches BIT(1),
	IN par_search_str VARCHAR(50), -- Search in kb_article_no and bulletin_id
	IN par_order_by VARCHAR(50),
	IN par_order VARCHAR(10),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_application_id BIGINT(20) DEFAULT NULL;
	DECLARE var_is_sub_group BIT(1) DEFAULT FALSE;
	
	IF par_show_subgroup_patches = TRUE THEN
		SET var_is_sub_group = IFNULL((SELECT TRUE FROM groups WHERE ParentGrpId = par_group_id LIMIT 1), FALSE);
	END IF;
	
	IF par_client_name <> '' AND par_group_id <> 0 THEN
		SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
	ELSEIF par_client_name <> '' THEN
		SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
	ELSE
		SET var_client_count = -1;
	END IF;
	
	IF par_application_name <> '' THEN
		SET var_application_id = (SELECT application_id FROM pm_application_master WHERE application_name = par_application_name LIMIT 1);
	ELSE
		SET var_application_id = -1;
	END IF;
	
	SET time_zone = '+00:00';
	
	IF var_client_count > 1 OR var_client_count = -1 THEN
		SELECT a.patch_id, b.patch_title, b.application_name, b.category, b.severity_id, b.eula_accepted, b.eula_accept_required, a.restart_required, 
		b.max_download_size, b.vulnerabilities_targeted, IFNULL(COUNT(a.client_id), 0) AS client_count, a.installation_status, c.download_status,
		IF(b.severity_id=4, -1, b.severity_id) AS severity_id_for_sort -- As 'Unspecified' sverity is 4, for correct sorting, made it -1
		
		FROM pm_patch_scan_fact AS a, pm_patch_master AS b, pm_patch_download_status_dim c, client_master AS d
		WHERE 
		a.patch_id = b.patch_id AND a.patch_id = c.patch_id AND a.pmserver_id = c.pmserver_id AND a.client_id = d.client_id AND a.installation_status <> 8
		AND (par_severity_id = -1 OR a.severity_id = par_severity_id)
		AND (par_category_id = -1 OR a.category_id = par_category_id)
		AND (var_client_count = -1 OR FIND_IN_SET(a.client_id, var_client_ids_str))
		AND (par_restart_required = -1 OR a.restart_required = par_restart_required)
		AND (par_eula_accepted = -1 OR (b.eula_accepted = par_eula_accepted AND b.eula_accept_required = TRUE))
		AND (var_application_id = -1 OR b.application_id = var_application_id)
		AND (par_group_id = 0 OR d.GroupId = par_group_id OR var_is_sub_group = TRUE)
		AND (par_search_str = '' OR a.kb_article_no = par_search_str OR a.bulletin_id = par_search_str) AND d.client_status & 8 <> 8 -- To skip Uninstalled clients
		GROUP BY a.patch_id
		
		ORDER BY 
		
		CASE WHEN par_order_by = 'patch_title' AND par_order = 'DESC' THEN b.patch_title END DESC,
		CASE WHEN par_order_by = 'patch_title' AND par_order = 'ASC' THEN b.patch_title END ASC,
		
		CASE WHEN par_order_by = 'application_name' AND par_order = 'DESC' THEN b.application_name END DESC,
		CASE WHEN par_order_by = 'application_name' AND par_order = 'ASC' THEN b.application_name END ASC,
		
		CASE WHEN par_order_by = 'category' AND par_order = 'DESC' THEN b.category END DESC,
		CASE WHEN par_order_by = 'category' AND par_order = 'ASC' THEN b.category END ASC,
		
		CASE WHEN par_order_by = 'severity' AND par_order = 'DESC' THEN severity_id_for_sort END DESC,
		CASE WHEN par_order_by = 'severity' AND par_order = 'ASC' THEN severity_id_for_sort END ASC,
		
		CASE WHEN par_order_by = 'max_download_size' AND par_order = 'DESC' THEN b.max_download_size END DESC,
		CASE WHEN par_order_by = 'max_download_size' AND par_order = 'ASC' THEN b.max_download_size END ASC,
		
		CASE WHEN par_order_by = 'eula_accepted' AND par_order = 'DESC' THEN (b.eula_accepted + b.eula_accept_required) END DESC,
		CASE WHEN par_order_by = 'eula_accepted' AND par_order = 'ASC' THEN (b.eula_accepted + b.eula_accept_required) END ASC,
		
		CASE WHEN par_order_by = 'client_count' AND par_order = 'DESC' THEN IFNULL(COUNT(a.client_id), 0) END DESC,
		CASE WHEN par_order_by = 'client_count' AND par_order = 'ASC' THEN IFNULL(COUNT(a.client_id), 0) END ASC,
		
		CASE WHEN par_order_by = 'vulnerabilities_targeted' AND par_order = 'DESC' THEN b.vulnerabilities_targeted END DESC,
		CASE WHEN par_order_by = 'vulnerabilities_targeted' AND par_order = 'ASC' THEN b.vulnerabilities_targeted END ASC,
		
		CASE WHEN par_order_by = '' AND par_order = '' THEN severity_id_for_sort END DESC
		
		LIMIT par_start_index, par_max_records;
		
	ELSEIF var_client_count = 1 OR var_client_count = -1 THEN
		SELECT a.patch_id, b.patch_title, b.application_name, b.category, b.severity_id, b.eula_accepted, b.eula_accept_required, a.restart_required, 
		b.max_download_size, b.vulnerabilities_targeted, IFNULL(COUNT(a.client_id), 0) AS client_count, a.installation_status, c.download_status,
		IF(b.severity_id=4, -1, b.severity_id) AS severity_id_for_sort -- As 'Unspecified' sverity is 4, for correct sorting, made it -1
		
		FROM pm_patch_scan_fact AS a, pm_patch_master AS b, pm_patch_download_status_dim c, client_master AS d
		WHERE 
		a.patch_id = b.patch_id AND a.patch_id = c.patch_id AND a.pmserver_id = c.pmserver_id AND a.client_id = d.client_id AND a.installation_status <> 8
		AND (par_severity_id = -1 OR a.severity_id = par_severity_id)
		AND (par_category_id = -1 OR a.category_id = par_category_id)
		AND (var_client_count = -1 OR a.client_id = var_client_ids_str)
		AND (par_restart_required = -1 OR a.restart_required = par_restart_required)
		AND (par_eula_accepted = -1 OR (b.eula_accepted = par_eula_accepted AND b.eula_accept_required = TRUE))
		AND (var_application_id = -1 OR b.application_id = var_application_id)
		AND (par_group_id = 0 OR d.GroupId = par_group_id OR var_is_sub_group = TRUE)
		AND (par_search_str = '' OR a.kb_article_no = par_search_str OR a.bulletin_id = par_search_str) AND d.client_status & 8 <> 8 -- To skip Uninstalled clients
		GROUP BY a.patch_id
		ORDER BY 
		
		CASE WHEN par_order_by = 'patch_title' AND par_order = 'DESC' THEN b.patch_title END DESC,
		CASE WHEN par_order_by = 'patch_title' AND par_order = 'ASC' THEN b.patch_title END ASC,
		
		CASE WHEN par_order_by = 'application_name' AND par_order = 'DESC' THEN b.application_name END DESC,
		CASE WHEN par_order_by = 'application_name' AND par_order = 'ASC' THEN b.application_name END ASC,
		
		CASE WHEN par_order_by = 'category' AND par_order = 'DESC' THEN b.category END DESC,
		CASE WHEN par_order_by = 'category' AND par_order = 'ASC' THEN b.category END ASC,
		
		CASE WHEN par_order_by = 'severity' AND par_order = 'DESC' THEN severity_id_for_sort END DESC,
		CASE WHEN par_order_by = 'severity' AND par_order = 'ASC' THEN severity_id_for_sort END ASC,
		
		CASE WHEN par_order_by = 'max_download_size' AND par_order = 'DESC' THEN b.max_download_size END DESC,
		CASE WHEN par_order_by = 'max_download_size' AND par_order = 'ASC' THEN b.max_download_size END ASC,
		
		CASE WHEN par_order_by = 'eula_accepted' AND par_order = 'DESC' THEN (b.eula_accepted + b.eula_accept_required) END DESC,
		CASE WHEN par_order_by = 'eula_accepted' AND par_order = 'ASC' THEN (b.eula_accepted + b.eula_accept_required) END ASC,
		
		CASE WHEN par_order_by = 'client_count' AND par_order = 'DESC' THEN IFNULL(COUNT(a.client_id), 0) END DESC,
		CASE WHEN par_order_by = 'client_count' AND par_order = 'ASC' THEN IFNULL(COUNT(a.client_id), 0) END ASC,
		
		CASE WHEN par_order_by = 'vulnerabilities_targeted' AND par_order = 'DESC' THEN b.vulnerabilities_targeted END DESC,
		CASE WHEN par_order_by = 'vulnerabilities_targeted' AND par_order = 'ASC' THEN b.vulnerabilities_targeted END ASC,
		
		CASE WHEN par_order_by = '' AND par_order = '' THEN severity_id_for_sort END DESC
		
		LIMIT par_start_index, par_max_records;
		
	END IF;
	
END $$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pm_get_patchlist_count_for_install_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_get_patchlist_count_for_install_pr`(
	IN par_severity_id INT(11),
	IN par_category_id INT(11),
	IN par_restart_required INT(11),
	IN par_client_name VARCHAR(45),
	IN par_eula_accepted INT(1),
	IN par_application_name VARCHAR(255),
	IN par_group_id BIGINT(20),
	IN par_show_subgroup_patches BIT(1),
	IN par_search_str VARCHAR(50) -- Search in kb_article_no and bulletin_id
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_application_id BIGINT(20) DEFAULT NULL;
	DECLARE var_is_sub_group BIT(1) DEFAULT FALSE;
	
	IF par_show_subgroup_patches = TRUE THEN
		SET var_is_sub_group = IFNULL((SELECT TRUE FROM groups WHERE ParentGrpId = par_group_id LIMIT 1), FALSE);
	END IF;
	
	IF par_client_name <> '' AND par_group_id <> 0 THEN
		SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
	ELSEIF par_client_name <> '' THEN
		SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
	ELSE
		SET var_client_count = -1;
	END IF;
	
	IF par_application_name <> '' THEN
		SET var_application_id = (SELECT application_id FROM pm_application_master WHERE application_name = par_application_name LIMIT 1);
	ELSE
		SET var_application_id = -1;
	END IF;
	
	SET time_zone = '+00:00';
	
	IF var_client_count > 1 OR var_client_count = -1 THEN
		SELECT IFNULL(COUNT(DISTINCT a.patch_id), 0) AS record_count	
		FROM pm_patch_scan_fact AS a, pm_patch_master AS b, client_master AS c
		WHERE 
		a.patch_id = b.patch_id AND a.client_id = c.client_id AND a.installation_status <> 8
		AND (par_severity_id = -1 OR a.severity_id = par_severity_id)
		AND (par_category_id = -1 OR a.category_id = par_category_id)
		AND (var_client_count = -1 OR FIND_IN_SET(a.client_id, var_client_ids_str))
		AND (par_restart_required = -1 OR a.restart_required = par_restart_required)
		AND (par_eula_accepted = -1 OR (b.eula_accepted = par_eula_accepted AND b.eula_accept_required = TRUE))
		AND (var_application_id = -1 OR b.application_id = var_application_id)
		AND (par_group_id = 0 OR a.group_id = par_group_id OR var_is_sub_group = TRUE)
		AND (par_search_str = '' OR a.kb_article_no = par_search_str OR a.bulletin_id = par_search_str)
		AND c.client_status & 8 <> 8; -- To skip Uninstalled clients
		
	ELSEIF var_client_count = 1 OR var_client_count = -1 THEN
		SELECT IFNULL(COUNT(DISTINCT a.patch_id), 0) AS record_count	
		FROM pm_patch_scan_fact AS a, pm_patch_master AS b, client_master AS c
		WHERE 
		a.patch_id = b.patch_id AND a.client_id = c.client_id AND a.installation_status <> 8
		AND (par_severity_id = -1 OR a.severity_id = par_severity_id)
		AND (par_category_id = -1 OR a.category_id = par_category_id)
		AND (var_client_count = -1 OR a.client_id = var_client_ids_str)
		AND (par_restart_required = -1 OR a.restart_required = par_restart_required)
		AND (par_eula_accepted = -1 OR (b.eula_accepted = par_eula_accepted AND b.eula_accept_required = TRUE))
		AND (var_application_id = -1 OR b.application_id = var_application_id)
		AND (par_group_id = 0 OR a.group_id = par_group_id OR var_is_sub_group = TRUE)
		AND (par_search_str = '' OR a.kb_article_no = par_search_str OR a.bulletin_id = par_search_str)
		AND c.client_status & 8 <> 8; -- To skip Uninstalled clients
		
	END IF;	
	
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pm_get_clients_for_patch_install_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_get_clients_for_patch_install_pr`(
	IN par_patch_id BIGINT(20),
	IN par_group_id BIGINT(20),
	IN par_client_name VARCHAR(45),
	IN par_show_subgroup_patches BIT(1),
	IN par_search_str VARCHAR(255), -- Search in Computer-Name and IP-Address
	IN par_restart_required INT(11),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	DECLARE var_is_sub_group BIT(1) DEFAULT FALSE;
	
	IF par_show_subgroup_patches = TRUE THEN
		SET var_is_sub_group = IFNULL((SELECT TRUE FROM groups WHERE ParentGrpId = par_group_id LIMIT 1), FALSE);
	END IF;
	
	IF par_client_name <> '' AND par_group_id <> 0 THEN
		SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
	ELSEIF par_client_name <> '' THEN
		SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
	ELSE
		SET var_client_count = -1;
	END IF;
	
	SET time_zone = '+00:00';
	
	IF var_client_count > 1 OR var_client_count = -1 THEN
		SELECT a.client_id, b.computer_name, b.domain_name, b.GroupId, c.GroupName AS group_name, 
		b.str_ip_address, e.pm_server_name, d.download_status, a.installation_status, a.restart_required,
		(b.client_status & 1024 = 1024) AS exclude_from_patch_install, a.is_client_selected4installation,
		a.status_error_code
		
		FROM pm_patch_scan_fact AS a, client_master AS b, groups AS c, pm_patch_download_status_dim AS d, pm_server_info AS e
		
		WHERE 
		a.client_id = b.client_id AND b.GroupId = c.GroupId AND a.patch_id = d.patch_id AND a.pmserver_id = d.pmserver_id AND a.pmserver_id = e.pm_server_guid
		AND a.patch_id = par_patch_id
		AND a.installation_status <>8
		AND (var_client_count = -1 OR FIND_IN_SET(a.client_id, var_client_ids_str))
		AND b.client_status & 8 <> 8 -- To skip Uninstalled clients
		AND (par_group_id = 0 OR group_id = par_group_id OR var_is_sub_group = TRUE)
		AND (par_restart_required = -1 OR a.restart_required = par_restart_required)
		AND (par_search_str = '' OR b.computer_name LIKE CONCAT('%', par_search_str, '%') OR b.str_ip_address LIKE CONCAT('%', par_search_str, '%'))
		ORDER BY a.patch_id LIMIT par_start_index, par_max_records;
	ELSEIF var_client_count = 1 OR var_client_count = -1 THEN
		SELECT a.client_id, b.computer_name, b.domain_name, b.GroupId, c.GroupName AS group_name, 
		b.str_ip_address, e.pm_server_name, d.download_status, a.installation_status, a.restart_required,
		(b.client_status & 1024 = 1024) AS exclude_from_patch_install, a.is_client_selected4installation,
		a.status_error_code
		
		FROM pm_patch_scan_fact AS a, client_master AS b, groups AS c, pm_patch_download_status_dim AS d, pm_server_info AS e
		
		WHERE 
		a.client_id = b.client_id AND b.GroupId = c.GroupId AND a.patch_id = d.patch_id AND a.pmserver_id = d.pmserver_id AND a.pmserver_id = e.pm_server_guid
		AND a.patch_id = par_patch_id
		AND a.installation_status <>8
		AND (var_client_count = -1 OR a.client_id = var_client_ids_str)
		AND b.client_status & 8 <> 8 -- To skip Uninstalled clients
		AND (par_group_id = 0 OR group_id = par_group_id OR var_is_sub_group = TRUE)
		AND (par_restart_required = -1 OR a.restart_required = par_restart_required)
		AND (par_search_str = '' OR b.computer_name LIKE CONCAT('%', par_search_str, '%') OR b.str_ip_address LIKE CONCAT('%', par_search_str, '%'))
		ORDER BY a.patch_id LIMIT par_start_index, par_max_records;
	END IF;
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pm_get_patches_for_installation_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_get_patches_for_installation_pr`(
	IN `par_client_guid` CHAR(40),
	IN `par_scan_type` INT(11), -- 1: On Demand, 2: Schedule, 0: Return all
	IN `par_severity_id` INT(11), -- (-1) for all severities
	IN `par_is_client_roaming` BIT(1) -- If Client is Roaming then TRUE
)
BEGIN
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	SET var_client_id = (SELECT client_id FROM client_master WHERE guid = par_client_guid LIMIT 1);	
	
    IF par_scan_type = 1 THEN
		SELECT b.patch_guid, b.patch_revision, a.scan_type, a.pmserver_id
		FROM pm_patch_scan_fact AS a, pm_patch_master AS b, pm_patch_download_status_dim AS c
		WHERE a.client_id = var_client_id AND a.patch_id = b.patch_id
		AND a.patch_id = c.patch_id AND a.pmserver_id = c.pmserver_id
		AND a.installation_status <> 8 -- Only not installed patches
		AND (a.installation_status <> 5 OR par_is_client_roaming = TRUE)
		AND a.scan_type = 1
		-- AND (par_severity_id = -1 OR a.severity_id >= par_severity_id)
		AND is_patch_selected4installation = TRUE
		AND is_client_selected4installation = TRUE
		AND (c.download_status = TRUE OR par_is_client_roaming = TRUE); -- Only downloaded patches. OR if client is Roaming [Patch is not required to be downlaoded for RP Client].
	
	ELSEIF par_scan_type = 2 THEN
		SELECT b.patch_guid, b.patch_revision, a.scan_type, a.pmserver_id
		FROM pm_patch_scan_fact AS a, pm_patch_master AS b, pm_patch_download_status_dim AS c
		WHERE a.client_id = var_client_id AND a.patch_id = b.patch_id
		AND a.patch_id = c.patch_id AND a.pmserver_id = c.pmserver_id
		AND a.installation_status <> 8 -- Only not installed patches
		AND (a.installation_status <> 5 OR par_is_client_roaming = TRUE)
		AND a.scan_type = 2
		AND (par_severity_id = -1 OR a.severity_id >= par_severity_id)
		-- AND (is_patch_selected4installation = TRUE OR par_is_client_roaming = TRUE) -- For bug 36033 - We don't need to check is_patch_selected4installation in case of schedule
		AND is_client_selected4installation = TRUE
		AND (c.download_status = TRUE OR par_is_client_roaming = TRUE); -- Only downloaded patches. OR if client is Roaming [Patch is not required to be downlaoded for RP Client].
		
	ELSE -- All Scan Types
		SELECT b.patch_guid, b.patch_revision, a.scan_type, a.pmserver_id 
		FROM pm_patch_scan_fact AS a, pm_patch_master AS b, pm_patch_download_status_dim AS c
		WHERE a.client_id = var_client_id AND a.patch_id = b.patch_id
		AND a.patch_id = c.patch_id AND a.pmserver_id = c.pmserver_id
		AND a.installation_status <> 8 -- Only not installed patches
		AND (a.installation_status <> 5 OR par_is_client_roaming = TRUE)
		AND (par_severity_id = -1 OR a.severity_id >= par_severity_id OR a.scan_type = 1) -- All OnDemand records + Only those Schedule records with >= Severity criteria
		AND ((a.scan_type = 2) OR (is_patch_selected4installation = TRUE OR par_is_client_roaming = TRUE))
		AND is_client_selected4installation = TRUE
		AND (c.download_status = TRUE OR par_is_client_roaming = TRUE); -- Only downloaded patches. OR if client is Roaming [Patch is not required to be downlaoded for RP Client].
	END IF;
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pm_update_installation_status_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_update_installation_status_pr`(
	IN `par_client_guid` CHAR(40),
	IN `par_patch_guid` CHAR(40),
	IN `par_patch_revision` INT(11),
	IN `par_installation_status` INT(11),
	IN `par_error_code` INT(11)
)
BEGIN
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	DECLARE var_patch_id BIGINT(20) DEFAULT NULL;
	
	SET var_client_id = (SELECT client_id FROM client_master WHERE guid = par_client_guid LIMIT 1);	
	SET var_patch_id = (SELECT patch_id FROM pm_patch_master WHERE patch_guid = par_patch_guid AND patch_revision = par_patch_revision LIMIT 1);
	
	IF par_installation_status = 8 THEN -- Installation success
		-- Update installation status and de-select Selected Patches
		UPDATE pm_patch_scan_fact 
		SET installation_status = par_installation_status, status_error_code = 0, is_patch_selected4installation = FALSE 
		WHERE client_id = var_client_id AND patch_id = var_patch_id;
		
	ELSE
		-- Update installation status and ErrorCode
		UPDATE pm_patch_scan_fact 
		SET installation_status = par_installation_status, status_error_code = par_error_code
		WHERE client_id = var_client_id AND patch_id = var_patch_id;
	END IF;
	
END$$
DELIMITER ;

CREATE TABLE IF NOT EXISTS `pm_exclusion_settings` (
  `exclude_below_endpoints` BIT(1) DEFAULT b'1',
  `exclude_endpoints_server_os` BIT(1) DEFAULT b'0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO pm_exclusion_settings (exclude_below_endpoints, exclude_endpoints_server_os) VALUE (1, 0);

DROP PROCEDURE IF EXISTS `pm_get_download_missing_patch_list_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_get_download_missing_patch_list_pr`(
)
BEGIN

	SELECT pmserver_id, patch_id FROM pm_patch_download_status_dim WHERE download_status = FALSE ORDER BY pmserver_id DESC;
	
END$$
DELIMITER ;


DROP PROCEDURE IF EXISTS `pm_get_pms_settings_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_get_pms_settings_pr`(
IN par_pm_server_guid char(40)
)
BEGIN

	SELECT * FROM pm_server_info WHERE pm_server_guid = par_pm_server_guid;

END$$
DELIMITER ;


DROP PROCEDURE IF EXISTS `pm_dash_get_patch_info_by_severity_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_dash_get_patch_info_by_severity_pr`(
)
BEGIN

	SELECT severity_id, COUNT(DISTINCT patch_id) AS missing_cnt 
	FROM pm_patch_scan_fact 	
	WHERE installation_status <> 8
	GROUP BY severity_id 
	ORDER BY severity_id DESC;

END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `dash_security_pm_get_patch_info_by_severity_detail_table_pr`;
DELIMITER $$
CREATE PROCEDURE `dash_security_pm_get_patch_info_by_severity_detail_table_pr`(
	IN par_severity_id INT(11),
	IN par_activity_id INT(11),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN

	-- activity_id refed from MACRO PATCH_SCAN_ACTIVITY_XXX in rptintst.h
	SET time_zone = '+00:00';
	
	IF 1 = par_activity_id THEN
	
		SELECT application_name AS application, category, patch_title AS title,
		computer_name, domain_name, incident_date
		FROM
		(
			SELECT incident_date, patch_id, client_id
			FROM pm_patch_scan_fact
			WHERE
			par_severity_id = severity_id
			ORDER BY incident_date DESC
			LIMIT par_start_index, par_max_records
		) AS a, pm_patch_master AS b, client_master AS c
		WHERE 
		a.patch_id = b.patch_id
		AND a.client_id = c.client_id;
		 
	 ELSE
	 
		SELECT application_name AS application, category, patch_title AS title,
		computer_name, domain_name, incident_date
		FROM
		(
			SELECT incident_date, patch_id, client_id
			FROM pm_patch_scan_fact
			WHERE 
			par_severity_id = severity_id
			AND installation_status = 8
			ORDER BY incident_date DESC
			LIMIT par_start_index, par_max_records
		) AS a, pm_patch_master AS b, client_master AS c
		WHERE 
		a.patch_id = b.patch_id
		AND a.client_id = c.client_id;
	 		 
	 END IF;
	 
END$$
DELIMITER ;

-- Reports SPs --
DROP PROCEDURE IF EXISTS `pm_rpt_get_clientwise_count_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_rpt_get_clientwise_count_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
    IN par_severity_id INT(1)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN 
		SELECT IFNULL(COUNT(distinct client_id), 0) AS record_count
		FROM rpt_patch_clientwise_summary;
	ELSE
		IF par_client_name='' THEN
			
			SELECT IFNULL(COUNT(distinct client_id), 0) AS record_count
			FROM
			(              
				SELECT MAX(incident_date), patch_id, client_id, is_installed, rowid
				FROM rpt_patch_management_fact AS a USE INDEX(idx_incident_date)
				WHERE
				a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND (par_severity_id = -1 OR severity_id = par_severity_id)
				AND (par_group_id = 0 OR group_id = par_group_id)
				GROUP BY patch_id, client_id, is_installed
			) AS a;
		ELSE
			IF par_client_name <> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
			ELSEIF par_client_name <> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
			ELSE
				SET var_client_count = -1;
			END IF;
			
			IF var_client_count > 1 THEN
				
				SELECT IFNULL(COUNT(distinct client_id), 0) AS record_count
				FROM
				(              
					SELECT MAX(incident_date), patch_id, client_id, is_installed, rowid
					FROM rpt_patch_management_fact AS a USE INDEX(idx_incident_date)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_severity_id = -1 OR severity_id = par_severity_id)
					AND (par_group_id = 0 OR group_id = par_group_id)
					AND FIND_IN_SET(client_id, var_client_ids_str)
					GROUP BY patch_id, client_id, is_installed
				) AS a;
				
			ELSEIF var_client_count = 1 THEN
				
				SELECT IFNULL(COUNT(distinct client_id), 0) AS record_count
				FROM
				(              
					SELECT MAX(incident_date), patch_id, client_id, is_installed, rowid
					FROM rpt_patch_management_fact AS a USE INDEX(idx_incident_date)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_severity_id = -1 OR severity_id = par_severity_id)
					AND (par_group_id = 0 OR group_id = par_group_id)
					AND client_id = var_client_ids_str
					GROUP BY patch_id, client_id, is_installed
				) AS a;
				
			ELSEIF var_client_count = -1 THEN
				
				SELECT IFNULL(COUNT(distinct client_id), 0) AS record_count
				FROM
				(              
					SELECT MAX(incident_date), patch_id, client_id, is_installed, rowid
					FROM rpt_patch_management_fact AS a USE INDEX(idx_incident_date)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_severity_id = -1 OR severity_id = par_severity_id)
					AND (par_group_id = 0 OR group_id = par_group_id)
					GROUP BY patch_id, client_id, is_installed
				) AS a;
				
			END IF;
		END IF;
	END IF;
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pm_rpt_get_clientwise_table_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_rpt_get_clientwise_table_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
    IN par_severity_id INT(1),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN
		
		SELECT a.client_id, computer_name, domain_name, GroupId, 
		SUM(IF(is_installed = 0,1,0)) AS missing_count_sum, 
		SUM(IF(is_installed = 1,1,0)) AS install_count_sum,
		SUM(IF(installation_errorcode = 0,0,1)) AS install_failed_count,
		SUM(IF(download_status = TRUE AND is_installed = 0,1,0)) AS downloaded_patch_count
		FROM
		(              
			SELECT MAX(incident_date), a.patch_id, client_id, is_installed, installation_errorcode, download_status, rowid
			FROM rpt_patch_management_fact AS a, pm_patch_download_status_dim AS b
			WHERE
			a.patch_id = b.patch_id
			GROUP BY a.patch_id, client_id, is_installed
		) AS a, client_master AS b
		WHERE
		a.client_id = b.client_id
		GROUP BY client_id
		ORDER BY a.rowid DESC LIMIT par_start_index,par_max_records;
	ELSE
		IF par_client_name='' THEN
			
			SELECT a.client_id, computer_name, domain_name, GroupId, 
			SUM(IF(is_installed = 0,1,0)) AS missing_count_sum, 
			SUM(IF(is_installed = 1,1,0)) AS install_count_sum,
			SUM(IF(installation_errorcode = 0,0,1)) AS install_failed_count,
			SUM(IF(download_status = TRUE AND is_installed = 0,1,0)) AS downloaded_patch_count
			FROM
			(
				SELECT MAX(incident_date), a.patch_id, client_id, is_installed, installation_errorcode, download_status, rowid
				FROM rpt_patch_management_fact AS a, pm_patch_download_status_dim AS b
				WHERE
				a.patch_id = b.patch_id
				AND a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND (par_severity_id = -1 OR severity_id = par_severity_id)
				AND (par_group_id = 0 OR group_id = par_group_id)
				GROUP BY a.patch_id, client_id, is_installed
			) AS a, client_master AS b
			WHERE 
			a.client_id = b.client_id
			GROUP BY client_id
			ORDER BY a.rowid DESC LIMIT par_start_index,par_max_records;
		ELSE
			IF par_client_name <> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
			ELSEIF par_client_name <> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
			ELSE
				SET var_client_count = -1;
			END IF;
			
			IF var_client_count > 1 THEN
				
				SELECT a.client_id, computer_name, domain_name, GroupId, 
				SUM(IF(is_installed = 0,1,0)) AS missing_count_sum, 
				SUM(IF(is_installed = 1,1,0)) AS install_count_sum,
				SUM(IF(installation_errorcode = 0,0,1)) AS install_failed_count,
				SUM(IF(download_status = TRUE AND is_installed = 0,1,0)) AS downloaded_patch_count
				FROM
				(
					SELECT MAX(incident_date), a.patch_id, client_id, is_installed, installation_errorcode, download_status, rowid
					FROM rpt_patch_management_fact AS a, pm_patch_download_status_dim AS b
					WHERE
					a.patch_id = b.patch_id
					AND a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_severity_id = -1 OR severity_id = par_severity_id)
					AND (par_group_id = 0 OR group_id = par_group_id)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					GROUP BY a.patch_id, client_id, is_installed    
				) AS a, client_master AS b
				WHERE 
				a.client_id = b.client_id
				GROUP BY client_id
				ORDER BY a.rowid DESC LIMIT par_start_index,par_max_records;
				
			ELSEIF var_client_count = 1 THEN
				
				SELECT a.client_id, computer_name, domain_name, GroupId, 
				SUM(IF(is_installed = 0,1,0)) AS missing_count_sum, 
				SUM(IF(is_installed = 1,1,0)) AS install_count_sum,
				SUM(IF(installation_errorcode = 0,0,1)) AS install_failed_count,
				SUM(IF(download_status = TRUE AND is_installed = 0,1,0)) AS downloaded_patch_count
				FROM
				(              
					SELECT MAX(incident_date), a.patch_id, client_id, is_installed, installation_errorcode, download_status, rowid
					FROM rpt_patch_management_fact AS a, pm_patch_download_status_dim AS b
					WHERE
					a.patch_id = b.patch_id
					AND a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_severity_id = -1 OR severity_id = par_severity_id)
					AND (par_group_id = 0 OR group_id = par_group_id)
					AND client_id = var_client_ids_str
					GROUP BY a.patch_id, client_id, is_installed    
				) AS a, client_master AS b
				WHERE 
				a.client_id = b.client_id
				GROUP BY client_id
				ORDER BY a.rowid DESC LIMIT par_start_index,par_max_records;
			
			ELSEIF var_client_count = -1 THEN
				
				SELECT a.client_id, computer_name, domain_name, GroupId, 
				SUM(IF(is_installed = 0,1,0)) AS missing_count_sum, 
				SUM(IF(is_installed = 1,1,0)) AS install_count_sum,
				SUM(IF(installation_errorcode = 0,0,1)) AS install_failed_count,
				SUM(IF(download_status = TRUE AND is_installed = 0,1,0)) AS downloaded_patch_count
				FROM
				(              
					SELECT MAX(incident_date), a.patch_id, client_id, is_installed, installation_errorcode, download_status rowid
					FROM rpt_patch_management_fact AS a, pm_patch_download_status_dim AS b
					WHERE
					a.patch_id = b.patch_id
					AND a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_severity_id = -1 OR severity_id = par_severity_id)
					AND (par_group_id = 0 OR group_id = par_group_id)
					GROUP BY a.patch_id, client_id, is_installed    
				) AS a, client_master AS b
				WHERE 
				a.client_id = b.client_id
				GROUP BY client_id
				ORDER BY a.rowid DESC LIMIT par_start_index,par_max_records;
			END IF;
			
		END IF;
	END IF;
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pm_rpt_get_patchwise_count_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_rpt_get_patchwise_count_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
    IN par_severity_id INT(1)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN 
		
		SELECT IFNULL(COUNT(DISTINCT patch_id), 0) AS record_count
		FROM
		(              
			SELECT MAX(incident_date), patch_id, client_id, is_installed, rowid
			FROM rpt_patch_management_fact AS a USE INDEX(idx_incident_date)			
			GROUP BY client_id, patch_id, is_installed    
		) AS a 
		GROUP BY patch_id;
	ELSE
		IF par_client_name='' THEN
			
			SELECT IFNULL(COUNT(DISTINCT patch_id), 0) AS record_count
			FROM
			(              
				SELECT MAX(incident_date), patch_id, client_id, is_installed, rowid
				FROM rpt_patch_management_fact AS a USE INDEX(idx_incident_date)
				WHERE
				a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND (par_severity_id = -1 OR severity_id = par_severity_id)
				AND (par_group_id = 0 OR group_id = par_group_id)
				GROUP BY client_id, patch_id, is_installed    
			) AS a;
		ELSE
			IF par_client_name <> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
			ELSEIF par_client_name <> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
			ELSE
				SET var_client_count = -1;
			END IF;
			
			IF var_client_count > 1 THEN
				
				SELECT IFNULL(COUNT(DISTINCT patch_id), 0) AS record_count
				FROM
				(              
					SELECT MAX(incident_date), patch_id, client_id, is_installed, rowid
					FROM rpt_patch_management_fact AS a USE INDEX(idx_incident_date)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_severity_id = -1 OR severity_id = par_severity_id)
					AND (par_group_id = 0 OR group_id = par_group_id)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					GROUP BY client_id, patch_id, is_installed    
				) AS a;
				
			ELSEIF var_client_count = 1 THEN
				
				SELECT IFNULL(COUNT(DISTINCT patch_id), 0) AS record_count
				FROM
				(              
					SELECT MAX(incident_date), patch_id, client_id, is_installed, rowid
					FROM rpt_patch_management_fact AS a USE INDEX(idx_incident_date)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_severity_id = -1 OR severity_id = par_severity_id)
					AND (par_group_id = 0 OR group_id = par_group_id)
					AND client_id = var_client_ids_str
					GROUP BY client_id, patch_id, is_installed    
				) AS a;
				
			ELSEIF var_client_count = -1 THEN
				
				SELECT IFNULL(COUNT(DISTINCT patch_id), 0) AS record_count
				FROM
				(              
					SELECT MAX(incident_date), patch_id, client_id, is_installed, rowid
					FROM rpt_patch_management_fact AS a USE INDEX(idx_incident_date)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_severity_id = -1 OR severity_id = par_severity_id)
					AND (par_group_id = 0 OR group_id = par_group_id)
					GROUP BY client_id, patch_id, is_installed    
				) AS a;
				
			END IF;
		END IF;
	END IF;
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pm_rpt_get_patchwise_table_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_rpt_get_patchwise_table_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
    IN par_severity_id INT(1),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN
		
		SELECT a.patch_id, b.patch_title, b.vulnerabilities_targeted, a.severity_id,
		SUM(IF(is_installed = 0,1,0)) AS missing_count_sum, SUM(IF(is_installed = 1,1,0)) AS install_count_sum, patch_id 
		FROM
		(              
			SELECT MAX(incident_date), patch_id, client_id, is_installed, rowid
			FROM rpt_patch_management_fact AS a USE INDEX(idx_incident_date)
			GROUP BY client_id, patch_id, is_installed    
		) AS a, pm_patch_master AS b
		WHERE 
		a.patch_id = b.patch_id
		GROUP BY patch_id
		ORDER BY a.rowid DESC LIMIT par_start_index,par_max_records;
		
	ELSE
		IF par_client_name='' THEN
			
			SELECT a.patch_id, b.patch_title, b.vulnerabilities_targeted, a.severity_id,
			SUM(IF(is_installed = 0,1,0)) AS missing_count_sum, SUM(IF(is_installed = 1,1,0)) AS install_count_sum
			FROM
			(              
				SELECT MAX(incident_date), patch_id, client_id, is_installed, severity_id, rowid
				FROM rpt_patch_management_fact AS a USE INDEX(idx_incident_date)
				WHERE
				a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND (par_severity_id = -1 OR severity_id = par_severity_id)
				AND (par_group_id = 0 OR group_id = par_group_id)
				GROUP BY client_id, patch_id, is_installed    
			) AS a, pm_patch_master AS b
			WHERE 
			a.patch_id = b.patch_id
			GROUP BY patch_id
			ORDER BY a.rowid DESC LIMIT par_start_index,par_max_records;
			
		ELSE
			IF par_client_name <> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
			ELSEIF par_client_name <> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
			ELSE
				SET var_client_count = -1;
			END IF;
			
			IF var_client_count > 1 THEN
				
				SELECT a.patch_id, b.patch_title, b.vulnerabilities_targeted, a.severity_id,
				SUM(IF(is_installed = 0,1,0)) AS missing_count_sum, SUM(IF(is_installed = 1,1,0)) AS install_count_sum
				FROM
				(              
					SELECT MAX(incident_date), patch_id, client_id, is_installed, severity_id, rowid
					FROM rpt_patch_management_fact AS a USE INDEX(idx_incident_date)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_severity_id = -1 OR severity_id = par_severity_id)
					AND (par_group_id = 0 OR group_id = par_group_id)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					GROUP BY client_id, patch_id, is_installed    
				) AS a, pm_patch_master AS b
				WHERE 
				a.patch_id = b.patch_id
				GROUP BY patch_id
				ORDER BY a.rowid DESC LIMIT par_start_index,par_max_records;
				
			ELSEIF var_client_count = 1 THEN
				
				SELECT a.patch_id, b.patch_title, b.vulnerabilities_targeted, a.severity_id,
				SUM(IF(is_installed = 0,1,0)) AS missing_count_sum, SUM(IF(is_installed = 1,1,0)) AS install_count_sum 
				FROM
				(              
					SELECT MAX(incident_date), patch_id, client_id, is_installed, severity_id, rowid
					FROM rpt_patch_management_fact AS a USE INDEX(idx_incident_date)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_severity_id = -1 OR severity_id = par_severity_id)
					AND (par_group_id = 0 OR group_id = par_group_id)
					AND client_id = var_client_ids_str
					GROUP BY client_id, patch_id, is_installed    
				) AS a, pm_patch_master AS b
				WHERE 
				a.patch_id = b.patch_id
				GROUP BY patch_id
				ORDER BY a.rowid DESC LIMIT par_start_index,par_max_records;
				
			ELSEIF var_client_count = -1 THEN
				
				SELECT a.patch_id, b.patch_title, b.vulnerabilities_targeted, a.severity_id,
				SUM(IF(is_installed = 0,1,0)) AS missing_count_sum, SUM(IF(is_installed = 1,1,0)) AS install_count_sum 
				FROM
				(              
					SELECT MAX(incident_date), patch_id, client_id, is_installed, severity_id, rowid
					FROM rpt_patch_management_fact AS a USE INDEX(idx_incident_date)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_severity_id = -1 OR severity_id = par_severity_id)
					AND (par_group_id = 0 OR group_id = par_group_id)
					GROUP BY client_id, patch_id, is_installed    
				) AS a, pm_patch_master AS b
				WHERE 
				a.patch_id = b.patch_id
				GROUP BY patch_id
				ORDER BY a.rowid DESC LIMIT par_start_index,par_max_records;
				
			END IF;
		END IF;
	END IF;
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pm_rpt_get_patchlistpopup_table_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_rpt_get_patchlistpopup_table_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_id BIGINT(20),
    IN par_severity_id INT(1),
    IN par_patch_status INT(1),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN 
		IF par_patch_status = 0 THEN -- MISSING
			SELECT '1970-01-01' AS incident_date, a.patch_id, b.patch_title, b.vulnerabilities_targeted, b.severity_id, 
			b.application_name, b.category, 0 AS scan_type_id, 0 AS incident_date_in_seconds,
			0 AS installation_errorcode
			FROM
			(
				SELECT 
				DISTINCT patch_id
				FROM rpt_patch_management_fact
				WHERE client_id = par_client_id
				AND is_installed = par_patch_status
				GROUP BY a.patch_id
				ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
			) AS a, pm_patch_master AS b
			WHERE 
			a.patch_id = b.patch_id;
		ELSEIF par_patch_status = 1 THEN -- INSTALLED
			SELECT FROM_UNIXTIME(incident_date) AS incident_date, a.patch_id, b.patch_title, b.vulnerabilities_targeted, 
			b.severity_id, b.application_name, b.category, a.scan_type_id, incident_date AS incident_date_in_seconds,
			0 AS installation_errorcode
			FROM
			(
				SELECT 
				incident_date, patch_id, scan_type_id
				FROM rpt_patch_management_fact
				WHERE client_id = par_client_id
				AND is_installed = par_patch_status
				GROUP BY a.patch_id
				ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
			) AS a, pm_patch_master AS b
			WHERE 
			a.patch_id = b.patch_id;
			
		ELSEIF par_patch_status = 2 THEN -- DOWNLOADED
			SELECT FROM_UNIXTIME(incident_date) AS incident_date, a.patch_id, b.patch_title, b.vulnerabilities_targeted, 
			b.severity_id, b.application_name, b.category,a.scan_type_id, incident_date AS incident_date_in_seconds,
			0 AS installation_errorcode
			FROM
			(
				SELECT 
				incident_date, a.patch_id, scan_type_id
				FROM rpt_patch_management_fact AS a, pm_patch_download_status_dim AS b
				WHERE
				a.patch_id = b.patch_id
				AND client_id = par_client_id
				AND b.download_status = TRUE -- only downloaded patches
				GROUP BY a.patch_id
				ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
			) AS a, pm_patch_master AS b
			WHERE 
			a.patch_id = b.patch_id;
		
		ELSEIF par_patch_status = 3 THEN -- INSTALLATION FAILED
			SELECT FROM_UNIXTIME(incident_date) AS incident_date, a.patch_id, b.patch_title, b.vulnerabilities_targeted, 
			b.severity_id, b.application_name, b.category,a.scan_type_id, incident_date AS incident_date_in_seconds,
			installation_errorcode
			FROM
			(
				SELECT 
				incident_date, patch_id, scan_type_id, installation_errorcode
				FROM rpt_patch_management_fact AS a 
				WHERE client_id = par_client_id
				AND installation_errorcode <> 0 -- Installation Failed patches
				GROUP BY a.patch_id
				ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
			) AS a, pm_patch_master AS b
			WHERE
			a.patch_id = b.patch_id;

		END IF;
	ELSE
		IF par_patch_status = 0 THEN -- MISSING
			SELECT '1970-01-01' AS incident_date, a.patch_id, b.patch_title, b.vulnerabilities_targeted, b.severity_id, 
			b.application_name, b.category, 0 AS scan_type_id, 0 AS incident_date_in_seconds,
			0 AS installation_errorcode
			FROM
			(
				SELECT 
				DISTINCT patch_id
				FROM rpt_patch_management_fact AS a 
				WHERE
				a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND (par_severity_id = -1 OR severity_id = par_severity_id)
				AND (par_group_id = 0 OR group_id = par_group_id)
				AND client_id = par_client_id
				AND is_installed = par_patch_status
				GROUP BY a.patch_id
				ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
			) AS a, pm_patch_master AS b
			WHERE 
			a.patch_id = b.patch_id;
		ELSEIF par_patch_status = 1 THEN -- INSTALLED
			SELECT FROM_UNIXTIME(incident_date) AS incident_date, a.patch_id, b.patch_title, b.vulnerabilities_targeted, 
			b.severity_id, b.application_name, b.category,a.scan_type_id, incident_date AS incident_date_in_seconds,
			0 AS installation_errorcode
			FROM
			(
				SELECT 
				incident_date, patch_id, scan_type_id
				FROM rpt_patch_management_fact AS a 
				WHERE
				a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND (par_severity_id = -1 OR severity_id = par_severity_id)
				AND (par_group_id = 0 OR group_id = par_group_id)
				AND client_id = par_client_id
				AND is_installed = par_patch_status
				GROUP BY a.patch_id
				ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
			) AS a, pm_patch_master AS b
			WHERE 
			a.patch_id = b.patch_id;
			
		ELSEIF par_patch_status = 2 THEN -- DOWNLOADED
			SELECT FROM_UNIXTIME(incident_date) AS incident_date, a.patch_id, b.patch_title, b.vulnerabilities_targeted, 
			b.severity_id, b.application_name, b.category,a.scan_type_id, incident_date AS incident_date_in_seconds,
			0 AS installation_errorcode
			FROM
			(
				SELECT 
				incident_date, a.patch_id, scan_type_id
				FROM rpt_patch_management_fact AS a, pm_patch_download_status_dim AS b
				WHERE
				a.patch_id = b.patch_id
				AND a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND (par_severity_id = -1 OR severity_id = par_severity_id)
				AND (par_group_id = 0 OR group_id = par_group_id)
				AND client_id = par_client_id
				AND b.download_status = TRUE -- only downloaded patches
				GROUP BY a.patch_id
				ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
			) AS a, pm_patch_master AS b
			WHERE 
			a.patch_id = b.patch_id;
		
		ELSEIF par_patch_status = 3 THEN -- INSTALLATION FAILED
			SELECT FROM_UNIXTIME(incident_date) AS incident_date, a.patch_id, b.patch_title, b.vulnerabilities_targeted, 
			b.severity_id, b.application_name, b.category,a.scan_type_id, incident_date AS incident_date_in_seconds,
			installation_errorcode
			FROM
			(
				SELECT 
				incident_date, patch_id, scan_type_id, installation_errorcode
				FROM rpt_patch_management_fact AS a 
				WHERE
				a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND (par_severity_id = -1 OR severity_id = par_severity_id)
				AND (par_group_id = 0 OR group_id = par_group_id)
				AND client_id = par_client_id
				AND installation_errorcode <> 0 -- Installation Failed patches
				GROUP BY a.patch_id
				ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
			) AS a, pm_patch_master AS b
			WHERE 
			a.patch_id = b.patch_id;

		END IF;
	END IF;
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pm_rpt_get_clientlistpopup_table_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_rpt_get_clientlistpopup_table_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
    IN par_severity_id INT(1),
    IN par_patch_status INT(1),
	IN par_patch_id INT (1),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN
		IF par_patch_status = 0 THEN -- MISSING
			SELECT '1970-01-01' AS incident_date, a.client_id, b.computer_name, b.domain_name, c.GroupName, 
			b.str_ip_address, 0 AS scan_type_id, 0 AS incident_date_in_seconds
			FROM
			(
				SELECT 
				DISTINCT client_id
				FROM rpt_patch_management_fact
				WHERE patch_id = par_patch_id
				AND is_installed = par_patch_status
				ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
			) AS a, client_master AS b, groups AS c
			WHERE 
			a.client_id = b.client_id
			AND b.GroupId = c.GroupId
			ORDER BY b.computer_name DESC;
		ELSE -- INSTALLED
			SELECT FROM_UNIXTIME(incident_date) AS incident_date, a.client_id, b.computer_name, b.domain_name, c.GroupName, 
			b.str_ip_address, a.scan_type_id, incident_date AS incident_date_in_seconds
			FROM
			(
				SELECT 
				incident_date, client_id, scan_type_id
				FROM rpt_patch_management_fact
				WHERE patch_id = par_patch_id
				AND is_installed = par_patch_status
				ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
			) AS a, client_master AS b, groups AS c
			WHERE 
			a.client_id = b.client_id
			AND b.GroupId = c.GroupId
			ORDER BY b.computer_name DESC;
		END IF;
	ELSE
		IF par_client_name='' THEN
			IF par_patch_status = 0 THEN -- MISSING
				SELECT '1970-01-01' AS incident_date, a.client_id, b.computer_name, b.domain_name, c.GroupName, 
				b.str_ip_address, 0 AS scan_type_id, 0 AS incident_date_in_seconds
				FROM
				(
					SELECT 
					DISTINCT client_id
					FROM rpt_patch_management_fact AS a
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND patch_id = par_patch_id
					AND is_installed = par_patch_status
					AND (par_severity_id = -1 OR severity_id = par_severity_id)
					AND (par_group_id = 0 OR group_id = par_group_id)
					ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
				) AS a, client_master AS b, groups AS c
				WHERE 
				a.client_id = b.client_id
				AND b.GroupId = c.GroupId
				ORDER BY b.computer_name DESC;
			ELSE -- INSTALLED
				SELECT FROM_UNIXTIME(incident_date) AS incident_date, a.client_id, b.computer_name, b.domain_name, c.GroupName, 
				b.str_ip_address, a.scan_type_id, incident_date AS incident_date_in_seconds
				FROM
				(
					SELECT 
					incident_date, client_id, scan_type_id
					FROM rpt_patch_management_fact AS a
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND patch_id = par_patch_id
					AND is_installed = par_patch_status
					AND (par_severity_id = -1 OR severity_id = par_severity_id)
					AND (par_group_id = 0 OR group_id = par_group_id)
					ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
				) AS a, client_master AS b, groups AS c
				WHERE 
				a.client_id = b.client_id
				AND b.GroupId = c.GroupId
				ORDER BY b.computer_name DESC;
			END IF;
			
		ELSE
			IF par_client_name <> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
			ELSEIF par_client_name <> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
			ELSE
				SET var_client_count = -1;
			END IF;
			
			IF var_client_count > 1 THEN
				IF par_patch_status = 0 THEN -- MISSING
					SELECT '1970-01-01' AS incident_date, a.client_id, b.computer_name, b.domain_name, c.GroupName, 
					b.str_ip_address, 0 AS scan_type_id, 0 AS incident_date_in_seconds
					FROM
					(
						SELECT 
						DISTINCT client_id
						FROM rpt_patch_management_fact AS a
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND patch_id = par_patch_id
						AND is_installed = par_patch_status
						AND (par_severity_id = -1 OR severity_id = par_severity_id)
						AND (par_group_id = 0 OR group_id = par_group_id)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, client_master AS b, groups AS c
					WHERE 
					a.client_id = b.client_id
					AND b.GroupId = c.GroupId
					ORDER BY b.computer_name DESC;
				ELSE -- INSTALLED
					SELECT FROM_UNIXTIME(incident_date) AS incident_date, a.client_id, b.computer_name, b.domain_name, c.GroupName, 
					b.str_ip_address, a.scan_type_id, incident_date AS incident_date_in_seconds
					FROM
					(
						SELECT 
						incident_date, client_id, scan_type_id
						FROM rpt_patch_management_fact AS a
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND patch_id = par_patch_id
						AND is_installed = par_patch_status
						AND (par_severity_id = -1 OR severity_id = par_severity_id)
						AND (par_group_id = 0 OR group_id = par_group_id)
						AND FIND_IN_SET(a.client_id, var_client_ids_str)
						ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, client_master AS b, groups AS c
					WHERE 
					a.client_id = b.client_id
					AND b.GroupId = c.GroupId
					ORDER BY b.computer_name DESC;
				END IF;
				
			ELSEIF var_client_count = 1 THEN
				IF par_patch_status = 0 THEN -- MISSING
					SELECT '1970-01-01' AS incident_date, a.client_id, b.computer_name, b.domain_name, c.GroupName, 
					b.str_ip_address, 0 AS scan_type_id, 0 AS incident_date_in_seconds
					FROM
					(
						SELECT 
						DISTINCT client_id
						FROM rpt_patch_management_fact AS a
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND patch_id = par_patch_id
						AND is_installed = par_patch_status
						AND (par_severity_id = -1 OR severity_id = par_severity_id)
						AND (par_group_id = 0 OR group_id = par_group_id)
						AND client_id = var_client_ids_str
						ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, client_master AS b, groups AS c
					WHERE 
					a.client_id = b.client_id
					AND b.GroupId = c.GroupId
					ORDER BY b.computer_name DESC;
				ELSE -- INSTALLED
					SELECT FROM_UNIXTIME(incident_date) AS incident_date, a.client_id, b.computer_name, b.domain_name, c.GroupName, 
					b.str_ip_address, a.scan_type_id, incident_date AS incident_date_in_seconds
					FROM
					(
						SELECT 
						incident_date, client_id, scan_type_id
						FROM rpt_patch_management_fact AS a
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND patch_id = par_patch_id
						AND is_installed = par_patch_status
						AND (par_severity_id = -1 OR severity_id = par_severity_id)
						AND (par_group_id = 0 OR group_id = par_group_id)
						AND client_id = var_client_ids_str
						ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, client_master AS b, groups AS c
					WHERE 
					a.client_id = b.client_id
					AND b.GroupId = c.GroupId
					ORDER BY b.computer_name DESC;
				END IF;
				
			ELSEIF var_client_count = -1 THEN
				IF par_patch_status = 0 THEN -- MISSING
					SELECT '1970-01-01' AS incident_date, a.client_id, b.computer_name, b.domain_name, c.GroupName, 
					b.str_ip_address, 0 AS scan_type_id, 0 AS incident_date_in_seconds
					FROM
					(
						SELECT 
						DISTINCT client_id
						FROM rpt_patch_management_fact AS a
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND patch_id = par_patch_id
						AND is_installed = par_patch_status
						AND (par_severity_id = -1 OR severity_id = par_severity_id)
						AND (par_group_id = 0 OR group_id = par_group_id)
						ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, client_master AS b
					WHERE 
					a.client_id = b.client_id
					AND b.GroupId = c.GroupId
					ORDER BY b.computer_name DESC;
				ELSE -- INSTALLED
					SELECT FROM_UNIXTIME(incident_date) AS incident_date, a.client_id, b.computer_name, b.domain_name, c.GroupName, 
					b.str_ip_address, a.scan_type_id, incident_date AS incident_date_in_seconds
					FROM
					(
						SELECT 
						incident_date, client_id, scan_type_id
						FROM rpt_patch_management_fact AS a
						WHERE
						a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
						AND patch_id = par_patch_id
						AND is_installed = par_patch_status
						AND (par_severity_id = -1 OR severity_id = par_severity_id)
						AND (par_group_id = 0 OR group_id = par_group_id)
						ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
					) AS a, client_master AS b
					WHERE 
					a.client_id = b.client_id
					AND b.GroupId = c.GroupId
					ORDER BY b.computer_name DESC;
				END IF;
				
			END IF;
		END IF;
	END IF;
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pm_rpt_get_allrecords_table_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_rpt_get_allrecords_table_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
    IN par_severity_id INT(1),
    IN par_patch_status INT(1),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN         
        SELECT from_unixtime(a.incident_date) AS incident_date, c.computer_name, c.domain_name, a.patch_id, b.patch_title, b.vulnerabilities_targeted, a.severity_id, b.application_name, b.category, a.is_installed, a.scan_type_id, incident_date AS incident_date_in_seconds
			FROM
			(
				SELECT incident_date, patch_id, severity_id, client_id, is_installed, scan_type_id
				FROM rpt_patch_management_fact AS a USE INDEX(idx_incident_date)
				WHERE
				(par_patch_status = -1 OR is_installed = par_patch_status)
				ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
			) AS a, pm_patch_master AS b, client_master c
			WHERE 
			a.patch_id = b.patch_id 
			AND a.client_id = c.client_id
			ORDER BY a.incident_date DESC;
	ELSE
		IF par_client_name='' THEN
			SELECT from_unixtime(a.incident_date) AS incident_date, c.computer_name, c.domain_name, a.patch_id, b.patch_title, b.vulnerabilities_targeted, a.severity_id, b.application_name, b.category, a.is_installed, a.scan_type_id, incident_date AS incident_date_in_seconds
			FROM
			(
				SELECT incident_date, patch_id, severity_id, client_id, is_installed, scan_type_id
				FROM rpt_patch_management_fact AS a USE INDEX(idx_incident_date)
				WHERE
				a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND (par_severity_id = -1 OR severity_id = par_severity_id)
				AND (par_group_id = 0 OR group_id = par_group_id)
				AND (par_patch_status = -1 OR is_installed = par_patch_status)
				ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
			) AS a, pm_patch_master AS b, client_master c
			WHERE 
			a.patch_id = b.patch_id 
			AND a.client_id = c.client_id
			ORDER BY a.incident_date DESC;
		ELSE
			IF par_client_name <> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
			ELSEIF par_client_name <> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
			ELSE
				SET var_client_count = -1;
			END IF;
            
			IF var_client_count > 1 THEN
				SELECT from_unixtime(a.incident_date) AS incident_date, c.computer_name, c.domain_name, a.patch_id, b.patch_title, b.vulnerabilities_targeted, a.severity_id, b.application_name, b.category, a.is_installed, a.scan_type_id, incident_date AS incident_date_in_seconds
				FROM
				(
					SELECT incident_date, patch_id, severity_id, client_id, is_installed, scan_type_id
					FROM rpt_patch_management_fact AS a USE INDEX(idx_incident_date)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_severity_id = -1 OR severity_id = par_severity_id)
					AND (par_group_id = 0 OR group_id = par_group_id)
					AND (par_patch_status = -1 OR is_installed = par_patch_status)
					AND FIND_IN_SET(a.client_id, var_client_ids_str)
					ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
				) AS a, pm_patch_master AS b, client_master c
				WHERE 
				a.patch_id = b.patch_id 
				AND a.client_id = c.client_id
				ORDER BY a.incident_date DESC;
			
			ELSEIF var_client_count = 1 THEN
				SELECT from_unixtime(a.incident_date) AS incident_date, c.computer_name, c.domain_name, a.patch_id, b.patch_title, b.vulnerabilities_targeted, a.severity_id, b.application_name, b.category, a.is_installed, a.scan_type_id, incident_date AS incident_date_in_seconds
				FROM
				(
					SELECT incident_date, patch_id, severity_id, client_id, is_installed, scan_type_id
					FROM rpt_patch_management_fact AS a USE INDEX(idx_incident_date)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_severity_id = -1 OR severity_id = par_severity_id)
					AND (par_group_id = 0 OR group_id = par_group_id)
					AND (par_patch_status = -1 OR is_installed = par_patch_status)
					AND client_id = var_client_ids_str
					ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
				) AS a, pm_patch_master AS b, client_master c
				WHERE 
				a.patch_id = b.patch_id 
				AND a.client_id = c.client_id
				ORDER BY a.incident_date DESC;
				
			ELSEIF var_client_count = -1 THEN
				SELECT from_unixtime(a.incident_date) AS incident_date, c.computer_name, c.domain_name, a.patch_id, b.patch_title, b.vulnerabilities_targeted, a.severity_id, b.application_name, b.category, a.is_installed, a.scan_type_id, incident_date AS incident_date_in_seconds
				FROM
				(
					SELECT incident_date, patch_id, severity_id, client_id, is_installed, scan_type_id
					FROM rpt_patch_management_fact AS a USE INDEX(idx_incident_date)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_severity_id = -1 OR severity_id = par_severity_id)
					AND (par_group_id = 0 OR group_id = par_group_id)
					AND (par_patch_status = -1 OR is_installed = par_patch_status)
					ORDER BY incident_date DESC LIMIT par_start_index,par_max_records
				) AS a, pm_patch_master AS b, client_master c
				WHERE 
				a.patch_id = b.patch_id 
				AND a.client_id = c.client_id
				ORDER BY a.incident_date DESC;
			END IF;
			
		END IF;
	END IF;
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pm_rpt_get_allrecords_count_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_rpt_get_allrecords_count_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
    IN par_severity_id INT(1)
)
BEGIN
	DECLARE var_client_count BIGINT(20) DEFAULT NULL;
	DECLARE var_client_ids_str VARCHAR(2000) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN         

				SELECT IFNULL(SUM(missing_count), 0) AS missing_count, IFNULL(SUM(install_count), 0) AS install_count
				FROM rpt_patch_all_records_summary AS a USE INDEX(idx_incident_date_only);

	ELSE
		IF par_client_name='' THEN
				SELECT IFNULL(SUM(missing_count), 0) AS missing_count, IFNULL(SUM(install_count), 0) AS install_count
				FROM rpt_patch_all_records_summary AS a USE INDEX(idx_incident_date_only)
				WHERE
				a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND (par_severity_id = -1 OR severity_id = par_severity_id)
				AND (par_group_id = 0 OR group_id = par_group_id);
		ELSE
			IF par_client_name <> '' AND par_group_id <> 0 THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE GroupId=par_group_id AND computer_name=par_client_name;
			ELSEIF par_client_name <> '' THEN
				SELECT COUNT(*), GROUP_CONCAT(`client_id` SEPARATOR ',') INTO var_client_count, var_client_ids_str FROM client_master WHERE computer_name=par_client_name;
			ELSE
				SET var_client_count = -1;
			END IF;
            
			IF var_client_count > 1 THEN
				SELECT IFNULL(SUM(missing_count), 0) AS missing_count, IFNULL(SUM(install_count), 0) AS install_count
				FROM rpt_patch_all_records_summary AS a USE INDEX(idx_incident_date_only)
				WHERE
				a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND (par_severity_id = -1 OR severity_id = par_severity_id)
				AND (par_group_id = 0 OR group_id = par_group_id)
                AND FIND_IN_SET(a.client_id, var_client_ids_str);
				
			ELSEIF var_client_count = 1 THEN
				SELECT IFNULL(SUM(missing_count), 0) AS missing_count, IFNULL(SUM(install_count), 0) AS install_count
				FROM rpt_patch_all_records_summary AS a USE INDEX(idx_incident_date_only)
				WHERE
				a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND (par_severity_id = -1 OR severity_id = par_severity_id)
				AND (par_group_id = 0 OR group_id = par_group_id)
                AND client_id = var_client_ids_str;
				
			ELSEIF var_client_count = -1 THEN
				SELECT IFNULL(SUM(missing_count), 0) AS missing_count, IFNULL(SUM(install_count), 0) AS install_count
				FROM rpt_patch_all_records_summary AS a USE INDEX(idx_incident_date_only)
				WHERE
				a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
				AND (par_severity_id = -1 OR severity_id = par_severity_id)
				AND (par_group_id = 0 OR group_id = par_group_id);
				
			END IF;
			
		END IF;
	END IF;
END$$
DELIMITER ;

CREATE TABLE IF NOT EXISTS `rpt_patch_all_records_summary` (
  `rowid` bigint(20) NOT NULL AUTO_INCREMENT,
  `incident_date_only` int(11) DEFAULT NULL,
  `client_id` bigint(11) DEFAULT NULL,
  `group_id` bigint(20) DEFAULT NULL,
  `severity_id` int(11) DEFAULT NULL,
  `missing_count` bigint(11) DEFAULT 0,
  `install_count` bigint(11) DEFAULT 0,
  `md5_match` char(64) DEFAULT NULL,
  PRIMARY KEY (`rowid`),
  KEY `idx_incident_date_only` (`incident_date_only`),
  KEY `idx_client_id` (`client_id`),
  KEY `idx_GroupId` (`group_id`),
  KEY `idx_severity_id` (`severity_id`),
  KEY `idx_md5_match` (`md5_match`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP PROCEDURE IF EXISTS `pm_rpt_get_patch_details_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_rpt_get_patch_details_pr`(
	IN par_patch_id BIGINT(20)
)
BEGIN
	SELECT a.kb_article_no, 
	IFNULL(a.application_name, '') AS application_name, 
	IFNULL(a.application_family, '') AS application_family, 
	IFNULL(a.bulletin_id, '') AS bulletin_id, 
	IFNULL(a.loc_lang, '') AS loc_lang, 
	a.category, a.severity_id,
	IFNULL(a.vulnerabilities_targeted, '') AS vulnerabilities_targeted, 
	IFNULL(a.vendor, '') AS vendor,
	a.max_download_size, a.eula_accepted, 
	IFNULL(a.superseded, '') AS superseded, 
	IFNULL(a.superseding, '') AS superseding, 
	IFNULL(a.ref_links, '') AS ref_links,
	IFNULL(a.patch_title, '') AS patch_title, 
	IFNULL(a.patch_desc, '') AS patch_desc
	
	FROM pm_patch_master AS a
	WHERE a.patch_id = par_patch_id;
END$$
DELIMITER ;


-- Firewall Wi-Fi tables and SPs --
DROP PROCEDURE IF EXISTS wifi_rpt_get_table_pr;
DELIMITER $$
CREATE PROCEDURE `wifi_rpt_get_table_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512),
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN
	DECLARE var_client_id INT(11) DEFAULT NULL;	
	DECLARE var_user_id INT(11) DEFAULT NULL;	
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN 
		SELECT incident_date,
		wifi_name, physical_address, `event`,
		a.client_id, b.computer_name, b.domain_name, c.username, incident_date_in_seconds
		FROM
		(
			SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, 
			wifi_name, physical_address, `event`, incident_date AS incident_date_in_seconds
			FROM rpt_wifi_fact AS a
			ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
		) AS a, client_master AS b, rpt_user_master AS c
		WHERE 
		a.client_id=b.client_id AND a.user_id=c.user_id
		ORDER BY incident_date DESC;
	ELSE
		IF par_username='' THEN
			IF par_client_name='' THEN
				SELECT incident_date,
				wifi_name, physical_address, `event`,
				a.client_id, b.computer_name, b.domain_name, c.username, incident_date_in_seconds
				FROM
				(
					SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, 
					wifi_name, physical_address, `event`, incident_date AS incident_date_in_seconds
					FROM rpt_wifi_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_group_id = 0 OR GroupId = par_group_id)
					ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
				) AS a, client_master AS b, rpt_user_master AS c
				WHERE 
				a.client_id=b.client_id AND a.user_id=c.user_id
				ORDER BY incident_date DESC;
			ELSE
				IF par_client_name <> '' AND par_group_id <> 0 THEN
					SET var_client_id = (SELECT client_id FROM client_master WHERE GroupId = par_group_id AND computer_name = par_client_name LIMIT 1);
				ELSEIF par_client_name <> '' THEN
					SET var_client_id = (SELECT client_id FROM client_master WHERE computer_name = par_client_name LIMIT 1);
				ELSE
					SET var_client_id = -1;
				END IF;			
				
				SELECT incident_date,
				wifi_name, physical_address, `event`,
				a.client_id, b.computer_name, b.domain_name, c.username, incident_date_in_seconds
				FROM
				(
					SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, 
					wifi_name, physical_address, `event`, incident_date AS incident_date_in_seconds
					FROM rpt_wifi_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_group_id = 0 OR GroupId = par_group_id)
					AND client_id = var_client_id
					ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
				) AS a, client_master AS b, rpt_user_master AS c
				WHERE 
				a.client_id=b.client_id AND a.user_id=c.user_id
				ORDER BY incident_date DESC;
			END IF;
		ELSE
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
			IF par_client_name='' THEN
				SELECT incident_date,
				wifi_name, physical_address, `event`,
				a.client_id, b.computer_name, b.domain_name, c.username, incident_date_in_seconds
				FROM
				(
					SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, 
					wifi_name, physical_address, `event`, incident_date AS incident_date_in_seconds
					FROM rpt_wifi_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.user_id=var_user_id
					AND (par_group_id = 0 OR GroupId = par_group_id)
					ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
				) AS a, client_master AS b, rpt_user_master AS c
				WHERE 
				a.client_id=b.client_id AND a.user_id=c.user_id
				ORDER BY incident_date DESC;
			ELSE
				IF par_client_name <> '' AND par_group_id <> 0 THEN
					SET var_client_id = (SELECT client_id FROM client_master WHERE GroupId = par_group_id AND computer_name = par_client_name LIMIT 1);
				ELSEIF par_client_name <> '' THEN
					SET var_client_id = (SELECT client_id FROM client_master WHERE computer_name = par_client_name LIMIT 1);
				ELSE
					SET var_client_id = -1;
				END IF;			
				
				SELECT incident_date,
				wifi_name, physical_address, `event`,
				a.client_id, b.computer_name, b.domain_name, c.username, incident_date_in_seconds
				FROM
				(
					SELECT from_unixtime(incident_date) AS incident_date, client_id, user_id, 
					wifi_name, physical_address, `event`, incident_date AS incident_date_in_seconds
					FROM rpt_wifi_fact AS a USE INDEX(idx_incident_date, idx_client_id, idx_GroupId)
					WHERE
					a.incident_date >= unix_timestamp(par_start_date) AND a.incident_date <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.user_id=var_user_id
					AND (par_group_id = 0 OR GroupId = par_group_id)
					AND client_id = var_client_id
					ORDER BY a.incident_date DESC LIMIT par_start_index,par_max_records
				) AS a, client_master AS b, rpt_user_master AS c
				WHERE 
				a.client_id=b.client_id AND a.user_id=c.user_id
				ORDER BY incident_date DESC;
			END IF;
		END IF;
	END IF;
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS wifi_rpt_get_count_pr;
DELIMITER $$
CREATE PROCEDURE `wifi_rpt_get_count_pr`(
	IN par_start_date DATE,
	IN par_end_date DATE,
	IN par_group_id INT(11),
	IN par_client_name VARCHAR(45),
	IN par_username VARCHAR(512)
)
BEGIN
	DECLARE var_client_id INT(11) DEFAULT NULL;	
	DECLARE var_user_id INT(11) DEFAULT NULL;	
	
	SET time_zone = '+00:00';
	IF (par_start_date IS NULL AND par_end_date IS NULL) OR (par_start_date='1970-01-01' AND par_end_date='1970-01-01') THEN 
		SELECT IFNULL(SUM(incident_count),0) AS record_count FROM rpt_wifi_summary;
	ELSE
		IF par_username='' THEN
			IF par_client_name='' THEN
					SELECT 
					IFNULL(SUM(incident_count),0) AS record_count 
					FROM 
					rpt_wifi_summary AS a USE INDEX(idx_incident_date_only)
					WHERE
					a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_group_id = 0 OR GroupId = par_group_id);
			ELSE
				IF par_client_name <> '' AND par_group_id <> 0 THEN
					SET var_client_id = (SELECT client_id FROM client_master WHERE GroupId = par_group_id AND computer_name = par_client_name LIMIT 1);
				ELSEIF par_client_name <> '' THEN
					SET var_client_id = (SELECT client_id FROM client_master WHERE computer_name = par_client_name LIMIT 1);
				ELSE
					SET var_client_id = -1;
				END IF;
				
					SELECT IFNULL(SUM(incident_count),0) AS record_count
					FROM rpt_wifi_summary AS a USE INDEX(idx_incident_date, idx_client_id)
					WHERE
					a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND (par_group_id = 0 OR GroupId = par_group_id)
					AND client_id = var_client_id;
			END IF;
		ELSE
			SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
			IF par_client_name='' THEN
					SELECT 
					IFNULL(SUM(incident_count),0) AS record_count 
					FROM 
					rpt_wifi_summary AS a USE INDEX(idx_incident_date_only)
					WHERE
					a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.user_id=var_user_id
					AND (par_group_id = 0 OR GroupId = par_group_id);
			ELSE
				IF par_client_name <> '' AND par_group_id <> 0 THEN
					SET var_client_id = (SELECT client_id FROM client_master WHERE GroupId = par_group_id AND computer_name = par_client_name LIMIT 1);
				ELSEIF par_client_name <> '' THEN
					SET var_client_id = (SELECT client_id FROM client_master WHERE computer_name = par_client_name LIMIT 1);
				ELSE
					SET var_client_id = -1;
				END IF;
				
					SELECT IFNULL(SUM(incident_count),0) AS record_count
					FROM rpt_wifi_summary AS a USE INDEX(idx_incident_date, idx_client_id)
					WHERE
					a.incident_date_only >= unix_timestamp(par_start_date) AND a.incident_date_only <= unix_timestamp(par_end_date + interval 1 day - interval 1 second)
					AND a.user_id=var_user_id
					AND (par_group_id = 0 OR GroupId = par_group_id)
					AND client_id = var_client_id;
			END IF;
		END IF;
	END IF;
END$$
DELIMITER ;

CREATE TABLE IF NOT EXISTS `rpt_wifi_fact` (
  `wifi_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `incident_date` int(11) DEFAULT NULL,
  `wifi_name` varchar(512) DEFAULT NULL,
  `physical_address` varchar(40) DEFAULT NULL,
  `event` int(1) DEFAULT NULL,
  `client_id` int(11) DEFAULT NULL,
  `user_id` int(11) DEFAULT NULL,
  `GroupId` int(11) DEFAULT NULL,
  PRIMARY KEY (`wifi_id`),
  KEY `idx_incident_date` (`incident_date`),
  KEY `idx_client_id` (`client_id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_GroupId` (`GroupId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `rpt_wifi_summary` (
  `wifi_summary_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `incident_date_only` int(11) DEFAULT NULL,
  `client_id` int(11) DEFAULT NULL,
  `user_id` int(11) DEFAULT NULL,
  `GroupId` int(11) DEFAULT NULL,
  `incident_count` bigint(20) DEFAULT '0',
  `md5_match` char(64) DEFAULT NULL,
  PRIMARY KEY (`wifi_summary_id`),
  KEY `idx_incident_date_only` (`incident_date_only`),
  KEY `idx_client_id` (`client_id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_GroupId` (`GroupId`),
  KEY `idx_md5_match` (`md5_match`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP PROCEDURE IF EXISTS `pr_insert_firewall_wifi_rpt`;
DELIMITER $$
CREATE PROCEDURE `pr_insert_firewall_wifi_rpt`(
	IN `par_incident_date` INT(11),
	IN `par_wifi_name` VARCHAR(512),
	IN `par_physical_address` VARCHAR(30),
	IN `event` INT(1),
	IN `par_machine_id` varchar(45),
	IN `par_username` varchar(512)
)
BEGIN
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	DECLARE var_GroupId INT(11) DEFAULT NULL;
	DECLARE var_md5 CHAR(64) DEFAULT NULL;
	DECLARE var_matched_id BIGINT(20) DEFAULT NULL;
	DECLARE var_user_id BIGINT(20) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	
	SELECT client_id, GroupId INTO var_client_id, var_GroupId FROM client_master WHERE guid=par_machine_id; 
	SELECT user_id INTO var_user_id FROM rpt_user_master WHERE username=par_username LIMIT 1;
	IF var_user_id IS NULL THEN
		INSERT INTO rpt_user_master(username) VALUES(par_username);
		SET var_user_id = (select last_insert_id());
	END IF;
	IF var_client_id IS NOT NULL THEN
		INSERT INTO `rpt_wifi_fact`(
			`incident_date`,
			`wifi_name`,
			`physical_address`,
			`event`,
			`client_id`,
			`user_id`,
			`GroupId`
		)
		VALUES(
			par_incident_date,
			par_wifi_name,
			par_physical_address,
			event,
			var_client_id,
			var_user_id,
			var_GroupId
		);
		
		SET var_md5 = MD5(CONCAT(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))), var_GroupId, var_client_id, var_user_id));
		
		SET var_matched_id = (SELECT wifi_summary_id FROM rpt_wifi_summary WHERE md5_match=var_md5);
		
		IF var_matched_id IS NOT NULL THEN
			UPDATE rpt_wifi_summary SET incident_count=(incident_count+1) WHERE `wifi_summary_id`=var_matched_id;
		ELSE
			INSERT INTO rpt_wifi_summary(incident_date_only, client_id, user_id, GroupId, md5_match, incident_count) 
			VALUES(unix_timestamp(DATE(FROM_UNIXTIME(par_incident_date))), var_client_id, var_user_id, var_GroupId, var_md5, 1);
		END IF;
		
	END IF;
END $$
DELIMITER ;

-- ================================================
-- +
-- Tables for UPDATE MANAGER  Added by Dhanendra
--

--
-- Table structure for table `um_master`
--
CREATE TABLE IF NOT EXISTS `um_master` (
  `guid` varchar(40) NOT NULL,
  `um_name` varchar(410) DEFAULT '',
  `url` varchar(1050) DEFAULT '',
  `is_added_to_eps` int(11) DEFAULT 0,
  `is_default_um` int(11) DEFAULT 0,
  `is_assoc_client` int(11) DEFAULT 0,
  `valid_details` int(11) DEFAULT 0,
  `is_url_assoc_to_UM` boolean DEFAULT FALSE,
  PRIMARY KEY (`guid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Table structure for table `um_status`
--
CREATE TABLE IF NOT EXISTS `um_status` (
  `guid` varchar(40) NOT NULL,
  `platform_id` int(11) DEFAULT 0,
  `platform_desc` varchar(1050) DEFAULT '',
  `um_type` varchar(260) DEFAULT '',
  `version` varchar(260) DEFAULT '',
  `service_pack` int(11) DEFAULT 0,
  `ob_download` int(11) DEFAULT 0,
  `systime` int(11) DEFAULT 0,
  `platform_download` boolean DEFAULT FALSE,
   FOREIGN KEY (`guid`) REFERENCES `um_master` (`guid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


--
-- Table structure for table `um_settings`
--
CREATE TABLE IF NOT EXISTS `um_settings` (
  `guid` varchar(40) NOT NULL,
  `auto_update` int(11) DEFAULT 0,
  `backup` int(11) DEFAULT 0,
  `del_reports` int(11) DEFAULT 0,
  `del_rpts_after_days` int(11) DEFAULT 0,
  `sp_download` boolean DEFAULT FALSE,
  `is_limited_download_speed` int(11) DEFAULT 0,
  `download_speed_inkB` int(11) DEFAULT 0,
   PRIMARY KEY (`guid`),
   FOREIGN KEY (`guid`) REFERENCES `um_master` (`guid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Table structure for table `um_rollback`
--
CREATE TABLE IF NOT EXISTS `um_rollback` (
  `guid` varchar(40) NOT NULL,
  `platform_id` int(11) DEFAULT 0,
  `platform_desc` varchar(1050) DEFAULT '',
   FOREIGN KEY (`guid`) REFERENCES `um_master` (`guid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `um_scheduler` ( 
    `guid` varchar(40) NOT NULL, 
    `isDefault` int(11) DEFAULT 0,
    `frequency` int(11) DEFAULT 0, 
    `weekDay` int(11) DEFAULT 0,
    `start_hr` int(11) DEFAULT 0,
    `start_min` int(11) DEFAULT 0,
    `IsRepeateUpdate` int(11) DEFAULT 0,
    `repeateDay_hr` int(11) DEFAULT 0, 
    PRIMARY KEY (`guid`),
    FOREIGN KEY (`guid`) REFERENCES um_master (`guid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- - Tables for UPDATE MANAGER  Added by Dhanendra 
-- ===================================================================
-- ===================================================================
-- 14th Apr 2016 :: Added by Dhanendra
-- Tables related to clients, group & policy are added here from qhacdb module.
-- +
CREATE TABLE IF NOT EXISTS policy (
	PolicyId integer PRIMARY KEY NOT NULL,
	PolicyName varchar(1040) NOT NULL,
	GUID varchar(40) NOT NULL
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS groups (
	GroupId integer PRIMARY KEY NOT NULL,
	ParentGrpId integer,
	PolicyId integer NOT NULL,
	GroupName varchar(1040) NOT NULL,
	GroupGUID varchar(40) UNIQUE NOT NULL,
	FOREIGN KEY( PolicyId ) REFERENCES policy(PolicyId)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS acsync (
	GroupId integer PRIMARY KEY NOT NULL,
	DomainName varchar(1050),
	AdsPath TEXT,
	SyncInterval integer,
	Username blob,
	Password blob,
	Reserved blob,
	FOREIGN KEY( GroupId ) REFERENCES groups(GroupId)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS clntsync (
	guid varchar(40) PRIMARY KEY NOT NULL,
	ComputerName varchar(1050) NOT NULL,
	GroupId integer,
	Reserved blob,
	FOREIGN KEY( GroupId ) REFERENCES groups(GroupId)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS client_master (
	client_id bigint PRIMARY KEY NOT NULL AUTO_INCREMENT,
	guid varchar(40) UNIQUE NOT NULL,
	client_inst_netwk integer(1) NOT NULL,
	computer_name varchar(1050) NOT NULL,
	domain_name varchar(1050) NOT NULL,
	username blob,
	ip_address integer,
	ip_v6_address TEXT,
	client_type integer,
	client_port integer,
	client_status integer,
	connection_time integer,
	info_time integer,
	exclusion integer,
	offline_task bigint(21) unsigned,
	GroupId integer,
	version blob,
	ip_address_from_client integer,
	macid1 varchar(18),
	macid2 varchar(18),
	macid3 varchar(18),
	boot_scan_mode integer,
	roaming_client integer,
	rp_state_id blob,
	is_roaming_state integer,
	rp_connection_time integer,
	ip_add_from_rp_client integer,
	policy_status integer,
	clnt_special_sp_version blob,
	clnt_disconnected_on integer,
	str_ip_address varchar(20),
	isdlplicense tinyint(1),
	KEY idx_computer_name(computer_name),
	KEY idx_group_id(GroupId),
	FOREIGN KEY( GroupId ) REFERENCES groups(GroupId)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS clientav (
	guid varchar(40) PRIMARY KEY NOT NULL,
	InstallationStatus integer,
	InstallerLog varchar(20),
	ProductName varchar(1050),
	ProductVersion blob,
	InstallationDate integer,
	VdbDate integer,
	LastScanDate integer,
	LastTuneUpDate integer,
	ModuleStatus integer,
	SettingFilename varchar(20),
	LogFilename varchar(20),
	PrevVirusCount integer,
	NewVirusCount integer,
	AV_Reserved blob,
	LastVulnerabilityScanDate integer,
	PostInstallAction integer,
	FOREIGN KEY( guid ) REFERENCES client_master(guid)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS clientos (
	guid varchar(40) PRIMARY KEY NOT NULL,
	OsPlatform integer,
	OsVersion varchar(1050),
	VersionStruct blob,
	SystemDate integer,
	Locale integer,
	Language integer,
	MailClient varchar(1050),
	MailClientVersion blob,
	Browser varchar(1050),
	BrowserVersion blob,
	OS_Reserved blob,
	OsID integer,
	is_server_os integer,
	FOREIGN KEY( guid ) REFERENCES client_master(guid) 
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS RpClients (
	guid varchar(40) PRIMARY KEY NOT NULL,
	client_inst_netwk integer(1) NOT NULL,
	computer_name varchar(1050),
	domain_name varchar(1050),
	username blob,
	ip_address integer,
	ip_v6_address TEXT,
	client_type integer,
	client_port integer,
	client_status integer,
	connection_time integer,
	info_time integer,
	exclusion integer,
	offline_task bigint(21) unsigned,
	GroupId integer,
	version blob,
	ip_address_from_client integer,
	macid1 varchar(18),
	macid2 varchar(18),
	macid3 varchar(18),
	boot_scan_mode integer,
	roaming_client integer,
	rp_state_id blob,
	is_roaming_state integer,
	rp_connection_time integer,
	ip_add_from_rp_client integer,
	policy_status integer,
	clnt_special_sp_version blob,
	clnt_disconnected_on integer,
	str_ip_address varchar(20),
	isdlplicense tinyint(1)	
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS RpClientav (
	guid varchar(40) PRIMARY KEY NOT NULL,
	InstallationStatus integer,
	InstallerLog varchar(20),
	ProductName varchar(1050),
	ProductVersion blob,
	InstallationDate integer,
	VdbDate integer,
	LastScanDate integer,
	LastTuneUpDate integer,
	ModuleStatus integer,
	SettingFilename varchar(20),
	LogFilename varchar(20),
	PrevVirusCount integer,
	NewVirusCount integer,
	AV_Reserved blob,
	LastVulnerabilityScanDate integer,
	PostInstallAction integer
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS RpClientos (
	guid varchar(40) PRIMARY KEY NOT NULL,
	OsPlatform integer,
	OsVersion varchar(1050),
	VersionStruct blob,
	SystemDate integer,
	Locale integer,
	Language integer,
	MailClient varchar(1050),
	MailClientVersion blob,
	Browser varchar(1050),
	BrowserVersion blob,
	OS_Reserved blob,
	OsID integer,
	is_server_os integer
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS epsStatOsInfo (
	OsVersion varchar(1050) NOT NULL,
	IsUpdating integer NOT NULL,
	UNIQUE KEY ( OsVersion(255)) 
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS client_action_Info (
	guid varchar(40) PRIMARY KEY NOT NULL,
	scan_status integer,
	scan_notification_time integer,
	update_status integer,
	update_notification_time integer,
	tuneup_status integer,
	tuneup_notification_time integer,
	appctrl_status integer,
	appctrl_notification_time integer,
	vulscan_status integer,
	vulscan_notification_time integer,
	dar_status integer,
	dar_notification_time integer,
	patchscan_status integer,
	patchscan_notification_time integer,
	rmuninst_status integer,
	rmuninst_notification_time integer,	
	FOREIGN KEY( guid ) REFERENCES client_master(guid)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS RpClientData (
	ClientGUID varchar(40) NOT NULL,
	DataId integer NOT NULL,
	DataType integer NOT NULL,
	Data blob
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS ADExclusion (
	ExclusionType integer NOT NULL,
	HostOrIPAddress blob NOT NULL,
	IPAddress2 varchar(16)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS rminst_clients (
	client_id bigint PRIMARY KEY NOT NULL AUTO_INCREMENT,
	machine_name varchar(1050) NOT NULL,
	domain_name varchar(1050),
	updated_time integer,
	install_status integer,
	install_error_code integer,
	ad_sync_clients integer,
	GroupId integer,
	ip_address integer
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS rminst_credentials (
	cred_id bigint PRIMARY KEY NOT NULL AUTO_INCREMENT,
	username varchar(1050) NOT NULL,
	password varchar(1050)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS rminst_credential_map (
	client_id bigint,
	cred_id bigint,
	FOREIGN KEY( client_id ) REFERENCES rminst_clients(client_id),
	FOREIGN KEY( cred_id ) REFERENCES rminst_credentials(cred_id)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS feature_lic_info (
	dlp_license_count int(11) DEFAULT 0 
) ENGINE=InnoDB;

-- - Tables related to clients, group & policy are added here from qhacdb module.
-- ===================================================================


DROP PROCEDURE IF EXISTS `pm_rpt_get_daywise_patch_info_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_rpt_get_daywise_patch_info_pr`(
)
BEGIN

	DECLARE var_last_sent_date INT(11) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	
	SET var_last_sent_date = (SELECT unix_timestamp(date(from_unixtime(last_sent_date))) FROM cloud_status LIMIT 1);
	
	SELECT incident_date_only AS 'incident_date', SUM(missing_count) AS 'missing_count', SUM(install_count) AS 'install_count'
	FROM rpt_patch_clientwise_summary
	WHERE
	incident_date_only >= var_last_sent_date
	AND incident_date_only < unix_timestamp(GetCurrentDate() + interval 1 day)
	GROUP BY incident_date;
	 		
	 
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS dash_security_vulnscan_get_severity_chart_pr;
DELIMITER $$
CREATE PROCEDURE dash_security_vulnscan_get_severity_chart_pr(
IN par_no_of_days INT(11)
)
BEGIN

	DECLARE var_total_cnt INT(11) DEFAULT NULL;
	
	SET time_zone = '+00:00';
	
	SET var_total_cnt = (SELECT SUM(count) AS cnt FROM vulnscan_optm_summary);
	
	select severity, ROUND(SUM(count)/var_total_cnt*100) AS cnt 
	FROM vulnscan_optm_summary 
	WHERE incident_date >= unix_timestamp(GetCurrentDate() - INTERVAL par_no_of_days DAY)
	AND incident_date < unix_timestamp(GetCurrentDate() + INTERVAL 1 DAY)
	GROUP BY severity;
	
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pm_get_not_downloaded_patches_for_autodownload_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_get_not_downloaded_patches_for_autodownload_pr`(
	IN `par_client_guid` VARCHAR(40),
	IN `par_scan_type` INT(11),
	IN `par_severity_id` INT(11)
)
BEGIN
	DECLARE var_client_id BIGINT(20) DEFAULT NULL;
	SELECT client_id INTO var_client_id FROM client_master WHERE guid=par_client_guid;
	
	IF par_severity_id = 4 THEN -- [4 = Unspecified Severity]
		SELECT c.patch_guid, c.patch_revision, a.pmserver_id
		FROM pm_patch_scan_fact AS a, pm_patch_download_status_dim AS b, pm_patch_master AS c
		WHERE a.patch_id = b.patch_id AND a.patch_id = c.patch_id
		AND a.client_id = var_client_id
		AND a.scan_type = par_scan_type
		AND b.download_status = FALSE
		AND a.installation_status <> 2; -- skip 'download notification sent' patches.
	ELSE
		SELECT c.patch_guid, c.patch_revision, a.pmserver_id
		FROM pm_patch_scan_fact AS a, pm_patch_download_status_dim AS b, pm_patch_master AS c
		WHERE a.patch_id = b.patch_id AND a.patch_id = c.patch_id
		AND a.client_id = var_client_id
		AND a.scan_type = par_scan_type	
		AND c.severity_id >= par_severity_id
		AND b.download_status = FALSE
		AND a.installation_status <> 2; -- skip 'download notification sent' patches.
	END IF;
	
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS `pm_delete_patchscan_data_of_uninstalled_pms_pr`;
DELIMITER $$
CREATE PROCEDURE `pm_delete_patchscan_data_of_uninstalled_pms_pr`(
	IN par_pmserver_guid CHAR(40)
)
BEGIN
	
	DELETE 
	FROM pm_patch_scan_fact
	WHERE pmserver_id = par_pmserver_guid;
	
	DELETE 
	FROM pm_patch_download_status_dim
	WHERE pmserver_id = par_pmserver_guid;
	
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS clnt_set_offline_task;
DELIMITER $$
	CREATE PROCEDURE clnt_set_offline_task(
		IN par_guids text,
		IN par_int_offline_bit_value INT(11)
)
BEGIN
	UPDATE client_master set offline_task = offline_task|par_int_offline_bit_value, isdlplicense = 0 where FIND_IN_SET(guid, par_guids); 
	SELECT computer_name, guid FROM client_master where FIND_IN_SET(guid, par_guids);
END$$
DELIMITER ;

-- Current Assets Changes
DROP PROCEDURE IF EXISTS assets_current_assets_rpt_get_table_pr;
DELIMITER $$
CREATE PROCEDURE `assets_current_assets_rpt_get_table_pr`(
	IN par_osplatform_id INT(11),
	IN par_os_id INT(11),
	IN par_application_name VARCHAR(256),
	IN par_sys_manufacturer VARCHAR(256),
	IN par_ram BIGINT(20),
	IN par_processor VARCHAR(256),
	IN par_last_shutdown DATE,
	IN par_start_index INT(11),
	IN par_max_records INT(11)
)
BEGIN
	DECLARE var_client_id INT(11) DEFAULT NULL;	
	
	SET time_zone = '+00:00';
	IF (par_osplatform_id = -1 AND par_os_id = -1 AND par_application_name = '' AND par_sys_manufacturer = '' AND par_ram = -1 AND par_processor = '' AND par_last_shutdown = '1970-01-01') THEN 
		SELECT client_id, computer_name, domain_name, str_ip_address
		FROM client_master
		ORDER BY client_id;
	ELSE
		IF par_application_name = '' THEN
			IF par_ram <> 9 THEN
				SELECT b.client_id, b.computer_name, b.domain_name, b.str_ip_address,
				IFNULL(a.OSName, '') AS OSName, IFNULL(SystemManufacturer, '') AS SystemManufacturer, IFNULL(ProcessorName, '') AS ProcessorName, FROM_UNIXTIME(IFNULL(SystemLastShutDownTime, 0)) AS SystemLastShutDownTime, ROUND(IFNULL(PhysicalMemorySize, 0) / 1073741824, 2) AS PhysicalRam
				FROM sysinfo AS a, client_master AS b
				WHERE
				a.ClientGuid = b.guid AND b.client_status & 8 <> 8
				AND(par_osplatform_id = -1 OR PlatformID = par_osplatform_id)
				AND(par_os_id = -1 OR OSID = par_os_id)
				AND(par_sys_manufacturer = '' OR SystemManufacturer = par_sys_manufacturer)
				AND(par_ram = -1 OR CEIL(PhysicalMemorySize / 1073741824) <= par_ram)
				AND(par_processor = '' OR ProcessorName = par_processor)
				AND SystemLastShutDownTime <= UNIX_TIMESTAMP(par_last_shutdown + INTERVAL 1 DAY - INTERVAL 1 SECOND)
				ORDER BY b.computer_name LIMIT par_start_index,par_max_records;
			ELSE
				SELECT b.client_id, b.computer_name, b.domain_name, b.str_ip_address,
				IFNULL(a.OSName, '') AS OSName, IFNULL(SystemManufacturer, '') AS SystemManufacturer, IFNULL(ProcessorName, '') AS ProcessorName, FROM_UNIXTIME(IFNULL(SystemLastShutDownTime, 0)) AS SystemLastShutDownTime, ROUND(IFNULL(PhysicalMemorySize, 0) / 1073741824, 2) AS PhysicalRam
				FROM sysinfo AS a, client_master AS b
				WHERE
				a.ClientGuid = b.guid AND b.client_status & 8 <> 8
				AND(par_osplatform_id = -1 OR PlatformID = par_osplatform_id)
				AND(par_os_id = -1 OR OSID = par_os_id)
				AND(par_sys_manufacturer = '' OR SystemManufacturer = par_sys_manufacturer)
				AND CEIL(PhysicalMemorySize / 1073741824) >= par_ram
				AND(par_processor = '' OR ProcessorName = par_processor)
				AND SystemLastShutDownTime <= UNIX_TIMESTAMP(par_last_shutdown + INTERVAL 1 DAY - INTERVAL 1 SECOND)
				ORDER BY b.computer_name LIMIT par_start_index,par_max_records;
			END IF;
			
		ELSE
			IF par_ram <> 9 THEN
				SELECT b.client_id, b.computer_name, b.domain_name, b.str_ip_address,
				IFNULL(a.OSName, '') AS OSName, IFNULL(SystemManufacturer, '') AS SystemManufacturer, IFNULL(ProcessorName, '') AS ProcessorName, FROM_UNIXTIME(IFNULL(SystemLastShutDownTime, 0)) AS SystemLastShutDownTime, ROUND(IFNULL(PhysicalMemorySize, 0) / 1073741824, 2) AS PhysicalRam
				FROM sysinfo AS a, client_master AS b, installed_programs AS c
				WHERE
				a.ClientGuid = b.guid AND a.ClientGuid = c.ClientGuid AND b.client_status & 8 <> 8
				AND(par_osplatform_id = -1 OR PlatformID = par_osplatform_id)
				AND(par_os_id = -1 OR OSID = par_os_id)
				AND(par_sys_manufacturer = '' OR SystemManufacturer = par_sys_manufacturer)
				AND(par_ram = -1 OR CEIL(PhysicalMemorySize / 1073741824) <= par_ram)
				AND(par_processor = '' OR ProcessorName = par_processor)
				AND SystemLastShutDownTime <= UNIX_TIMESTAMP(par_last_shutdown + INTERVAL 1 DAY - INTERVAL 1 SECOND)
				AND(par_application_name = '' OR c.Name = par_application_name)
				ORDER BY b.computer_name LIMIT par_start_index,par_max_records;
			ELSE
				SELECT b.client_id, b.computer_name, b.domain_name, b.str_ip_address,
				IFNULL(a.OSName, '') AS OSName, IFNULL(SystemManufacturer, '') AS SystemManufacturer, IFNULL(ProcessorName, '') AS ProcessorName, FROM_UNIXTIME(IFNULL(SystemLastShutDownTime, 0)) AS SystemLastShutDownTime, ROUND(IFNULL(PhysicalMemorySize, 0) / 1073741824, 2) AS PhysicalRam
				FROM sysinfo AS a, client_master AS b, installed_programs AS c
				WHERE
				a.ClientGuid = b.guid AND a.ClientGuid = c.ClientGuid AND b.client_status & 8 <> 8
				AND(par_osplatform_id = -1 OR PlatformID = par_osplatform_id)
				AND(par_os_id = -1 OR OSID = par_os_id)
				AND(par_sys_manufacturer = '' OR SystemManufacturer = par_sys_manufacturer)
				AND CEIL(PhysicalMemorySize / 1073741824) >= par_ram
				AND(par_processor = '' OR ProcessorName = par_processor)
				AND SystemLastShutDownTime <= UNIX_TIMESTAMP(par_last_shutdown + INTERVAL 1 DAY - INTERVAL 1 SECOND)
				AND(par_application_name = '' OR c.Name = par_application_name)
				ORDER BY b.computer_name LIMIT par_start_index,par_max_records;
			END IF;
		END IF;
	END IF;
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS assets_current_assets_rpt_get_count_pr;
DELIMITER $$
CREATE PROCEDURE `assets_current_assets_rpt_get_count_pr`(
	IN par_osplatform_id INT(11),
	IN par_os_id INT(11),
	IN par_application_name VARCHAR(256),
	IN par_sys_manufacturer VARCHAR(256),
	IN par_ram BIGINT(20),
	IN par_processor VARCHAR(256),
	IN par_last_shutdown DATE
)
BEGIN
	DECLARE var_client_id INT(11) DEFAULT NULL;	
	
	SET time_zone = '+00:00';
	IF (par_osplatform_id = -1 AND par_os_id = -1 AND par_application_name = '' AND par_sys_manufacturer = '' AND par_ram = -1 AND par_processor = '' AND par_last_shutdown = '1970-01-01') THEN 
		SELECT IFNULL(COUNT(*),0) AS record_count
		FROM client_master
		ORDER BY client_id;
	ELSE
		IF par_application_name = '' THEN
			IF par_ram <> 9 THEN
				SELECT IFNULL(COUNT(*),0) AS record_count
				FROM sysinfo AS a, client_master AS c 
				WHERE
				a.ClientGuid = c.guid AND c.client_status & 8 <> 8
				AND(par_osplatform_id = -1 OR PlatformID = par_osplatform_id)
				AND(par_os_id = -1 OR OSID = par_os_id)
				AND(par_sys_manufacturer = '' OR SystemManufacturer = par_sys_manufacturer)
				AND(par_ram = -1 OR CEIL(PhysicalMemorySize / 1073741824) <= par_ram)
				AND(par_processor = '' OR ProcessorName = par_processor)
				AND SystemLastShutDownTime <= UNIX_TIMESTAMP(par_last_shutdown + INTERVAL 1 DAY - INTERVAL 1 SECOND);
			ELSE
				SELECT IFNULL(COUNT(*),0) AS record_count
				FROM sysinfo AS a, client_master AS c 
				WHERE 
				a.ClientGuid = c.guid AND c.client_status & 8 <> 8
				AND (par_osplatform_id = -1 OR PlatformID = par_osplatform_id)
				AND(par_os_id = -1 OR OSID = par_os_id)
				AND(par_sys_manufacturer = '' OR SystemManufacturer = par_sys_manufacturer)
				AND CEIL(PhysicalMemorySize / 1073741824) >= par_ram
				AND(par_processor = '' OR ProcessorName = par_processor)
				AND SystemLastShutDownTime <= UNIX_TIMESTAMP(par_last_shutdown + INTERVAL 1 DAY - INTERVAL 1 SECOND);
			END IF;
			
		ELSE
			IF par_ram <> 9 THEN
				SELECT IFNULL(COUNT(*),0) AS record_count
				FROM sysinfo AS a, installed_programs AS b, client_master AS c 
				WHERE				
				a.ClientGuid = b.ClientGuid AND c.client_status & 8 <> 8
				AND a.ClientGuid = c.guid
				AND(par_osplatform_id = -1 OR PlatformID = par_osplatform_id)
				AND(par_os_id = -1 OR OSID = par_os_id)
				AND(par_sys_manufacturer = '' OR SystemManufacturer = par_sys_manufacturer)
				AND(par_ram = -1 OR CEIL(PhysicalMemorySize / 1073741824) <= par_ram)
				AND(par_processor = '' OR ProcessorName = par_processor)
				AND SystemLastShutDownTime <= UNIX_TIMESTAMP(par_last_shutdown + INTERVAL 1 DAY - INTERVAL 1 SECOND)
				AND(par_application_name = '' OR b.Name = par_application_name);
			ELSE
				SELECT IFNULL(COUNT(*), 0) AS record_count
				FROM sysinfo AS a, installed_programs AS b, client_master AS c 
				WHERE
				a.ClientGuid = b.ClientGuid AND c.client_status & 8 <> 8
				AND a.ClientGuid = c.guid
				AND(par_osplatform_id = -1 OR PlatformID = par_osplatform_id)
				AND(par_os_id = -1 OR OSID = par_os_id)
				AND(par_sys_manufacturer = '' OR SystemManufacturer = par_sys_manufacturer)
				AND CEIL(PhysicalMemorySize / 1073741824) >= par_ram
				AND(par_processor = '' OR ProcessorName = par_processor)
				AND SystemLastShutDownTime <= UNIX_TIMESTAMP(par_last_shutdown + INTERVAL 1 DAY - INTERVAL 1 SECOND)
				AND(par_application_name = '' OR b.Name = par_application_name);
			END IF;
		END IF;
	END IF;
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS add_dlp_feature_to_client_pr;
DELIMITER $$
CREATE PROCEDURE add_dlp_feature_to_client_pr(
	IN par_client_ids_str VARCHAR(2000),
	IN par_clients_count INT(11)
)
BEGIN
	DECLARE var_total_dlp_license INT(11) DEFAULT 0;
	DECLARE var_consumed_dlp_license INT(11) DEFAULT 0;
	
	SET var_total_dlp_license = (SELECT dlp_license_count FROM feature_lic_info);
	SET var_consumed_dlp_license = (SELECT IFNULL(COUNT(*),0) FROM client_master WHERE client_status & 8 <> 8 AND isdlplicense = 1 AND NOT FIND_IN_SET(client_id, par_client_ids_str));	
	
	IF (var_consumed_dlp_license + par_clients_count) <= var_total_dlp_license THEN
		UPDATE client_master 
		SET isdlplicense = 1
		WHERE FIND_IN_SET(client_id, par_client_ids_str);
		
		select 1 As response;
	ELSE
		select 0 As response;	-- License limit exceeded.
	END IF;
	
END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS select_dlp_feature_status;
DELIMITER $$
	CREATE PROCEDURE select_dlp_feature_status(
		IN par_lic_count INT(11)
)
BEGIN

	SELECT guid 
	FROM client_master 
	WHERE 
	isdlplicense = 1 AND (client_status & 8 != 8)
	AND guid NOT IN(
		SELECT * 
		FROM (
			SELECT guid 
			FROM client_master
			WHERE isdlplicense = 1 AND (client_status & 8 != 8)
			LIMIT par_lic_count
		) AS temp
	);

END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS update_dlp_feature_status;
DELIMITER $$
	CREATE PROCEDURE update_dlp_feature_status(
		IN par_lic_count INT(11)
)
BEGIN
	UPDATE client_master
	SET isdlplicense=0 
	WHERE guid NOT IN (
		SELECT * FROM (
			SELECT guid FROM client_master WHERE isdlplicense=1 AND (client_status & 4 != 4 ) AND (client_status & 8 != 8) LIMIT par_lic_count
			)
			AS dlp_clnts);

END$$
DELIMITER ;

DROP PROCEDURE IF EXISTS pm_all_reset_patch_download_status;
DELIMITER $$
	CREATE PROCEDURE pm_all_reset_patch_download_status(
)
BEGIN
	UPDATE pm_patch_download_status_dim
	SET download_status=0 WHERE download_status=1;

END$$
DELIMITER ;

--
-- Table structure for table `rpt_user_master`
--
CREATE TABLE IF NOT EXISTS `rpt_user_master` (
  `user_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(512) NOT NULL,
  PRIMARY KEY (`user_id`),
  KEY idx_username(`username`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

-- ================================================
-- + Table to check EPS DB creation status
-- DO NOT PUT ANY CODE UNDER THIS TABLE --

CREATE TABLE IF NOT EXISTS `check_eps_db_creation_status` (
  `creation_status` int(11) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- - Table to check EPS DB creation status 
-- ================================================
-- DO NOT PUT ANY CODE UNDER THIS TABLE ---