				SELECT Message;
				CALL hrm_message('1104001', 'National', 'create', NationalsName);
			END IF;
		ELSE
			IF Showing = 1 THEN
				SET Message = "exist";
				SELECT Message;
				CALL hrm_message('1104004', 'National', 'exist', NationalsName);
			END IF;
		END IF;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeePosition`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeePosition`(userid varchar(255),positionID varchar(255),positionName varchar(255), positionLevel varchar(255),position text)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE CheckExist2 INT DEFAULT(0);
	

	IF position != "" THEN
		SELECT COUNT(*) INTO CheckExist FROM ame_mt_pos p WHERE LOWER(p.var_id) = positionID;
		IF CheckExist <= 0 THEN
			SELECT COUNT(*) INTO CheckExist2 FROM ame_mt_pos p WHERE LOWER(p.var_name) = positionName AND p.int_level = positionLevel;
		END IF;
		
		IF CheckExist <= 0 AND CheckExist2 <= 0 THEN

			SET @SQL1 = CONCAT("INSERT INTO ame_mt_pos(var_id, var_name,var_addr,int_level,var_description) VALUES ", position, ";");
		
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'EmployeePosition', positionID);
			
			SET ID = positionName;
			SELECT ID;
			CALL hrm_message('1102901', 'Position', 'create', positionID);

		ELSEIF CheckExist > 0 THEN
			SET ID = "exist";
			SELECT ID;
			CALL hrm_message('1102906', 'Position', 'exist', positionID);

		ELSEIF CheckExist2 > 0 THEN
			SET ID = "exist";
			SELECT ID;
			CALL hrm_message_param3('1102904', 'Position', 'exist', positionName, positionLevel, '');
		END IF;
	
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeSchool`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeSchool`(userid varchar(255),SchoolName varchar(255),School text, Showing int(1))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	
	IF School != "" THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_emp_school WHERE LOWER(School_Name) = SchoolName;

		IF CheckExist <= 0 THEN
			
			SET @SQL1 = CONCAT("INSERT INTO hrm_emp_school(School_Name) VALUES ", School, ";");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'EmployeeSchool', SchoolName);
			
			IF Showing = 1 THEN
				SET Message = "success";
				SELECT Message;
				CALL hrm_message('1104101', 'School', 'create', SchoolName);
			END IF;
		ELSE
			IF Showing = 1 THEN
				SET Message = "exist";
				SELECT Message;
				CALL hrm_message('1104104', 'School', 'exist', SchoolName);
			END IF;
		END IF;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeSocialCommunication`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeSocialCommunication`(userid varchar(255),SCName varchar(255),SC text, Showing int(1))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	
	IF SC != "" THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_emp_social_communication WHERE LOWER(SocialCommunication_Name) = SCName;

		IF CheckExist <= 0 THEN
			
			SET @SQL1 = CONCAT("INSERT INTO hrm_emp_social_communication(SocialCommunication_Name) VALUES ", SC, ";");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'EmployeeSocialCommunication', SCName);

			IF Showing = 1 THEN 
				SET Message = "success";
				SELECT Message;
				CALL hrm_message('1103801', 'SocialCommunication', 'create', SCName);
			END IF;
		ELSE
			IF Showing = 1 THEN
				SET Message = "exist";
				SELECT Message;
				CALL hrm_message('1103804', 'SocialCommunication', 'exist', SCName);
			END IF;
		END IF;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeStatus`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeStatus`(userid varchar(255),statusName varchar(255),statuss text, Showing int(1))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	
	IF statuss != "" THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_emp_status WHERE LOWER(Status_Name) = statusName;

		IF CheckExist <= 0 THEN
			
			SET @SQL1 = CONCAT("INSERT INTO hrm_emp_status(Status_Name) VALUES ", statuss, ";");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'EmployeeStatus', StatusName);

			IF Showing = 1 THEN
				SET Message = "success";
				SELECT Message;
				CALL hrm_message('1103001', 'Status', 'create', StatusName);
			END IF;
		ELSE
			IF Showing = 1 THEN
				SET Message = "exist";
				SELECT Message;
				CALL hrm_message('1103004', 'Status', 'exist', StatusName);
			END IF;
		END IF;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddEmployeeType`;
DELIMITER |
CREATE PROCEDURE `spHRMAddEmployeeType`(userid varchar(255),typeName varchar(255),type text, Showing int(1))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	
	IF type != "" THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_emp_type WHERE LOWER(Type_Name) = typeName;

		IF CheckExist <= 0 THEN

			SET @SQL1 = CONCAT("INSERT INTO hrm_emp_type(Type_Name) VALUES ", type, ";");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'EmployeeType', typeName);

			IF Showing = 1 THEN
				SET Message = "success";
				SELECT Message;
				CALL hrm_message('1103101', 'Type', 'create', TypeName);
			END IF;
		ELSE
			IF Showing = 1 THEN
				SET Message = "exist";
				SELECT Message;
				CALL hrm_message('1103104', 'Type', 'exist', TypeName);
			END IF;
		END IF;
	
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddFingerPrint`;
DELIMITER |
CREATE PROCEDURE `spHRMAddFingerPrint`(userid varchar(255), SFileName varchar(255), SValue longtext)
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);

	IF SValue != "" THEN	
	
				SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_fingerprint(FP_ID,FP_Date,FP_Punch1,FP_Punch2,FP_Punch3,FP_Punch4,FP_Punch5,FP_Punch6,FP_Punch7,FP_Punch8,FP_Punch9,FP_Punch10) VALUES ", SValue, ";");
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'import', 'Attendance', SFileName);
				
				SET Message = "success";
				SELECT Message;
				CALL hrm_message('1102101', 'Attendance', 'create', SFileName);

	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddFormPer`;
DELIMITER |
CREATE PROCEDURE `spHRMAddFormPer`(UID varchar(255))
    DETERMINISTIC
BEGIN
DECLARE v_finished INTEGER DEFAULT 0;
DECLARE SysName varchar(255) DEFAULT "";
DEClARE LocationID_Cursor CURSOR FOR
SELECT FrmSysName FROM hrm_userpermission U WHERE U.UID = 'ADMIN';
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET v_finished = 1;
OPEN LocationID_Cursor;
GetLocationID: LOOP
FETCH LocationID_Cursor INTO SysName;
IF v_finished = 1 THEN
LEAVE GetLocationID;
END IF;
INSERT INTO hrm_userpermission VALUES(UID,SysName,0,0,0,0,0,0);
END LOOP GetLocationID;
CLOSE LocationID_Cursor;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddGAuthorisationApproved`;
DELIMITER |
CREATE PROCEDURE `spHRMAddGAuthorisationApproved`(IN AuthID varchar(255),IN ProcessID varchar(255),IN ProcessName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE done INT DEFAULT FALSE;
	DECLARE AuthEmpID VARCHAR(255);
	DECLARE AuthGroupID VARCHAR(255);
	DECLARE SNow DATE;
	DECLARE SNowTime DATETIME;
	DECLARE tz VARCHAR(20) DEFAULT('');
	DECLARE ComName VARCHAR(255) DEFAULT('');
	DECLARE EmpName VARCHAR(255) DEFAULT('');
	DECLARE EmpSalutation VARCHAR(255) DEFAULT('');
	DECLARE UID VARCHAR(255) DEFAULT('');
	DECLARE Email VARCHAR(255) DEFAULT('');

	DECLARE cur1 CURSOR FOR SELECT a.Auth_GroupID, AuthGroup_EmpID, e.var_id, e.var_hrm_salutation, u.var_id, e.var_hrm_company_email FROM hrm_authorisation_detail a LEFT JOIN hrm_authorisation_group_detail g ON(g.AuthGroup_ID = a.Auth_GroupID) LEFT JOIN ame_mt_emp e ON(AuthGroup_EmpID = e.var_id) LEFT JOIN ame_user u ON(u.var_empid = AuthGroup_EmpID) WHERE a.Auth_ID = AuthID;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	SELECT Setting_Value INTO ComName FROM hrm_setting WHERE Setting_Type = 'Company' AND Setting_Name = 'Name';

	SELECT Setting_Value INTO tz FROM hrm_setting WHERE Setting_Type = 'TimeZone' AND Setting_Name = 'TimeZone';
	SET SNow = convert_tz(now(), @@session.time_zone, tz);

	SET SNowTime = convert_tz(now(), @@session.time_zone, tz);

	OPEN cur1;
	read_loop: LOOP
    FETCH cur1 INTO AuthGroupID, AuthEmpID, EmpName, EmpSalutation, UID, Email;
    IF done THEN
      LEAVE read_loop;
    END IF;
		IF !ISNULL(AuthEmpID) THEN
			INSERT INTO hrm_authorisation_approved(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_GroupID,Auth_EmpID,Auth_Status,Auth_Date) VALUES (ProcessID, ProcessName, AuthID, AuthGroupID, AuthEmpID, 'requested', SNow);
		
			IF LOWER(ProcessName) = "dayoff" THEN
				INSERT INTO hrm_notification(noti_userid,noti_subject,noti_body,noti_url,noti_email,noti_email_subject,noti_email_body) VALUES(UID, ComName, CONCAT("Hello, " , EmpSalutation , " ", EmpName, ".\nThere's a new dayoff request that need you to approve."), "/auth/authapprove", Email, "Approval Dayoff Request", CONCAT("Company\t\t\t: <b>", ComName, "</b><br><br>Objective\t\t:Approval Dayoff Request<br><br>Transaction\t\t\t: ", ProcessID, "<br><br><br><br><br>Dear ", EmpSalutation, " ", EmpName, "<br><br><br><br><br>On ", DATE_FORMAT(SNowTime, "%W, %M %e, %Y %h:%i %p"), ", The dayoff request has been created with Transaction ID <b>", ProcessID, "</b> that need you to approve on this request.<br><br><br><br><br>Thank you for using Balancika HRM, if you need further assistance, please contact our support team at support@balancikacambodia.com.<br><br><br><br><br>Best regard,<br><br>Balancika Team"));
			ELSEIF LOWER(ProcessName) = "deduction" THEN
				INSERT INTO hrm_notification(noti_userid,noti_subject,noti_body,noti_url,noti_email,noti_email_subject,noti_email_body) VALUES(UID, ComName, CONCAT("Hello, " , EmpSalutation , " ", EmpName, ".\nThere's a new deduction request that need you to approve."), "/auth/authapprove", Email, "Approval Deduction Request", CONCAT("Company\t\t\t: <b>", ComName, "</b><br><br>Objective\t\t:Approval Deduction Request<br><br>Transaction\t\t\t: ", ProcessID, "<br><br><br><br><br>Dear ", EmpSalutation, " ", EmpName, "<br><br><br><br><br>On ", DATE_FORMAT(SNowTime, "%W, %M %e, %Y %h:%i %p"), ", The deduction request has been created with Transaction ID <b>", ProcessID, "</b> that need you to approve on this request.<br><br><br><br><br>Thank you for using Balancika HRM, if you need further assistance, please contact our support team at support@balancikacambodia.com.<br><br><br><br><br>Best regard,<br><br>Balancika Team"));
			ELSEIF LOWER(ProcessName) = "leave" THEN
				INSERT INTO hrm_notification(noti_userid,noti_subject,noti_body,noti_url,noti_email,noti_email_subject,noti_email_body) VALUES(UID, ComName, CONCAT("Hello, " , EmpSalutation , " ", EmpName, ".\nThere's a new leave request that need you to approve."), "/auth/authapprove", Email, "Approval Leave Request", CONCAT("Company\t\t\t: <b>", ComName, "</b><br><br>Objective\t\t:Approval Leave Request<br><br>Transaction\t\t\t: ", ProcessID, "<br><br><br><br><br>Dear ", EmpSalutation, " ", EmpName, "<br><br><br><br><br>On ", DATE_FORMAT(SNowTime, "%W, %M %e, %Y %h:%i %p"), ", The leave request has been created with Transaction ID <b>", ProcessID, "</b> that need you to approve on this request.<br><br><br><br><br>Thank you for using Balancika HRM, if you need further assistance, please contact our support team at support@balancikacambodia.com.<br><br><br><br><br>Best regard,<br><br>Balancika Team"));
			ELSEIF LOWER(ProcessName) = "overtime" THEN
				INSERT INTO hrm_notification(noti_userid,noti_subject,noti_body,noti_url,noti_email,noti_email_subject,noti_email_body) VALUES(UID, ComName, CONCAT("Hello, " , EmpSalutation , " ", EmpName, ".\nThere's a new overtime request that need you to approve."), "/auth/authapprove", Email, "Approval Overtime Request", CONCAT("Company\t\t\t: <b>", ComName, "</b><br><br>Objective\t\t:Approval Overtime Request<br><br>Transaction\t\t\t: ", ProcessID, "<br><br><br><br><br>Dear ", EmpSalutation, " ", EmpName, "<br><br><br><br><br>On ", DATE_FORMAT(SNowTime, "%W, %M %e, %Y %h:%i %p"), ", The overtime request has been created with Transaction ID <b>", ProcessID, "</b> that need you to approve on this request.<br><br><br><br><br>Thank you for using Balancika HRM, if you need further assistance, please contact our support team at support@balancikacambodia.com.<br><br><br><br><br>Best regard,<br><br>Balancika Team"));
			END IF;
		END IF;
  END LOOP;

	CLOSE cur1;


	CALL ameAddAuthorizationWatcherIn(AuthID,ProcessID,ProcessName);

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddGAuthorisationApprovedTemp`;
DELIMITER |
CREATE PROCEDURE `spHRMAddGAuthorisationApprovedTemp`(IN SUserID varchar(255), IN AuthID varchar(255),IN ProcessName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE done INT DEFAULT FALSE;
	DECLARE AuthEmpID VARCHAR(255);
	DECLARE AuthGroupID VARCHAR(255);
	DECLARE SNow DATE;
	DECLARE tz VARCHAR(20) DEFAULT('');
	DECLARE cur1 CURSOR FOR SELECT a.Auth_GroupID,AuthGroup_EmpID FROM hrm_authorisation_detail a LEFT JOIN hrm_authorisation_group_detail g ON(g.AuthGroup_ID = a.Auth_GroupID) WHERE a.Auth_ID = AuthID;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	SELECT Setting_Value INTO tz FROM hrm_setting WHERE Setting_Type = 'TimeZone' AND Setting_Name = 'TimeZone';
	SET SNow = convert_tz(now(), @@session.time_zone, tz);

	OPEN cur1;
	read_loop: LOOP
    FETCH cur1 INTO AuthGroupID,AuthEmpID;
    IF done THEN
      LEAVE read_loop;
    END IF;
		IF !ISNULL(AuthEmpID) THEN
			IF ProcessName = "Dayoff" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_GroupID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT dayoff_id, ProcessName, AuthID, AuthGroupID, AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = dayoff_id AND Auth_ProcessName = 'Dayoff' AND Auth_ID = AuthID AND Auth_GroupID = AuthGroupID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, SUserID FROM hrm_timesheet_dayoff WHERE LOWER(dayoff_status) NOT IN('approved', 'rejected') AND dayoff_authid = AuthID);
			ELSEIF ProcessName = "Deduction" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_GroupID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT deduction_id, ProcessName, AuthID, AuthGroupID, AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = deduction_id AND Auth_ProcessName = 'Deduction' AND Auth_ID = AuthID AND Auth_GroupID = AuthGroupID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, SUserID FROM hrm_payroll_deduction WHERE LOWER(deduction_status) NOT IN('approved', 'rejected') AND deduction_authid = AuthID);
			ELSEIF ProcessName = "Overtime" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_GroupID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT overtime_id, ProcessName, AuthID, AuthGroupID, AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = overtime_id AND Auth_ProcessName = 'Overtime' AND Auth_ID = AuthID AND Auth_GroupID = AuthGroupID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, SUserID FROM hrm_payroll_overtime WHERE LOWER(overtime_status) NOT IN('approved', 'rejected') AND overtime_authid = AuthID);
			ELSEIF ProcessName = "Leave" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_GroupID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT leave_id, ProcessName, AuthID, AuthGroupID, AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = leave_id AND Auth_ProcessName = 'Leave' AND Auth_ID = AuthID AND Auth_GroupID = AuthGroupID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, SUserID FROM hrm_timesheet_leave WHERE LOWER(leave_status) NOT IN('approved', 'rejected') AND leave_authid = AuthID);
			ELSEIF ProcessName = "Customer" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_GroupID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT var_id, ProcessName, AuthID, AuthGroupID,AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.var_id AND Auth_ProcessName = 'Customer' AND Auth_ID = AuthID AND Auth_GroupID = AuthGroupID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM crm_customer d WHERE LOWER(var_crm_approval) NOT IN('approved', 'rejected') AND d.var_authId = AuthID);
			ELSEIF ProcessName = "Sale Order" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_GroupID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT var_id, ProcessName, AuthID, AuthGroupID,AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.var_id AND Auth_ProcessName = 'Sale Order' AND Auth_ID = AuthID AND Auth_GroupID = AuthGroupID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM ame_ar_so d WHERE LOWER(var_auth_status) NOT IN('approved', 'rejected') AND d.var_authId = AuthID);
			ELSEIF ProcessName = "Quote" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_GroupID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT var_id, ProcessName, AuthID, AuthGroupID,AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.var_id AND Auth_ProcessName = 'Quote' AND Auth_ID = AuthID AND Auth_GroupID = AuthGroupID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM ame_ar_quo d WHERE LOWER(d.var_auth_status) NOT IN('approved', 'rejected') AND d.var_authId = AuthID);
			ELSEIF ProcessName = "Over Due Date" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_GroupID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT var_id, ProcessName, AuthID, AuthGroupID,AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.var_id AND Auth_ProcessName = 'Over Due Date' AND Auth_ID = AuthID AND Auth_GroupID = AuthGroupID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM ame_mt_tem_odd d WHERE LOWER(d.var_status) NOT IN('approved', 'rejected') AND d.var_authId = AuthID);
			ELSEIF ProcessName = "Temporary Credit" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_GroupID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT var_id, ProcessName, AuthID, AuthGroupID,AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.var_id AND Auth_ProcessName = 'Temporary Credit' AND Auth_ID = AuthID AND Auth_GroupID = AuthGroupID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM ame_mt_tem_tc d WHERE LOWER(`d.var_status`) NOT IN('approved', 'rejected') AND d.var_authId = AuthID);
			ELSEIF ProcessName = "General Requisition" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_GroupID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT FrmID, ProcessName, AuthID, AuthGroupID,AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.FrmID AND Auth_ProcessName = 'General Requisition' AND Auth_ID = AuthID AND Auth_GroupID = AuthGroupID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM crm_frm_general d WHERE LOWER(ApprovalStatus) NOT IN('approved', 'rejected') AND d.GRAuthID = AuthID);
			ELSEIF ProcessName = "Budget Requisition" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_GroupID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT FrmID, ProcessName, AuthID, AuthGroupID,AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.FrmID AND Auth_ProcessName = 'Budget Requisition' AND Auth_ID = AuthID AND Auth_GroupID = AuthGroupID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM crm_frm_budget d WHERE LOWER(ApprovalStatus) NOT IN('approved', 'rejected') AND  d.BRAuthID = AuthID);
			ELSEIF ProcessName = "Material Request" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_GroupID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT EntryNo, ProcessName, AuthID, AuthGroupID,AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.EntryNo AND Auth_ProcessName = 'Expense Request' AND Auth_ID = AuthID AND Auth_GroupID = AuthGroupID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM ats_materialrequest d WHERE LOWER(`STATUS`) NOT IN('approved', 'rejected') AND  d.var_authId = AuthID);
			END IF;

		END IF;
  END LOOP;

	CLOSE cur1;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddHoliday`;
DELIMITER |
CREATE PROCEDURE `spHRMAddHoliday`(userid varchar(255),SName varchar(255), SType varchar(255), SStart Date,SEnd Date, SValue text, SValue2 text)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE CheckAllowed INT DEFAULT(0);

	
	IF SValue != "" THEN
		
		IF CheckExist <= 0 THEN
			CALL spHRMGetNumberPrefix("Holiday", ID);
		
			SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_holiday(Holiday_ID,Holiday_Name,Holiday_Type,Holiday_Duration,Holiday_StartDate,Holiday_EndDate,Holiday_Description) VALUES ", SValue, ";");
			SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			IF SValue2 <> '' THEN
				SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_holiday_detail(HolidayD_ID,HolidayD_Status,HolidayD_BranchID,HolidayD_DepartmentID,HolidayD_Index) VALUES ", SValue2, ";");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;
			END IF;

			CALL spHRMUpdateNumberPrefix("Holiday");

			IF LOWER(SType) = 'all' THEN
				CALL spHRMAttendanceHolidayAddAll(SStart, SEnd);
			ELSE
				BEGIN
					DECLARE SDType VARCHAR(255) DEFAULT('');
					DECLARE SDBranch VARCHAR(255) DEFAULT('');
					DECLARE SDDepartment VARCHAR(255) DEFAULT('');
					DECLARE done INT DEFAULT FALSE;
					DECLARE cursor_i CURSOR FOR SELECT HolidayD_Status,HolidayD_BranchID,HolidayD_DepartmentID FROM hrm_timesheet_holiday_detail h WHERE h.HolidayD_ID = ID;
					DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
					OPEN cursor_i;
					read_loop: LOOP
					FETCH cursor_i INTO SDType,SDBranch,SDDepartment;
					IF done THEN
						LEAVE read_loop;
					END IF;
						CALL spHRMAttendanceHolidayAdd(SDType, SDBranch, SDDepartment, SStart, SEnd);
					END LOOP;
				END;
			END IF;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Holiday', ID);

			SELECT ID;
			CALL hrm_message('1101801', 'Holiday', 'create', ID);
		ELSE
			SET ID = "exist";
			SELECT ID;
			CALL hrm_message('1101804', 'Holiday', 'exist', SName);
		END IF;
	ELSE
		SET ID = "not allow";
		SELECT ID;
		CALL hrm_message('1101806', 'Holiday', 'notallowed', SBranch);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddIAuthorisationApproved`;
DELIMITER |
CREATE PROCEDURE `spHRMAddIAuthorisationApproved`(IN AuthID varchar(255),IN ProcessID varchar(255),IN ProcessName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE done INT DEFAULT FALSE;
	DECLARE AuthEmpID VARCHAR(255);
	DECLARE SNow DATE;
	DECLARE SNowTime DATETIME;
	DECLARE tz VARCHAR(20) DEFAULT('');
	DECLARE ComName VARCHAR(255) DEFAULT('');
	DECLARE EmpName VARCHAR(255) DEFAULT('');
	DECLARE EmpSalutation VARCHAR(255) DEFAULT('');
	DECLARE UID VARCHAR(255) DEFAULT('');
	DECLARE Email VARCHAR(255) DEFAULT('');
	
	DECLARE cur1 CURSOR FOR SELECT DISTINCT(Auth_EmpID), e.var_id, e.var_hrm_salutation, u.var_id, e.var_hrm_company_email FROM hrm_authorisation_detail authd LEFT JOIN ame_mt_emp e ON(authd.Auth_EmpID = e.var_id) LEFT JOIN ame_user u ON(u.var_empid = authd.Auth_EmpID) WHERE Auth_ID = AuthID;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	
	SELECT Setting_Value INTO ComName FROM hrm_setting WHERE Setting_Type = 'Company' AND Setting_Name = 'Name';

	SELECT Setting_Value INTO tz FROM hrm_setting WHERE Setting_Type = 'TimeZone' AND Setting_Name = 'TimeZone';
	SET SNow = convert_tz(now(), @@session.time_zone, tz);
	SET SNowTime = convert_tz(now(), @@session.time_zone, tz);

	OPEN cur1;
	read_loop: LOOP
    FETCH cur1 INTO AuthEmpID, EmpName, EmpSalutation, UID, Email;
    IF done THEN
      LEAVE read_loop;
    END IF;
		IF !ISNULL(AuthEmpID) THEN
			INSERT INTO hrm_authorisation_approved(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_EmpID,Auth_Status,Auth_Date) VALUES (ProcessID, ProcessName, AuthID, AuthEmpID, 'requested', SNow);
			
			IF LOWER(ProcessName) = "dayoff" THEN
				INSERT INTO hrm_notification(noti_userid,noti_subject,noti_body,noti_url,noti_email,noti_email_subject,noti_email_body) VALUES(UID, ComName, CONCAT("Hello, " , EmpSalutation , " ", EmpName, ".\nThere's a new dayoff request that need you to approve."), "/auth/authapprove", Email, "Approval Dayoff Request", CONCAT("Company\t\t\t: <b>", ComName, "</b><br><br>Objective\t\t:Approval Dayoff Request<br><br>Transaction\t\t\t: ", ProcessID, "<br><br><br><br><br>Dear ", EmpSalutation, " ", EmpName, "<br><br><br><br><br>On ", DATE_FORMAT(SNowTime, "%W, %M %e, %Y %h:%i %p"), ", The dayoff request has been created with Transaction ID <b>", ProcessID, "</b> that need you to approve on this request.<br><br><br><br><br>Thank you for using Balancika HRM, if you need further assistance, please contact our support team at support@balancikacambodia.com.<br><br><br><br><br>Best regard,<br><br>Balancika Team"));
			ELSEIF LOWER(ProcessName) = "deduction" THEN
				INSERT INTO hrm_notification(noti_userid,noti_subject,noti_body,noti_url,noti_email,noti_email_subject,noti_email_body) VALUES(UID, ComName, CONCAT("Hello, " , EmpSalutation , " ", EmpName, ".\nThere's a new deduction request that need you to approve."), "/auth/authapprove", Email, "Approval Deduction Request", CONCAT("Company\t\t\t: <b>", ComName, "</b><br><br>Objective\t\t:Approval Deduction Request<br><br>Transaction\t\t\t: ", ProcessID, "<br><br><br><br><br>Dear ", EmpSalutation, " ", EmpName, "<br><br><br><br><br>On ", DATE_FORMAT(SNowTime, "%W, %M %e, %Y %h:%i %p"), ", The deduction request has been created with Transaction ID <b>", ProcessID, "</b> that need you to approve on this request.<br><br><br><br><br>Thank you for using Balancika HRM, if you need further assistance, please contact our support team at support@balancikacambodia.com.<br><br><br><br><br>Best regard,<br><br>Balancika Team"));
			ELSEIF LOWER(ProcessName) = "leave" THEN
				INSERT INTO hrm_notification(noti_userid,noti_subject,noti_body,noti_url,noti_email,noti_email_subject,noti_email_body) VALUES(UID, ComName, CONCAT("Hello, " , EmpSalutation , " ", EmpName, ".\nThere's a new leave request that need you to approve."), "/auth/authapprove", Email, "Approval Leave Request", CONCAT("Company\t\t\t: <b>", ComName, "</b><br><br>Objective\t\t:Approval Leave Request<br><br>Transaction\t\t\t: ", ProcessID, "<br><br><br><br><br>Dear ", EmpSalutation, " ", EmpName, "<br><br><br><br><br>On ", DATE_FORMAT(SNowTime, "%W, %M %e, %Y %h:%i %p"), ", The leave request has been created with Transaction ID <b>", ProcessID, "</b> that need you to approve on this request.<br><br><br><br><br>Thank you for using Balancika HRM, if you need further assistance, please contact our support team at support@balancikacambodia.com.<br><br><br><br><br>Best regard,<br><br>Balancika Team"));
			ELSEIF LOWER(ProcessName) = "overtime" THEN
				INSERT INTO hrm_notification(noti_userid,noti_subject,noti_body,noti_url,noti_email,noti_email_subject,noti_email_body) VALUES(UID, ComName, CONCAT("Hello, " , EmpSalutation , " ", EmpName, ".\nThere's a new overtime request that need you to approve."), "/auth/authapprove", Email, "Approval Overtime Request", CONCAT("Company\t\t\t: <b>", ComName, "</b><br><br>Objective\t\t:Approval Overtime Request<br><br>Transaction\t\t\t: ", ProcessID, "<br><br><br><br><br>Dear ", EmpSalutation, " ", EmpName, "<br><br><br><br><br>On ", DATE_FORMAT(SNowTime, "%W, %M %e, %Y %h:%i %p"), ", The overtime request has been created with Transaction ID <b>", ProcessID, "</b> that need you to approve on this request.<br><br><br><br><br>Thank you for using Balancika HRM, if you need further assistance, please contact our support team at support@balancikacambodia.com.<br><br><br><br><br>Best regard,<br><br>Balancika Team"));
			END IF;
			
		END IF;
  END LOOP;
	CLOSE cur1;

	
	-- CALL ameAddAuthorizationWatcherIn(AuthID,ProcessID,ProcessName);


END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddIAuthorisationApprovedTemp`;
DELIMITER |
CREATE PROCEDURE `spHRMAddIAuthorisationApprovedTemp`(IN UserID varchar(255), IN AuthID varchar(255),IN ProcessName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE done INT DEFAULT FALSE;
	DECLARE AuthEmpID VARCHAR(255);
	DECLARE SNow DATE;
	DECLARE tz VARCHAR(20) DEFAULT('');
	DECLARE cur1 CURSOR FOR SELECT DISTINCT(Auth_EmpID) FROM hrm_authorisation_detail WHERE Auth_ID = AuthID;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	SELECT Setting_Value INTO tz FROM hrm_setting WHERE Setting_Type = 'TimeZone' AND Setting_Name = 'TimeZone';
	SET SNow = convert_tz(now(), @@session.time_zone, tz);

	OPEN cur1;
	read_loop: LOOP
    FETCH cur1 INTO AuthEmpID;
    IF done THEN
      LEAVE read_loop;
    END IF;
		IF !ISNULL(AuthEmpID) THEN

			IF ProcessName = "Dayoff" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT dayoff_id, ProcessName, AuthID, AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.dayoff_id AND Auth_ProcessName = 'Dayoff' AND Auth_ID = AuthID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM hrm_timesheet_dayoff d WHERE LOWER(dayoff_status) NOT IN('approved', 'rejected') AND dayoff_authid = AuthID);
			ELSEIF ProcessName = "Deduction" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT deduction_id, ProcessName, AuthID, AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.deduction_id AND Auth_ProcessName = 'Deduction' AND Auth_ID = AuthID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM hrm_payroll_deduction d WHERE LOWER(deduction_status) NOT IN('approved', 'rejected') AND deduction_authid = AuthID);
			ELSEIF ProcessName = "Overtime" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT overtime_id, ProcessName, AuthID, AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.overtime_id AND Auth_ProcessName = 'Overtime' AND Auth_ID = AuthID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM hrm_payroll_overtime d WHERE LOWER(overtime_status) NOT IN('approved', 'rejected') AND overtime_authid = AuthID);
			ELSEIF ProcessName = "Leave" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT leave_id, ProcessName, AuthID, AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.leave_id AND Auth_ProcessName = 'Leave' AND Auth_ID = AuthID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM hrm_timesheet_leave d WHERE LOWER(leave_status) NOT IN('approved', 'rejected') AND leave_authid = AuthID);
			ELSEIF ProcessName = "Customer" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT var_id, ProcessName, AuthID, AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.var_id AND Auth_ProcessName = 'Customer' AND Auth_ID = AuthID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM crm_customer d WHERE LOWER(var_crm_approval) NOT IN('approved', 'rejected') AND d.var_authId = AuthID);
			ELSEIF ProcessName = "Sale Order" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT var_id, ProcessName, AuthID, AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.var_id AND Auth_ProcessName = 'Sale Order' AND Auth_ID = AuthID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM ame_ar_so d WHERE LOWER(var_auth_status) NOT IN('approved', 'rejected') AND d.var_authId = AuthID);
			ELSEIF ProcessName = "Quote" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT var_id, ProcessName, AuthID, AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.var_id AND Auth_ProcessName = 'Quote' AND Auth_ID = AuthID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM ame_ar_quo d WHERE LOWER(d.var_auth_status) NOT IN('approved', 'rejected') AND d.var_authId = AuthID);
			ELSEIF ProcessName = "Over Due Date" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT var_id, ProcessName, AuthID, AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.var_id AND Auth_ProcessName = 'Over Due Date' AND Auth_ID = AuthID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM ame_mt_tem_odd d WHERE LOWER(d.var_status) NOT IN('approved', 'rejected') AND d.var_authId = AuthID);
			ELSEIF ProcessName = "Temporary Credit" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT var_id, ProcessName, AuthID, AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.var_id AND Auth_ProcessName = 'Temporary Credit' AND Auth_ID = AuthID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM ame_mt_tem_tc d WHERE LOWER(`d.var_status`) NOT IN('approved', 'rejected') AND d.var_authId = AuthID);
			ELSEIF ProcessName = "General Requisition" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT FrmID, ProcessName, AuthID, AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.FrmID AND Auth_ProcessName = 'General Requisition' AND Auth_ID = AuthID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM crm_frm_general d WHERE LOWER(ApprovalStatus) NOT IN('approved', 'rejected') AND d.GRAuthID = AuthID);
			ELSEIF ProcessName = "Budget Requisition" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT FrmID, ProcessName, AuthID, AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.FrmID AND Auth_ProcessName = 'Budget Requisition' AND Auth_ID = AuthID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM crm_frm_budget d WHERE LOWER(ApprovalStatus) NOT IN('approved', 'rejected') AND  d.BRAuthID = AuthID);
			ELSEIF ProcessName = "Material Request" THEN
				INSERT INTO hrm_authorisation_approved_temp(Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_EmpID,Auth_Status,Auth_Date,UserID) (SELECT EntryNo, ProcessName, AuthID, AuthEmpID, COALESCE((SELECT Auth_Status FROM hrm_authorisation_approved WHERE Auth_ProcessID = d.EntryNo AND Auth_ProcessName = 'Expense Request' AND Auth_ID = AuthID AND Auth_EmpID = AuthEmpID LIMIT 1), 'requested'), SNow, UserID FROM ats_materialrequest d WHERE LOWER(`STATUS`) NOT IN('approved', 'rejected') AND  d.var_authId = AuthID);
			END IF;
			
		END IF;
  END LOOP;

	CLOSE cur1;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddLateDuration`;
DELIMITER |
CREATE PROCEDURE `spHRMAddLateDuration`(userid varchar(255), SValue text, SFrom int, STo int, SDeduct int)
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	
			SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_late_duration(LD_From,LD_To,LD_Deduction) VALUES ", SValue, ";");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Late Duration', CONCAT(SFrom,', ',STo, ', ', SDeduct));

			SET Message = "success";
			SELECT Message;
			CALL hrm_message('1104701', 'LateDuration', 'create', '');
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddLeave`;
DELIMITER |
CREATE PROCEDURE `spHRMAddLeave`(userid varchar(255), SEmpID varchar(255), SValue text, SValue2 text)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE CheckExist VARCHAR(255) DEFAULT("");
	DECLARE AuthType VARCHAR(255) DEFAULT("");
	DECLARE CheckAuth VARCHAR(1) DEFAULT("1");
	DECLARE Amt FLOAT DEFAULT(0);
	
	IF SValue != "" THEN
			
			-- Check Auth Allow or not
			SELECT Setting_Value INTO CheckAuth FROM hrm_setting WHERE Setting_Type = "Authorisation" AND Setting_Name = "Authorisation_Leave";

			IF CheckAuth = "1" THEN
			
				-- find Auth ID
				SELECT Auth_ID INTO CheckExist FROM hrm_authorisation_employee WHERE Emp_ID = SEmpID AND Auth_Process = 'Leave';
				IF CheckExist = "" THEN
					SELECT Setting_Value INTO CheckExist FROM hrm_setting WHERE Setting_Name = 'Leave' AND Setting_Type = 'Authorisation';
				END IF;

				IF CheckExist != "" THEN

						CALL spHRMGetNumberPrefix("Leave", ID);

						SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_leave(Leave_ID,Leave_EmpID,Leave_Tel,Leave_Email,Leave_Reason,Leave_From,Leave_To,Leave_Description,Leave_AttachmentName,Leave_AttachmentPath,Leave_Status,Leave_AuthID) VALUES ", SValue, ";");
						SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
						SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'requested');
						SET @SQL1 = REPLACE(@SQL1, 'Temp_AuthID', CheckExist);
						PREPARE St FROM @SQL1;
						EXECUTE St;
						DEALLOCATE PREPARE St;

						CALL spHRMUpdateNumberPrefix("Leave");

						SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_leave_detail(LeaveD_ID,LeaveD_Date,LeaveD_Duration,LeaveD_TypeID,LeaveD_TimeFrom,LeaveD_TimeTo,Leave_Total,Leave_Amount,Leave_TotalWorkHour) VALUES ", SValue2, ";");
						SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
						PREPARE St FROM @SQL1;
						EXECUTE St;
						DEALLOCATE PREPARE St;

						INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Leave', ID);

						SELECT Auth_Type INTO AuthType FROM hrm_authorisation WHERE Auth_ID = CheckExist;
			
						IF AuthType = "Individual" THEN
							CALL spHRMAddIAuthorisationApproved(CheckExist, ID, 'Leave');
						ELSE
							CALL spHRMAddGAuthorisationApproved(CheckExist, ID, 'Leave');
						END IF;
						CALL spHRMAddAuthorisationTemp(CheckExist,ID); 

						SELECT ID;
						CALL hrm_message('1101601', 'Leave', 'create', ID);

				ELSE
					SET ID = "no authorisation";
					SELECT ID;
					CALL hrm_message('1101608', 'Leave', 'auth', SEmpID);
				END IF;

			ELSE
						CALL spHRMGetNumberPrefix("Leave", ID);
						
						SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_leave(Leave_ID,Leave_EmpID,Leave_Tel,Leave_Email,Leave_Reason,Leave_From,Leave_To,Leave_Description,Leave_AttachmentName,Leave_AttachmentPath,Leave_Status,Leave_AuthID) VALUES ", SValue, ";");
						SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
						SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'approved');
						SET @SQL1 = REPLACE(@SQL1, 'Temp_AuthID', '');
						PREPARE St FROM @SQL1;
						EXECUTE St;
						DEALLOCATE PREPARE St;

						CALL spHRMUpdateNumberPrefix("Leave");

						SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_leave_detail(LeaveD_ID,LeaveD_Date,LeaveD_Duration,LeaveD_TypeID,LeaveD_TimeFrom,LeaveD_TimeTo,Leave_Total,Leave_Amount,Leave_TotalWorkHour) VALUES ", SValue2, ";");
						SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
						PREPARE St FROM @SQL1;
						EXECUTE St;
						DEALLOCATE PREPARE St;
			
						call spHRMCheckAddAttendanceLeave(ID, SEmpID); 

						INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Leave', ID);
						
						SELECT ID;
						CALL hrm_message('1101601', 'Leave', 'create', ID);
									
			END IF;
	
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddLog`;
DELIMITER |
CREATE PROCEDURE `spHRMAddLog`(UserID varchar(255),Action varchar(255),SysName varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID,Action,SysName,ID);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddManyEmployeeAuthorisation`;
DELIMITER |
CREATE PROCEDURE `spHRMAddManyEmployeeAuthorisation`(userid varchar(255), SReplace tinyint, EmployeeAuth text)
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE Exist INT DEFAULT(0);

	IF SReplace <= 0 THEN
		SET @SQL1 = CONCAT("INSERT INTO hrm_authorisation_employee(Emp_ID,Auth_Process,Auth_ID) VALUES ", EmployeeAuth, " ON DUPLICATE KEY UPDATE Emp_ID = Emp_ID ,Auth_Process=Auth_Process;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
			CALL spHRMAddLog(userid, "insert", "EmployeeAuthorisation", "Many");
	
			SET Message = "success";
			SELECT Message;
			CALL hrm_message('1102401', 'EmpAuth', 'create', '');
	ELSE
		SET @SQL1 = CONCAT("INSERT INTO hrm_authorisation_employee(Emp_ID,Auth_Process,Auth_ID) VALUES ", EmployeeAuth, " ON DUPLICATE KEY UPDATE Emp_ID = Emp_ID ,Auth_Process=Auth_Process;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
			CALL spHRMAddLog(userid, "insert", "EmployeeAuthorisation", "Many");
	
			SET Message = "success";
			SELECT Message;
			CALL hrm_message('1102401', 'EmpAuth', 'create', '');
	END IF;
		
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddOvertime`;
DELIMITER |
CREATE PROCEDURE `spHRMAddOvertime`(userid varchar(255),SValue text, SValue2 text, SValue3 text)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE CheckExist VARCHAR(255) DEFAULT("");
	DECLARE AuthType VARCHAR(255) DEFAULT("");
	DECLARE CheckAuth VARCHAR(1) DEFAULT("1");
	DECLARE CheckOvertime int DEFAULT(0);

	DECLARE CheckU VARCHAR(255) DEFAULT("");
	DECLARE Emp VARCHAR(255) DEFAULT("");

	DECLARE SNow DATETIME;
	DECLARE tz VARCHAR(20) DEFAULT('');

	SELECT Setting_Value INTO tz FROM hrm_setting WHERE Setting_Type = 'TimeZone' AND Setting_Name = 'TimeZone';
	SET SNow = convert_tz(now(), @@session.time_zone, tz);

	SELECT var_hrm_utype, var_empid INTO CheckU,Emp FROM ame_user u WHERE u.var_id = userid; 
	
	IF (SValue != "" AND CheckU = "ESS") OR (SValue != "" AND (CheckU = "Normal" OR CheckU = "Administrator" OR CheckU = "")) THEN

			SELECT Setting_Value INTO CheckAuth FROM hrm_setting WHERE Setting_Type = "Authorisation" AND Setting_Name = "Authorisation_Overtime";

			IF CheckAuth = "1" THEN

				SELECT Auth_ID INTO CheckExist FROM hrm_authorisation_employee WHERE Emp_ID = Emp AND Auth_Process = 'Overtime';
				IF CheckExist = "" THEN
					SELECT Setting_Value INTO CheckExist FROM hrm_setting WHERE Setting_Name = 'Overtime' AND Setting_Type = 'Authorisation';
				END IF;

				IF CheckExist != "" THEN

						CALL spHRMGetNumberPrefix("Overtime", ID);
	
						SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_overtime(Overtime_ID,Overtime_Reason,Overtime_Type,Overtime_Amount,Overtime_Multiplier,Overtime_DateFrom,Overtime_DateTo,Overtime_TimeIn,Overtime_TimeOut,Overtime_Description,Overtime_Status,Overtime_AuthID,Overtime_RequestBy,Overtime_CreateDate) VALUES ", SValue, ";");
						SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
						SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'requested');
						SET @SQL1 = REPLACE(@SQL1, 'Temp_AuthID', CheckExist);
						SET @SQL1 = REPLACE(@SQL1, 'Temp_RequestBy', Emp);
						SET @SQL1 = REPLACE(@SQL1, 'Temp_CreateDate', SNow);
						PREPARE St FROM @SQL1;
						EXECUTE St;
						DEALLOCATE PREPARE St;

						CALL spHRMUpdateNumberPrefix("Overtime");

						SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_overtime_detail(od_id,od_date,od_timein,od_timeout,od_hours,od_multiplier) VALUES ", SValue2, ";");
						SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
						PREPARE St FROM @SQL1;
						EXECUTE St;
						DEALLOCATE PREPARE St;

						SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_overtime_detail_employee(od_id,od_empid,od_status) VALUES ", SValue3, ";");
						SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
						SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'Open');
						PREPARE St FROM @SQL1;
						EXECUTE St;
						DEALLOCATE PREPARE St;

						INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Overtime', ID);

						SELECT Auth_Type INTO AuthType FROM hrm_authorisation WHERE Auth_ID = CheckExist;
						
						IF AuthType = "Individual" THEN
							CALL spHRMAddIAuthorisationApproved(CheckExist, ID, 'Overtime');
						ELSE
							CALL spHRMAddGAuthorisationApproved(CheckExist, ID, 'Overtime');
						END IF;
						CALL spHRMAddAuthorisationTemp(CheckExist,ID); 
						SELECT ID;
						CALL hrm_message('1100701', 'Overtime', 'create', ID);
					
				ELSE
					SET ID = "no authorisation";
					SELECT ID;
					CALL hrm_message('1100706', 'Overtime', 'auth', Emp);
				END IF;

			ELSE
					CALL spHRMGetNumberPrefix("Overtime", ID);
	
					SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_overtime(Overtime_ID,Overtime_Reason,Overtime_Type,Overtime_Amount,Overtime_Multiplier,Overtime_DateFrom,Overtime_DateTo,Overtime_TimeIn,Overtime_TimeOut,Overtime_Description,Overtime_Status,Overtime_AuthID,Overtime_RequestBy,Overtime_CreateDate) VALUES ", SValue, ";");
					SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
					SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'approved');
					SET @SQL1 = REPLACE(@SQL1, 'Temp_AuthID', CheckExist);
					SET @SQL1 = REPLACE(@SQL1, 'Temp_RequestBy', Emp);
					SET @SQL1 = REPLACE(@SQL1, 'Temp_CreateDate', SNow);
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;

					CALL spHRMUpdateNumberPrefix("Overtime");

					SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_overtime_detail(od_id,od_date,od_timein,od_timeout,od_hours,od_multiplier) VALUES ", SValue2, ";");
					SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;

					SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_overtime_detail_employee(od_id,od_empid,od_status) VALUES ", SValue3, ";");
					SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
					SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'Open');
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;

					CALL spHRMUpdateNumberPrefix("Overtime");
					INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Overtime', ID);
					SELECT ID;
					CALL hrm_message('1100701', 'Overtime', 'create', ID);
			END IF;
	ELSE
		SET ID = "not allow";
		SELECT ID;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddPayroll`;
DELIMITER |
CREATE PROCEDURE `spHRMAddPayroll`(userid varchar(255),CName varchar(255),CValue text)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);

	IF CValue != "" THEN

		SELECT COUNT(*) INTO CheckExist FROM hrm_payroll WHERE LOWER(Payroll_Name) = CName;

			IF CheckExist <= 0 THEN

				CALL spHRMGetNumberPrefix("Payroll", ID);
	
				SET @SQL1 = CONCAT("INSERT INTO hrm_payroll(Payroll_ID,Payroll_Name,Payroll_Type,Payroll_StartDate,Payroll_LastSubmitDate,Payroll_SubmitDate,Payroll_SalaryStartDate,Payroll_LastSalaryDate,Payroll_SalaryDate,Payroll_AmtWorkingDay,Payroll_AmtWorkingHourPerDay) VALUES ", CValue, ";");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				CALL spHRMUpdateNumberPrefix("Payroll");

				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Payroll', ID);

				SELECT ID;
				CALL hrm_message('1100801', 'Payroll', 'create', ID);
			ELSE
				SET ID = "exist";
				SELECT ID;
				CALL hrm_message('1100804', 'Payroll', 'exist', CName);
			END IF;
	
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddReportPer`;
DELIMITER |
CREATE PROCEDURE `spHRMAddReportPer`(UID varchar(255))
    DETERMINISTIC
BEGIN
DECLARE v_finished INTEGER DEFAULT 0;
DECLARE SysName varchar(255) DEFAULT "";
DEClARE LocationID_Cursor CURSOR FOR
SELECT U.RptName FROM hrm_reportpermission U WHERE U.UID = 'Admin';
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET v_finished = 1;
OPEN LocationID_Cursor;
GetLocationID: LOOP
FETCH LocationID_Cursor INTO SysName;
IF v_finished = 1 THEN
LEAVE GetLocationID;
END IF;
INSERT INTO hrm_reportpermission VALUES(UID,SysName,0);
END LOOP GetLocationID;
CLOSE LocationID_Cursor;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddRole`;
DELIMITER |
CREATE PROCEDURE `spHRMAddRole`(userid varchar(255),SValue text, SValueDetail text, SValueRDetail text)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);

	IF SValue != "" THEN	
				CALL spHRMGetNumberPrefix("Role", ID);
	
				SET @SQL1 = CONCAT("INSERT INTO hrm_role(RM_ID,RM_Name,RM_Des,RM_Status) VALUES ", SValue, ";");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				SET @SQL1 = CONCAT("INSERT INTO hrm_role_detail(RM_ModuleID,RM_Delete,RM_Edit,RM_Export,RM_Import,RM_List,RM_View,RM_Access,RM_RoleID) VALUES ", SValueDetail, ";");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				SET @SQL1 = CONCAT("INSERT INTO hrm_role_rpt_detail(RMR_RoleID,RMR_RPTID,RMR_View) VALUES ", SValueRDetail, ";");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				CALL spHRMUpdateNumberPrefix("Role");

				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Role', ID);

				SELECT ID;
				CALL hrm_message('1104301', 'Role', 'create', ID);

	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddRoster`;
DELIMITER |
CREATE PROCEDURE `spHRMAddRoster`(userid varchar(255), SDate Date, SEmpID varchar(255), SShiftID varchar(255), SValue text)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE SNow DATE;
	DECLARE tz VARCHAR(20) DEFAULT('');

	SELECT Setting_Value INTO tz FROM hrm_setting WHERE Setting_Type = 'TimeZone' AND Setting_Name = 'TimeZone';
	SET SNow = convert_tz(now(), @@session.time_zone, tz);

	IF SValue != "" AND SNow < SDate  THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_timesheet_roster WHERE Roster_Date = SDate AND LOWER(Roster_EmpID) = SEmpID;

		IF CheckExist <= 0 THEN
		
			SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_roster(Roster_Date,Roster_EmpID,Roster_ShiftID) VALUES ", SValue, ";");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;


			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Roster', CONCAT(SDate,", ",SEmpID));

			SET ID = SEmpID;
			SELECT ID;
			CALL hrm_message('1102001', 'Roster', 'create', SShiftID);
		ELSE
			SET ID = "exist";
			SELECT ID;
			CALL hrm_message_param3('1102004', 'Roster', 'exist', SDate, SEmpID, "");
		END IF;
	ELSE
		SET ID = "not allowed";
			SELECT ID;
			CALL hrm_message('1102006', 'Roster', 'notallowed', SDate);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddSalary`;
DELIMITER |
CREATE PROCEDURE `spHRMAddSalary`(userid varchar(255),ID varchar(255),PayrollID varchar(255),Salary text, SK varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE D DATE;
	DECLARE CheckDate DATE;
	DECLARE L LONG DEFAULT 1;
	DECLARE PayrollType varchar(255);
	DECLARE CheckEmp INT DEFAULT(0);
	DECLARE LastDate DATE;
	DECLARE SNow DATE;
	DECLARE tz VARCHAR(20) DEFAULT('');

	SELECT Setting_Value INTO tz FROM hrm_setting WHERE Setting_Type = 'TimeZone' AND Setting_Name = 'TimeZone';
	SET SNow = convert_tz(now(), @@session.time_zone, tz);

	IF Salary != "" THEN
	
					UPDATE hrm_payroll_salary SET Salary_Status = 'Deactive' WHERE Salary_EmpID = ID;
					SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_salary(Salary_EmpID,Salary_PayrollID,Salary_Type,Salary_Amount,Salary_Status) VALUES ", Salary, ";");
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;

					SET @SQL1 = CONCAT("UPDATE hrm_payroll_salary SET Salary_Amount = ", SK," WHERE Salary_EmpID = '", ID, "' AND Salary_Status = 'Active';");
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;

					INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Salary', ID);

					SELECT ID;
					CALL hrm_message('1100901', 'Salary', 'create', ID);
							
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddSalaryAdjustment`;
DELIMITER |
CREATE PROCEDURE `spHRMAddSalaryAdjustment`(userid varchar(255),SValue text, SID varchar(255), SEmpID varchar(255), SSalary Double)
    DETERMINISTIC
BEGIN
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE Message VARCHAR(255);
	DECLARE SNow DATETIME;
	DECLARE tz VARCHAR(20) DEFAULT('');
	IF SValue != "" THEN
				SELECT Setting_Value INTO tz FROM hrm_setting WHERE Setting_Type = 'TimeZone' AND Setting_Name = 'TimeZone';
				SET SNow = convert_tz(now(), @@session.time_zone, tz);
				
				SELECT COUNT(*) INTO CheckExist FROM hrm_payroll_salary_adjustment WHERE adj_submitpayrollID = SID AND adj_empid = SEmpID;
				IF CheckExist <= 0 THEN
					SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_salary_adjustment(adj_submitpayrollID,adj_empid,adj_salary,adj_createdate) VALUES ", SValue, ";");
					SET @SQL1 = REPLACE(@SQL1, 'TempNow', SNow);
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;

					CALL spHRMAddLog(userid, 'insert', 'Salary Adjustment', CONCAT(SID, ", ", SEmpID, ", ", SSalary));

					SET Message = 'success';
					SELECT Message;
					CALL hrm_message_param3('1104801', 'SalaryAdjustment', 'create', SID, SEmpID, '');
				ELSE
					SET Message = 'exist';
					SELECT Message;
					CALL hrm_message_param3('1104804', 'SalaryAdjustment', 'exist', SID, SEmpID, '');
				END IF;					

	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddsEmployeeAllowance`;
DELIMITER |
CREATE PROCEDURE `spHRMAddsEmployeeAllowance`(userid varchar(255),SValue text, SLog text, SID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255) DEFAULT(0);
	IF SValue != "" THEN
				DELETE FROM hrm_payroll_allowance_employee WHERE  Allowance_ID = SID;
				SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_allowance_employee(Allowance_EmpID,Allowance_ID) VALUES ", SValue, ";");
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				CALL spHRMAddLog(userid, 'insert', 'Employee Leave Type', SLog);

				SET Message = 'success';
				CALL hrm_message('1100401', 'EmpAllowance', 'create', SID);
				SELECT Message;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddsEmployeeLeaveType`;
DELIMITER |
CREATE PROCEDURE `spHRMAddsEmployeeLeaveType`(userid varchar(255),SValue text, SLog text, SID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255) DEFAULT(0);
	IF SValue != "" THEN
				DELETE FROM hrm_timesheet_leave_type_employee WHERE Leave_TypeID = SID;
				SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_leave_type_employee(Leave_EmpID,Leave_TypeID) VALUES ", SValue, ";");
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Employee Leave Type', SLog);
				SET Message = 'success';
				CALL hrm_message('1101101', 'EmpLeaveType', 'create', SID);
				SELECT Message;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddShift`;
DELIMITER |
CREATE PROCEDURE `spHRMAddShift`(ShiftID varchar(255), Shift text, ShiftDetail text)
    DETERMINISTIC
BEGIN
	SET @SQL1 = CONCAT("INSERT INTO hrm_shift(ShiftID,ShiftName,ShiftType,ShiftDescription) VALUES(", Shift, "); ");
	PREPARE St FROM @SQL1;
	EXECUTE St;
	DEALLOCATE PREPARE St;
	CALL spHRMCheckInsertSync('hrm_shift', 'ShiftID', ShiftID, NULL, NULL, NULL ,NULL);
	
	IF ShiftDetail != "" THEN
		SET @SQL1 = CONCAT("DELETE FROM hrm_shift_detail WHERE ShiftID = '", ShiftID, "'; ");
		PREPARE St FROM @SQL1;
		EXECUTE St;
		DEALLOCATE PREPARE St;

		SET @SQL1 = CONCAT("INSERT INTO hrm_shift_detail(ShiftID,Main,ShiftDay,TimeIn1,TimeIn1To,TimeOut1,TimeOut1To,TimeIn2,TimeIn2To,TimeOut2,TimeOut2To,TimeIn3,TimeIn3To,TimeOut3,TimeOut3To,TimeIn4,TimeIn4To,TimeOut4,TimeOut4To) VALUES", ShiftDetail, "; ");
		PREPARE St FROM @SQL1;
		EXECUTE St;
		DEALLOCATE PREPARE St;

		CALL spHRMCheckInsertSync('hrm_shift', 'hrm_shift_detail', ShiftID, NULL, NULL, NULL ,NULL);
	END IF;
	

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddsRoster`;
DELIMITER |
CREATE PROCEDURE `spHRMAddsRoster`(userid varchar(255), SReplace tinyint, SFileName varchar(255), SValue text)
    DETERMINISTIC
BEGIN
	DECLARE message VARCHAR(255) DEFAULT('');
	IF SReplace <= 0 THEN
		SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_roster(Roster_Date,Roster_EmpID,Roster_ShiftID) VALUES ", SValue, " ON DUPLICATE KEY UPDATE Roster_EmpID = Roster_EmpID ,Roster_Date=Roster_Date;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
			
			IF SFileName != '' THEN
				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'import', 'Roster', SFileName);
				SET message = "success";
				SELECT message;
				CALL hrm_message('1102007', 'Roster', 'create', SFileName);
			ELSE
				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'import', 'Roster', userid);
				SET message = "success";
				SELECT message;
				CALL hrm_message('1102007', 'Roster', 'create', '');
			END IF;
	ELSE
		SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_roster(Roster_Date,Roster_EmpID,Roster_ShiftID) VALUES ", SValue, " ON DUPLICATE KEY UPDATE Roster_ShiftID = VALUES(Roster_ShiftID);");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
			IF SFileName != '' THEN
				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'import', 'Roster', SFileName);
				SET message = "success";
				SELECT message;
				CALL hrm_message('1102007', 'Roster', 'create', SFileName);
			ELSE
				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'import', 'Roster', userid);
				SET message = "success";
				SELECT message;
				CALL hrm_message('1102007', 'Roster', 'create', '');
			END IF;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddSubmitDetailAllowance`;
DELIMITER |
CREATE PROCEDURE `spHRMAddSubmitDetailAllowance`(SID varchar(255), SEmpID varchar(255), SBSalary float)
    DETERMINISTIC
BEGIN
	DECLARE PercentageType VARCHAR(20) DEFAULT('');

	SELECT Setting_Value INTO PercentageType FROM hrm_setting WHERE Setting_Type = 'Percentage' AND Setting_Name = 'Percentage';

	DELETE FROM hrm_payroll_submit_payroll_detail_allowance WHERE SubmitPayroll_ID=SID AND SubmitPayroll_EmpID=SEmpID;
	INSERT INTO hrm_payroll_submit_payroll_detail_allowance(SubmitPayroll_ID,SubmitPayroll_EmpID,SubmitPayroll_AllowanceID,SubmitPayroll_AllowancePayType,SubmitPayroll_AllowancePayAmount,SubmitPayroll_TotalAllowancePayAmount)
	(SELECT SID, SEmpID,a.Allowance_ID, a.Allowance_PayType, a.Allowance_PayAmount, 
	IF(LOWER(a.Allowance_PayType) ='fixed',a.Allowance_PayAmount,IF(LOWER(a.Allowance_PayType) ='percent', COALESCE(IF(PercentageType='Salary', (SBSalary * (a.Allowance_PayAmount/100)), (PercentageType * (a.Allowance_PayAmount/100))), 0), 0)) AS 'Allowance_PayAmount' 
	from hrm_payroll_allowance_employee ae INNER JOIN hrm_payroll_allowance a ON a.Allowance_ID = ae.Allowance_ID WHERE ae.Allowance_EmpID=SEmpID);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddSubmitDetailBonus`;
DELIMITER |
CREATE PROCEDURE `spHRMAddSubmitDetailBonus`(SID varchar(255), SEmpID varchar(255), SBSalary float)
    DETERMINISTIC
BEGIN
	DECLARE PercentageType VARCHAR(20) DEFAULT('');
	DECLARE StartDate DATE;
	DECLARE EndDate DATE;

	SELECT Setting_Value INTO PercentageType FROM hrm_setting WHERE Setting_Type = 'Percentage' AND Setting_Name = 'Percentage';

	SELECT SubmitPayroll_StartDate, SubmitPayroll_EndDate into StartDate,EndDate FROM hrm_payroll_submit_payroll WHERE SubmitPayroll_ID = SID;


	DELETE FROM hrm_payroll_submit_payroll_detail_bonus WHERE SubmitPayroll_ID=SID AND SubmitPayroll_BonusEmpID=SEmpID;

	INSERT INTO hrm_payroll_submit_payroll_detail_bonus(SubmitPayroll_ID,SubmitPayroll_BonusEmpID,SubmitPayroll_BonusID,SubmitPayroll_BonusPayType,SubmitPayroll_BonusPayAmount,SubmitPayroll_TotalBonusPayAmount)
	(SELECT SID, SEmpID, bd.Bonus_ID, Bonus_PayType, Bonus_PayAmount,
	IF(LOWER(bd.Bonus_PayType)='fixed',bd.Bonus_PayAmount,IF(LOWER(bd.Bonus_PayType)='percent', COALESCE(IF(PercentageType='Salary',(SBSalary * (bd.Bonus_PayAmount/100)),(PercentageType*(bd.Bonus_PayAmount/100))),0),0))
	FROM hrm_payroll_bonus_detail bd
	INNER JOIN hrm_payroll_bonus b ON(b.Bonus_ID = bd.Bonus_ID AND b.Bonus_Date >= StartDate AND b.Bonus_Date <= EndDate)
	WHERE bd.Bonus_EmpID = SEmpID);

	UPDATE hrm_payroll_bonus_detail AS bd INNER JOIN hrm_payroll_bonus AS b ON(b.Bonus_ID = bd.Bonus_ID AND b.Bonus_Date >= StartDate AND b.Bonus_Date <= EndDate)
	SET Bonus_PayStatus = 'Paid' 
	WHERE Bonus_EmpID = SEmpID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddSubmitDetailDeduction`;
DELIMITER |
CREATE PROCEDURE `spHRMAddSubmitDetailDeduction`(SID varchar(255), SEmpID varchar(255), SBSalary float)
    DETERMINISTIC
BEGIN
	DECLARE PercentageType VARCHAR(20) DEFAULT('');
	DECLARE StartDate DATE;
	DECLARE EndDate DATE;

	SELECT Setting_Value INTO PercentageType FROM hrm_setting WHERE Setting_Type = 'Percentage' AND Setting_Name = 'Percentage';

	SELECT SubmitPayroll_StartDate, SubmitPayroll_EndDate into StartDate,EndDate FROM hrm_payroll_submit_payroll WHERE SubmitPayroll_ID = SID;

	DELETE FROM hrm_payroll_submit_payroll_detail_deduction WHERE SubmitPayroll_ID=SID AND SubmitPayroll_DeductionEmpID=SEmpID;

	INSERT INTO hrm_payroll_submit_payroll_detail_deduction(SubmitPayroll_ID,SubmitPayroll_DeductionEmpID,SubmitPayroll_DeductionID,SubmitPayroll_DeductionAmount,SubmitPayroll_TotalDeductionAmount,SubmitPayroll_DeductionLine)
	(SELECT SID, SEmpID, de.Deduction_ID, ded.dd_amount, ded.dd_amount, MIN(dd_line)	
	FROM hrm_payroll_deduction de
	LEFT JOIN hrm_payroll_deduction_detail ded ON(de.Deduction_ID = ded.dd_id)
	WHERE de.Deduction_EmpID = SEmpID AND LOWER(de.Deduction_Status) = 'approved' AND LOWER(ded.dd_status) = 'open'
	GROUP BY de.Deduction_ID
	ORDER BY de.Deduction_ID,ded.dd_line);

	CALL spHRMAddSubmitDetailDeductionSub(SEmpID);
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddSubmitDetailDeductionSub`;
DELIMITER |
CREATE PROCEDURE `spHRMAddSubmitDetailDeductionSub`(SEmpID varchar(255))
    DETERMINISTIC
BEGIN
		DECLARE v_finished INTEGER DEFAULT 0;
		DECLARE var_DedID varchar(255) DEFAULT "";
		DECLARE var_DedLine TINYINT DEFAULT 0;
		DEClARE CustID_Cursor CURSOR FOR SELECT de.Deduction_ID, MIN(dd_line)	FROM hrm_payroll_deduction de LEFT JOIN hrm_payroll_deduction_detail ded ON(de.Deduction_ID = ded.dd_id)
																																					WHERE de.Deduction_EmpID = SEmpID AND LOWER(de.Deduction_Status) = 'approved' AND LOWER(ded.dd_status) = 'open'
																																					GROUP BY de.Deduction_ID
																																					ORDER BY de.Deduction_ID,ded.dd_line;
		DECLARE CONTINUE HANDLER
		FOR NOT FOUND SET v_finished = 1;
		OPEN CustID_Cursor;
			GetCustID: LOOP
				FETCH CustID_Cursor INTO var_DedID, var_DedLine;
				IF v_finished = 1 THEN
					LEAVE GetCustID;
				END IF;
				UPDATE hrm_payroll_deduction_detail SET dd_status = 'Deducted' WHERE dd_id = var_DedID AND dd_line = var_DedLine;
			END LOOP GetCustID;
		CLOSE CustID_Cursor;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddSubmitDetailLeave`;
DELIMITER |
CREATE PROCEDURE `spHRMAddSubmitDetailLeave`(SID varchar(255), SEmpID varchar(255), SBSalary float)
    DETERMINISTIC
BEGIN
	DECLARE PercentageType VARCHAR(20) DEFAULT('');
	DECLARE StartDate DATE;
	DECLARE EndDate DATE;
	DECLARE AmtWorkingDay FLOAT DEFAULT(0);
	DECLARE AmtWorkingHourPerDay FLOAT DEFAULT(0);

	SELECT Setting_Value INTO PercentageType FROM hrm_setting WHERE Setting_Type = 'Percentage' AND Setting_Name = 'Percentage';

	SELECT SubmitPayroll_StartDate, SubmitPayroll_EndDate, Payroll_AmtWorkingDay, Payroll_AmtWorkingHourPerDay into StartDate,EndDate,AmtWorkingDay,AmtWorkingHourPerDay  FROM hrm_payroll_submit_payroll LEFT JOIN hrm_payroll ON(SubmitPayroll_PayrollID = Payroll_ID) WHERE SubmitPayroll_ID = SID;

	DELETE FROM hrm_payroll_submit_payroll_detail_leave WHERE SubmitPayroll_ID=SID AND SubmitPayroll_EmpID=SEmpID;

	INSERT INTO hrm_payroll_submit_payroll_detail_leave(SubmitPayroll_ID,SubmitPayroll_EmpID,SubmitPayroll_LeaveID,SubmitPayroll_LeaveTypeID,SubmitPayroll_LeaveTypePayType,SubmitPayroll_LeaveTypePayAmount,SubmitPayroll_TotalLeaveTypePayAmount)
	(SELECT SID, SEmpID, l.Leave_ID, l.LeaveD_TypeID, lt.LeaveType_PayType, lt.LeaveType_PayAmount,
		COALESCE(IF(LOWER(l.LeaveD_Duration) = 'hourly', 
								IF(LOWER(lt.LeaveType_PayType) = 'fixed hourly', lt.LeaveType_PayAmount * l.Leave_Total, 
								IF(LOWER(lt.LeaveType_PayType) = 'percent hourly', IF(PercentageType = 'Salary', (SBSalary * (lt.LeaveType_PayAmount/100)) * l.Leave_Total, (PercentageType * (lt.LeaveType_PayAmount/100)) * l.Leave_Total), 
								IF(LOWER(lt.LeaveType_PayType) = 'hourly rate', ((SBSalary / AmtWorkingDay) / AmtWorkingHourPerDay) * l.Leave_Total, 0.0))), 
						if(LOWER(l.LeaveD_Duration) = 'full day', 
								IF(LOWER(lt.LeaveType_PayType) = 'fixed dialy', lt.LeaveType_PayAmount * COALESCE(l.Leave_Total, 0), 
								IF(LOWER(lt.LeaveType_PayType) = 'percent dialy', COALESCE((IF(PercentageType = 'Salary', SBSalary , PercentageType)* (lt.LeaveType_PayAmount/100)) * l.Leave_Total, 0), 
								IF(LOWER(lt.LeaveType_PayType) = 'dialy rate', COALESCE((SBSalary/AmtWorkingDay) * l.Leave_Total, 0), 0.0))), 0.00)), 0)

	from (SELECT Leave_ID,Leave_EmpID,Leave_Status,LeaveD_Date,LeaveD_Duration,LeaveD_TypeID,LeaveD_TimeFrom,LeaveD_TimeTo,Leave_Total,Leave_Amount
								FROM hrm_timesheet_leave l
								LEFT JOIN hrm_timesheet_leave_detail ld ON(l.Leave_ID = ld.LeaveD_ID)
								WHERE LOWER(l.Leave_Status) IN('approved','approved & deducted') AND ld.LeaveD_Date >= StartDate AND ld.LeaveD_Date <= EndDate) l
	LEFT JOIN hrm_timesheet_leave_type lt ON l.LeaveD_TypeID = lt.LeaveType_ID AND LOWER(LeaveType_PayStatus) = 'unpaid'
	WHERE l.Leave_EmpID = SEmpID);
	
	-- UPDATE hrm_timesheet_leave AS l LEFT JOIN hrm_timesheet_leave_type AS lt ON l.Leave_TypeID = lt.LeaveType_ID AND LOWER(LeaveType_PayStatus) = 'unpaid'
	-- SET Leave_Status = 'approved & deducted' 
	-- WHERE l.Leave_EmpID = SEmpID AND LOWER(Leave_Status) IN('approved','approved & deducted')  AND ((l.Leave_From >= StartDate AND l.Leave_From <= EndDate) OR (l.Leave_To >= StartDate AND l.Leave_To <= EndDate));
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddSubmitDetailOvertime`;
DELIMITER |
CREATE PROCEDURE `spHRMAddSubmitDetailOvertime`(SID varchar(255), SEmpID varchar(255), SBSalary float)
    DETERMINISTIC
BEGIN
	DECLARE PercentageType VARCHAR(20) DEFAULT('');
	DECLARE StartDate DATE;
	DECLARE EndDate DATE;
	DECLARE AmtWorkDay FLOAT DEFAULT(0);
	DECLARE AmtWorkHourPerDay FLOAT DEFAULT(0);

	SELECT Setting_Value INTO PercentageType FROM hrm_setting WHERE Setting_Type = 'Percentage' AND Setting_Name = 'Percentage';

	SELECT SubmitPayroll_StartDate, SubmitPayroll_EndDate, p.Payroll_AmtWorkingDay, p.Payroll_AmtWorkingHourPerDay into StartDate,EndDate,AmtWorkDay,AmtWorkHourPerDay FROM hrm_payroll_submit_payroll s LEFT JOIN hrm_payroll p ON(s.SubmitPayroll_PayrollID = p.Payroll_ID) WHERE SubmitPayroll_ID = SID;

	DELETE FROM hrm_payroll_submit_payroll_detail_overtime WHERE SubmitPayroll_ID=SID AND SubmitPayroll_OTEmpID=SEmpID;

	INSERT INTO hrm_payroll_submit_payroll_detail_overtime(SubmitPayroll_ID,SubmitPayroll_OTID,SubmitPayroll_OTEmpID,SubmitPayroll_OTDate,SubmitPayroll_TotalOTPayAmount)
	(SELECT SID,o.Overtime_ID,o.od_empid,o.od_date,COALESCE(IF(LOWER(o.Overtime_Type) = 'fixed per hourly', (o.Overtime_Amount * o.od_multiplier)* (IF(o.Att_OvertimeOut >= o.od_timeout, o.od_hours, HOUR(TIMEDIFF(o.Att_OvertimeOut,o.od_timein)))),
																				IF(LOWER(o.Overtime_Type) = 'pro-rata based', ((IF( (IF(o.Att_OvertimeOut >= o.od_timeout, o.od_hours, HOUR(TIMEDIFF(o.Att_OvertimeOut,o.od_timein)))) > AmtWorkHourPerDay, (SBSalary / AmtWorkDay) * o.od_multiplier, (IF(o.Att_OvertimeOut >= o.od_timeout, o.od_hours, HOUR(TIMEDIFF(o.Att_OvertimeOut,o.od_timein)))) * ((SBSalary / AmtWorkDay)/AmtWorkHourPerDay))) * o.od_multiplier), 0.00)), 0)
							FROM (SELECT o.Overtime_ID,o.Overtime_Type,o.Overtime_Amount,od.od_date,od.od_timein,od.od_timeout,od.od_hours,od.od_multiplier,ode.od_empid,att.Att_OvertimeIn,att.Att_OvertimeOut
										FROM hrm_payroll_overtime o
										LEFT JOIN hrm_payroll_overtime_detail od ON(o.Overtime_ID = od.od_id)
										LEFT JOIN hrm_payroll_overtime_detail_employee ode ON(o.Overtime_ID = ode.od_id)
										INNER JOIN hrm_timesheet_attendance att ON(ode.od_empid = att.Att_EmpID AND od.od_date = att.Att_Date AND att.Att_OvertimeIn <= od.od_timein)
										WHERE LOWER(o.Overtime_Status) IN ('approved','approved & paid') AND LOWER(ode.od_status) = 'open') o 
		WHERE o.od_empid = SEmpID AND o.od_date >= StartDate AND o.od_date <= EndDate);

	UPDATE hrm_payroll_overtime_detail_employee SET od_status = 'Paid'
		WHERE od_empid = SEmpID AND od_id  IN 
		(SELECT o.Overtime_ID
								FROM (SELECT o.Overtime_ID,o.Overtime_Type,o.Overtime_Amount,od.od_date,od.od_timein,od.od_timeout,od.od_hours,od.od_multiplier,ode.od_empid,att.Att_OvertimeIn,att.Att_OvertimeOut
											FROM hrm_payroll_overtime o
											LEFT JOIN hrm_payroll_overtime_detail od ON(o.Overtime_ID = od.od_id)
											LEFT JOIN hrm_payroll_overtime_detail_employee ode ON(o.Overtime_ID = ode.od_id)
											INNER JOIN hrm_timesheet_attendance att ON(ode.od_empid = att.Att_EmpID AND od.od_date = att.Att_Date AND att.Att_OvertimeIn <= od.od_timein)
											WHERE LOWER(o.Overtime_Status) IN ('approved','approved & paid') AND LOWER(ode.od_status) = 'open') o 
		WHERE o.od_empid = SEmpID AND o.od_date >= StartDate AND o.od_date <= EndDate);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddSubmitPayroll`;
DELIMITER |
CREATE PROCEDURE `spHRMAddSubmitPayroll`(userid varchar(255),SID varchar(255), SValue Text, SAP Text, SAPD Text)
    DETERMINISTIC
BEGIN
	DECLARE message varchar(255) DEFAULT('');
	DECLARE ID varchar(255) DEFAULT('');
	DECLARE SNow DATETIME;
	DECLARE tz VARCHAR(20) DEFAULT('');
	DECLARE vendor VARCHAR(255) DEFAULT('');
	DECLARE CashAcc VARCHAR(255) DEFAULT('');
	DECLARE JID INT DEFAULT(0);

	IF SValue != "" THEN	
			
			SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_submit_payroll_detail(SubmitPayroll_ID,SubmitPayroll_EmpID,SubmitPayroll_SalaryType,SubmitPayroll_BasicSalary,SubmitPayroll_AllowancePayAmount,SubmitPayroll_BonusPayAmount,SubmitPayroll_OTPayAmount,SubmitPayroll_DeductionAmount,SubmitPayroll_LeaveDeductAmount,SubmitPayroll_LateDeductAmount,SubmitPayroll_AbsentDeductAmount,SubmitPayroll_TaxDeductAmount,SubmitPayroll_NetSalary) VALUES ", SValue, " ON DUPLICATE KEY UPDATE SubmitPayroll_BasicSalary=SubmitPayroll_BasicSalary, SubmitPayroll_AllowancePayAmount=SubmitPayroll_AllowancePayAmount, SubmitPayroll_BonusPayAmount=SubmitPayroll_BonusPayAmount, SubmitPayroll_OTPayAmount=SubmitPayroll_OTPayAmount, SubmitPayroll_DeductionAmount=SubmitPayroll_DeductionAmount, SubmitPayroll_LeaveDeductAmount=SubmitPayroll_LeaveDeductAmount, SubmitPayroll_LateDeductAmount=SubmitPayroll_LateDeductAmount, SubmitPayroll_AbsentDeductAmount=SubmitPayroll_AbsentDeductAmount, SubmitPayroll_TaxDeductAmount=SubmitPayroll_TaxDeductAmount, SubmitPayroll_NetSalary=SubmitPayroll_NetSalary;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Submit Payroll Detail', SID);

			CALL spHRMGetTblNumberPrefix("AP-PY", ID);

			SELECT Setting_Value INTO tz FROM hrm_setting WHERE Setting_Type = 'TimeZone' AND Setting_Name = 'TimeZone';

			SET SNow = convert_tz(now(), @@session.time_zone, tz);

			SELECT Setting_Value INTO vendor FROM hrm_setting WHERE Setting_Type = 'SubmitPayroll' AND Setting_Name = 'Vendor';
	
			SELECT COALESCE(MAX(JID), 0)+1 INTO JID FROM tblpayment;
			
			SET @SQL1 = CONCAT("INSERT INTO tblpayment(PmtID,PmtDate,PeriodM,PeriodY,PmtReference,PmtType,VendID,CashAccNo,TotalDiscount,TotalPmtAmount,PostStatus,JID,Remark,ClassID,TotalCash,AppliedStatus,AppliedAmt) VALUES ", SAP, ";");
			SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
			SET @SQL1 = REPLACE(@SQL1, 'Temp_Date', SNow);
			SET @SQL1 = REPLACE(@SQL1, 'Temp_M', MONTH(SNow));
			SET @SQL1 = REPLACE(@SQL1, 'Temp_Y', YEAR(SNow));
			SET @SQL1 = REPLACE(@SQL1, 'Temp_Vendor', vendor);
			SET @SQL1 = REPLACE(@SQL1, 'Temp_JID', JID);
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			SET @SQL1 = CONCAT("INSERT INTO tblpaymentdetails(PmtID,LineNo,PurID,Discount,ExpAccID,TransDescription,PmtAmount,PostStatus,JID,ClassID,AppliedAmt) VALUES ", SAPD, ";");
			SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
			SET @SQL1 = REPLACE(@SQL1, 'Temp_JID', JID);
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			CALL spHRMUpdateTblNumberPrefix("AP-PY");

			SELECT ID;
			SET message = "success";
			SELECT message;

			CALL hrm_message('1102301', 'SubmitPayroll', 'create', ID);
		
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddTimesheetLeaveType`;
DELIMITER |
CREATE PROCEDURE `spHRMAddTimesheetLeaveType`(userid varchar(255),LeaveTypeName varchar(255),LeaveType text, CValue2 text)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE tz VARCHAR(20) DEFAULT('');

	IF LeaveType != "" THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_timesheet_leave_type WHERE LOWER(LeaveType_Name) = LeaveTypeName;

		IF CheckExist <= 0 THEN
			CALL spHRMGetNumberPrefix("LeaveType", ID);
		
			SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_leave_type(LeaveType_ID,LeaveType_Name,LeaveType_PayStatus,LeaveType_Year,LeaveType_AmountAllowed,LeaveType_GenderRestriction,LeaveType_PayType,LeaveType_PayAmount,LeaveType_BaseBalance) VALUES ", LeaveType, ";");
			SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
			INSERT INTO hrm_emp_grade VALUES(@SQL1);
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			IF CValue2 != "" THEN
					SELECT Setting_Value INTO tz FROM hrm_setting WHERE Setting_Type = 'TimeZone' AND Setting_Name = 'TimeZone';

					SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_leave_type_history(LeaveType_ID,LeaveType_Date,LeaveType_PayStatus,LeaveType_Year,LeaveType_AmountAllowed,LeaveType_GenderRestriction,LeaveType_PayType,LeaveType_PayAmount) VALUES ", CValue2, ";");
					SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
					SET @SQL1 = REPLACE(@SQL1, 'Temp_Now',DATE_FORMAT(convert_tz(now(), @@session.time_zone, tz), '%Y-%m-%d'));
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;
			END IF;

			CALL spHRMUpdateNumberPrefix("LeaveType");

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'Leave Type', ID);

			SELECT ID;
			CALL hrm_message('1101201', 'LeaveType', 'create', ID);
		ELSE
			SET ID = "exist";
			SELECT ID;
			CALL hrm_message('1101204', 'LeaveType', 'exist', LeaveTypeName);
		END IF;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddUser`;
DELIMITER |
CREATE PROCEDURE `spHRMAddUser`(userid varchar(255), SID varchar(255), SEmpID varchar(255), SValue text, SValue1 text)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);

	SELECT COUNT(*) INTO CheckExist FROM ame_user WHERE var_id = SID;

	IF SValue != "" AND CheckExist <= 0 THEN	
	
				SET @SQL1 = CONCAT("INSERT INTO ame_user(var_id,var_name,var_hrm_utype,var_pwd,var_empid,tin_inactive,var_hrm_role) VALUES ", SValue, ";");
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				IF SEmpID != "" THEN
						DELETE FROM ame_user_app WHERE var_id = SID;
				END IF;

				SET @SQL1 = CONCAT("INSERT INTO ame_user_app(var_id,var_appid) VALUES ", SValue1, ";");
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'User', SID);
				SET ID = SID;
				SELECT ID;
				CALL hrm_message('1104401', 'User', 'create', SID);
	ELSE
				SET ID = 'exist'; 
				SELECT ID;
				CALL hrm_message('1104404', 'User', 'exist', SID);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAddWorkShift`;
DELIMITER |
CREATE PROCEDURE `spHRMAddWorkShift`(userid varchar(255),SName varchar(255),SValue text, SValueDetail text)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);
	DECLARE exist INT DEFAULT(0);

	SELECT COUNT(*) INTO exist FROM hrm_timesheet_workshift WHERE LOWER(Shift_Name) = SName;

	IF SValue != "" AND exist <=0 THEN	
				CALL spHRMGetNumberPrefix("WorkShift", ID);
	
				SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_workshift(Shift_ID,Shift_Name,Shift_Type,Shift_Description) VALUES ", SValue, ";");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_workshift_detail(Shift_ID,Shift_Day,Shift_TotalWorkHour,Shift_TotalWorkOvertime,Shift_TimeIn1,Shift_TimeInPeriod1,Shift_TimeOut1,Shift_TimeOutPeriod1,Shift_TimeIn2,Shift_TimeInPeriod2,Shift_TimeOut2,Shift_TimeOutPeriod2,Shift_TimeIn3,Shift_TimeInPeriod3,Shift_TimeOut3,Shift_TimeOutPeriod3,Shift_TimeIn4,Shift_TimeInPeriod4,Shift_TimeOut4,Shift_TimeOutPeriod4,Shift_TimeIn5,Shift_TimeInPeriod5,Shift_TimeOut5,Shift_TimeOutPeriod5,Shift_TimeInOvertime,Shift_TimeOutOvertime,Shift_TimeIn1LateDuration,Shift_TimeOut1LateDuration,Shift_TimeIn2LateDuration,Shift_TimeOut2LateDuration,Shift_TimeIn3LateDuration,Shift_TimeOut3LateDuration,Shift_TimeIn4LateDuration,Shift_TimeOut4LateDuration,Shift_TimeIn5LateDuration,Shift_TimeOut5LateDuration,Shift_TimeBreak1,Shift_TimeBreak2,Shift_TimeBreak3,Shift_TimeBreak4,Shift_TimeBreak5) VALUES ", SValueDetail, ";");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', ID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				CALL spHRMUpdateNumberPrefix("WorkShift");

				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'insert', 'WorkShift', ID);

				SELECT ID;
				CALL hrm_message('1101901', 'WorkShift', 'create', ID);

	ELSE
		SET ID = "exist";
		SELECT ID;
		CALL hrm_message('1101904', 'WorkShift', 'exist', SName);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAttendanceHolidayAdd`;
DELIMITER |
CREATE PROCEDURE `spHRMAttendanceHolidayAdd`(SType varchar(255), SBranchID varchar(255), SDepartment varchar(255), SFrom Date, STo Date)
    DETERMINISTIC
BEGIN
	DECLARE SEmpID VARCHAR(255) DEFAULT('');
	DECLARE done INT DEFAULT FALSE;
  DECLARE cursor_i CURSOR FOR SELECT var_id FROM ame_mt_emp e WHERE IF(SType = 'Branch' OR SType = 'Branch & Department', e.var_hrm_branch_id = SBranchID, TRUE) AND IF(SType = 'Department' OR SType = 'Branch & Department', e.var_hrm_department_id = SDepartment, TRUE);
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
  OPEN cursor_i;
  read_loop: LOOP
    FETCH cursor_i INTO SEmpID;
    IF done THEN
      LEAVE read_loop;
    END IF;
		CALL spHRMAttendanceHolidayEmp(SEmpID, SFrom, STo);   
  END LOOP;
  CLOSE cursor_i;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAttendanceHolidayAddAll`;
DELIMITER |
CREATE PROCEDURE `spHRMAttendanceHolidayAddAll`(SFrom Date, STo Date)
    DETERMINISTIC
BEGIN
	DECLARE SEmpID VARCHAR(255) DEFAULT('');
	DECLARE done INT DEFAULT FALSE;
  DECLARE cursor_i CURSOR FOR SELECT var_id FROM ame_mt_emp e WHERE e.var_hrm_fpid <> '' OR e.var_hrm_fpid <> NULL;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
  OPEN cursor_i;
  read_loop: LOOP
    FETCH cursor_i INTO SEmpID;
		IF done THEN
      LEAVE read_loop;
    END IF;
    CALL spHRMAttendanceHolidayEmp(SEmpID, SFrom, STo);		
  END LOOP;
  CLOSE cursor_i;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAttendanceHolidayDelete`;
DELIMITER |
CREATE PROCEDURE `spHRMAttendanceHolidayDelete`(SType varchar(255), SBranchID varchar(255), SDepartment varchar(255), SFrom Date, STo Date)
    DETERMINISTIC
BEGIN
	DECLARE SEmpID VARCHAR(255) DEFAULT('');
	DECLARE done INT DEFAULT FALSE;
  DECLARE cursor_i CURSOR FOR SELECT var_id FROM ame_mt_emp e WHERE IF(SType = 'Branch' OR SType = 'Branch & Department', e.var_hrm_branch_id = SBranchID, TRUE) AND IF(SType = 'Department' OR SType = 'Branch & Department', e.var_hrm_department_id = SDepartment, TRUE);
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
  OPEN cursor_i;
  read_loop: LOOP
    FETCH cursor_i INTO SEmpID;
    IF done THEN
      LEAVE read_loop;
    END IF;
		CALL spHRMAttendanceHolidayDeleteEmp(SEmpID, SFrom, STo);   
  END LOOP;
  CLOSE cursor_i;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAttendanceHolidayDeleteAll`;
DELIMITER |
CREATE PROCEDURE `spHRMAttendanceHolidayDeleteAll`(SFrom Date, STo Date)
    DETERMINISTIC
BEGIN
	DECLARE SEmpID VARCHAR(255) DEFAULT('');
	DECLARE done INT DEFAULT FALSE;
  DECLARE cursor_i CURSOR FOR SELECT var_id FROM ame_mt_emp e WHERE e.var_hrm_fpid <> '' OR e.var_hrm_fpid <> NULL;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
  OPEN cursor_i;
  read_loop: LOOP
    FETCH cursor_i INTO SEmpID;
    IF done THEN
      LEAVE read_loop;
    END IF;
    CALL spHRMAttendanceHolidayDeleteEmp(SEmpID, SFrom, STo);
  END LOOP;
  CLOSE cursor_i;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAttendanceHolidayDeleteEmp`;
DELIMITER |
CREATE PROCEDURE `spHRMAttendanceHolidayDeleteEmp`(SEmpID varchar(255),SFrom Date, STo Date)
    DETERMINISTIC
BEGIN
	DECLARE ShiftType VARCHAR(255) DEFAULT('');	
	DECLARE ShiftID VARCHAR(255) DEFAULT('');	

	DECLARE Shift_ID VARCHAR(255);
	DECLARE Shift_Day VARCHAR(255);
	DECLARE Shift_TimeIn1 TIME;
	DECLARE Shift_TimeInPeriod1 TIME;
	DECLARE Shift_TimeOut1 TIME;
	DECLARE Shift_TimeOutPeriod1 TIME;
	DECLARE Shift_TimeIn2 TIME;
	DECLARE Shift_TimeInPeriod2 TIME;
	DECLARE Shift_TimeOut2 TIME;
	DECLARE Shift_TimeOutPeriod2 TIME;
	DECLARE Shift_TimeIn3 TIME;
	DECLARE Shift_TimeInPeriod3 TIME;
	DECLARE Shift_TimeOut3 TIME;
	DECLARE Shift_TimeOutPeriod3 TIME;
	DECLARE Shift_TimeIn4 TIME;
	DECLARE Shift_TimeInPeriod4 TIME;
	DECLARE Shift_TimeOut4 TIME;
	DECLARE Shift_TimeOutPeriod4 TIME;
	DECLARE Shift_TimeIn5 TIME;
	DECLARE Shift_TimeInPeriod5 TIME;
	DECLARE Shift_TimeOut5 TIME;
	DECLARE Shift_TimeOutPeriod5 TIME;
	DECLARE Shift_TimeInOvertime TIME;
	DECLARE Shift_TimeOutOvertime TIME;

	DECLARE FPID VARCHAR(255)DEFAULT('');
	DECLARE FPDate DATE;
	DECLARE In1 TIME DEFAULT('00:00:00');
	DECLARE In2 TIME DEFAULT('00:00:00');
	DECLARE In3 TIME DEFAULT('00:00:00');
	DECLARE In4 TIME DEFAULT('00:00:00');
	DECLARE In5 TIME DEFAULT('00:00:00');
	DECLARE Out1 TIME DEFAULT('00:00:00');
	DECLARE Out2 TIME DEFAULT('00:00:00');
	DECLARE Out3 TIME DEFAULT('00:00:00');
	DECLARE Out4 TIME DEFAULT('00:00:00');
	DECLARE Out5 TIME DEFAULT('00:00:00');
	DECLARE OverIn TIME DEFAULT('00:00:00');
	DECLARE OverOut TIME DEFAULT('00:00:00');
	DECLARE O1 TIME DEFAULT('00:00:00');
	DECLARE O2 TIME DEFAULT('00:00:00');
	
	DECLARE TempDate DATE;
	DECLARE CheckExist TINYINT DEFAULT(0);
	
	SET TempDate = SFrom;

	SELECT e.var_hrm_shift_type,e.var_hrm_shift_id,e.var_hrm_fpid INTO ShiftType,ShiftID,FPID FROM ame_mt_emp e WHERE e.var_id = SEmpID;

	WHILE TempDate <= DATE(STo) DO

	SET In1 = '00:00:00';
	SET In2 = '00:00:00';
	SET In3 = '00:00:00';
	SET In4 = '00:00:00';
	SET In5 = '00:00:00';
	SET Out1 = '00:00:00';
	SET Out2 = '00:00:00';
	SET Out3 = '00:00:00';
	SET Out4 = '00:00:00';
	SET Out5 = '00:00:00';

		SELECT COUNT(*) INTO CheckExist FROM  hrm_timesheet_attendance att WHERE att.Att_FPID = FPID AND att.Att_Date = TempDate;
		IF CheckExist > 0 THEN
			SELECT Att_FPID,Att_Date,Att_In1,Att_Out1,Att_In2,Att_Out2,Att_In3,Att_Out3,Att_In4,Att_Out4,Att_In5,Att_Out5,Att_OvertimeIn,Att_OvertimeOut,Att_Other1,Att_Other2 INTO FPID,FPDate,In1,Out1,In2,Out2,In3,Out3,In4,Out4,In5,Out5,OverIn,OverOut,O1,O2 FROM hrm_timesheet_attendance att WHERE att.Att_FPID = FPID AND att.Att_Date = TempDate;
		END IF;
		IF LOWER(ShiftType) = 'normal' THEN
			SELECT wd.Shift_ID,wd.Shift_Day,wd.Shift_TimeIn1,wd.Shift_TimeInPeriod1,wd.Shift_TimeOut1,wd.Shift_TimeOutPeriod1,wd.Shift_TimeIn2,wd.Shift_TimeInPeriod2,wd.Shift_TimeOut2,wd.Shift_TimeOutPeriod2,wd.Shift_TimeIn3,wd.Shift_TimeInPeriod3,wd.Shift_TimeOut3,wd.Shift_TimeOutPeriod3,wd.Shift_TimeIn4,wd.Shift_TimeInPeriod4,wd.Shift_TimeOut4,wd.Shift_TimeOutPeriod4,wd.Shift_TimeIn5,wd.Shift_TimeInPeriod5,wd.Shift_TimeOut5,wd.Shift_TimeOutPeriod5,wd.Shift_TimeInOvertime,wd.Shift_TimeOutOvertime INTO Shift_ID, Shift_Day, Shift_TimeIn1, Shift_TimeInPeriod1, Shift_TimeOut1, Shift_TimeOutPeriod1, Shift_TimeIn2, Shift_TimeInPeriod2, Shift_TimeOut2, Shift_TimeOutPeriod2, Shift_TimeIn3, Shift_TimeInPeriod3, Shift_TimeOut3, Shift_TimeOutPeriod3, Shift_TimeIn4, Shift_TimeInPeriod4, Shift_TimeOut4, Shift_TimeOutPeriod4, Shift_TimeIn5, Shift_TimeInPeriod5, Shift_TimeOut5, Shift_TimeOutPeriod5, Shift_TimeInOvertime, Shift_TimeOutOvertime FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID = ShiftID AND LOWER(wd.Shift_Day) = LOWER(DAYNAME(TempDate));
		ELSE
			SELECT wd.Shift_ID,wd.Shift_Day,wd.Shift_TimeIn1,wd.Shift_TimeInPeriod1,wd.Shift_TimeOut1,wd.Shift_TimeOutPeriod1,wd.Shift_TimeIn2,wd.Shift_TimeInPeriod2,wd.Shift_TimeOut2,wd.Shift_TimeOutPeriod2,wd.Shift_TimeIn3,wd.Shift_TimeInPeriod3,wd.Shift_TimeOut3,wd.Shift_TimeOutPeriod3,wd.Shift_TimeIn4,wd.Shift_TimeInPeriod4,wd.Shift_TimeOut4,wd.Shift_TimeOutPeriod4,wd.Shift_TimeIn5,wd.Shift_TimeInPeriod5,wd.Shift_TimeOut5,wd.Shift_TimeOutPeriod5,wd.Shift_TimeInOvertime,wd.Shift_TimeOutOvertime INTO Shift_ID, Shift_Day, Shift_TimeIn1, Shift_TimeInPeriod1, Shift_TimeOut1, Shift_TimeOutPeriod1, Shift_TimeIn2, Shift_TimeInPeriod2, Shift_TimeOut2, Shift_TimeOutPeriod2, Shift_TimeIn3, Shift_TimeInPeriod3, Shift_TimeOut3, Shift_TimeOutPeriod3, Shift_TimeIn4, Shift_TimeInPeriod4, Shift_TimeOut4, Shift_TimeOutPeriod4, Shift_TimeIn5, Shift_TimeInPeriod5, Shift_TimeOut5, Shift_TimeOutPeriod5, Shift_TimeInOvertime, Shift_TimeOutOvertime FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID = (SELECT Roster_ShiftID FROM hrm_timesheet_roster WHERE Roster_Date = TempDate AND Roster_EmpID = SEmpID);
		END IF;


		IF CheckExist	> 0 THEN
			UPDATE hrm_timesheet_attendance SET 
			Att_In1= IF(Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Att_In1 = '00:00:02', '00:00:00', Att_In1),
			Att_Out1=IF(Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Att_Out1 = '00:00:02', '00:00:00', Att_Out1),
			Att_In2=IF(Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Att_In2 = '00:00:02', '00:00:00', Att_In2),
			Att_Out2=IF(Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Att_Out2 = '00:00:02', '00:00:00', Att_Out2),
			Att_In3=IF(Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND Att_In3 = '00:00:02', '00:00:00', Att_In3),
			Att_Out3=IF(Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND Att_Out3 = '00:00:02', '00:00:00', Att_Out3),
			Att_In4=IF(Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND Att_In4 = '00:00:02', '00:00:00', Att_In4),
			Att_Out4=IF(Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND Att_Out4 = '00:00:02', '00:00:00', Att_Out4),
			Att_In5=IF(Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND Att_In5 = '00:00:02', '00:00:00', Att_In5),
			Att_Out5=IF(Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND Att_Out5 = '00:00:02', '00:00:00', Att_Out5),
			Att_OvertimeIn=OverIn,
			Att_OvertimeOut=OverOut,
			Att_Other1=O1,
			Att_Other2=O2,
			Att_Status = 'AB',
			Att_RStatus = 'AB' WHERE Att_FPID=FPID AND Att_Date=TempDate;
			IF LOWER(ShiftType) = 'normal' THEN
				CALL spHRMCheckAttendanceNormal(SEmpID,ShiftID,FPID,TempDate);
			ELSE
				CALL spHRMCheckAttendanceRoster(SEmpID,ShiftID,FPID,TempDate);
			END IF;
		END IF;
		
		SET TempDate = DATE_ADD(TempDate,INTERVAL 1 DAY);
	END WHILE;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAttendanceHolidayEmp`;
DELIMITER |
CREATE PROCEDURE `spHRMAttendanceHolidayEmp`(SEmpID varchar(255),SFrom date, STo date)
    DETERMINISTIC
BEGIN
	DECLARE ShiftType VARCHAR(255) DEFAULT('');	
	DECLARE ShiftID VARCHAR(255) DEFAULT('');	

	DECLARE Shift_ID VARCHAR(255);
	DECLARE Shift_Day VARCHAR(255);
	DECLARE Shift_TimeIn1 TIME;
	DECLARE Shift_TimeInPeriod1 TIME;
	DECLARE Shift_TimeOut1 TIME;
	DECLARE Shift_TimeOutPeriod1 TIME;
	DECLARE Shift_TimeIn2 TIME;
	DECLARE Shift_TimeInPeriod2 TIME;
	DECLARE Shift_TimeOut2 TIME;
	DECLARE Shift_TimeOutPeriod2 TIME;
	DECLARE Shift_TimeIn3 TIME;
	DECLARE Shift_TimeInPeriod3 TIME;
	DECLARE Shift_TimeOut3 TIME;
	DECLARE Shift_TimeOutPeriod3 TIME;
	DECLARE Shift_TimeIn4 TIME;
	DECLARE Shift_TimeInPeriod4 TIME;
	DECLARE Shift_TimeOut4 TIME;
	DECLARE Shift_TimeOutPeriod4 TIME;
	DECLARE Shift_TimeIn5 TIME;
	DECLARE Shift_TimeInPeriod5 TIME;
	DECLARE Shift_TimeOut5 TIME;
	DECLARE Shift_TimeOutPeriod5 TIME;
	DECLARE Shift_TimeInOvertime TIME;
	DECLARE Shift_TimeOutOvertime TIME;

	DECLARE FPID VARCHAR(255)DEFAULT('');
	DECLARE FPDate DATE;
	DECLARE In1 TIME DEFAULT('00:00:00');
	DECLARE In2 TIME DEFAULT('00:00:00');
	DECLARE In3 TIME DEFAULT('00:00:00');
	DECLARE In4 TIME DEFAULT('00:00:00');
	DECLARE In5 TIME DEFAULT('00:00:00');
	DECLARE Out1 TIME DEFAULT('00:00:00');
	DECLARE Out2 TIME DEFAULT('00:00:00');
	DECLARE Out3 TIME DEFAULT('00:00:00');
	DECLARE Out4 TIME DEFAULT('00:00:00');
	DECLARE Out5 TIME DEFAULT('00:00:00');
	DECLARE OverIn TIME DEFAULT('00:00:00');
	DECLARE OverOut TIME DEFAULT('00:00:00');
	DECLARE O1 TIME DEFAULT('00:00:00');
	DECLARE O2 TIME DEFAULT('00:00:00');
	
	DECLARE S VARCHAR(255);
	
	DECLARE TempDate DATE;
	DECLARE CheckExist TINYINT DEFAULT(0);
	
	SET TempDate = SFrom;

	SELECT e.var_hrm_shift_type,e.var_hrm_shift_id,e.var_hrm_fpid INTO ShiftType,ShiftID,FPID FROM ame_mt_emp e WHERE e.var_id = SEmpID;

	WHILE TempDate <= DATE(STo) DO

	SET In1 = '00:00:00';
	SET In2 = '00:00:00';
	SET In3 = '00:00:00';
	SET In4 = '00:00:00';
	SET In5 = '00:00:00';
	SET Out1 = '00:00:00';
	SET Out2 = '00:00:00';
	SET Out3 = '00:00:00';
	SET Out4 = '00:00:00';
	SET Out5 = '00:00:00';

		SELECT COUNT(*) INTO CheckExist FROM  hrm_timesheet_attendance att WHERE att.Att_FPID = FPID AND att.Att_Date = TempDate;
		IF CheckExist > 0 THEN
			SELECT Att_FPID,Att_Date,Att_In1,Att_Out1,Att_In2,Att_Out2,Att_In3,Att_Out3,Att_In4,Att_Out4,Att_In5,Att_Out5,Att_OvertimeIn,Att_OvertimeOut,Att_Other1,Att_Other2 INTO FPID,FPDate,In1,Out1,In2,Out2,In3,Out3,In4,Out4,In5,Out5,OverIn,OverOut,O1,O2 FROM hrm_timesheet_attendance att WHERE att.Att_FPID = FPID AND att.Att_Date = TempDate;
		END IF;
		IF LOWER(ShiftType) = 'normal' THEN
			SELECT wd.Shift_ID,wd.Shift_Day,wd.Shift_TimeIn1,wd.Shift_TimeInPeriod1,wd.Shift_TimeOut1,wd.Shift_TimeOutPeriod1,wd.Shift_TimeIn2,wd.Shift_TimeInPeriod2,wd.Shift_TimeOut2,wd.Shift_TimeOutPeriod2,wd.Shift_TimeIn3,wd.Shift_TimeInPeriod3,wd.Shift_TimeOut3,wd.Shift_TimeOutPeriod3,wd.Shift_TimeIn4,wd.Shift_TimeInPeriod4,wd.Shift_TimeOut4,wd.Shift_TimeOutPeriod4,wd.Shift_TimeIn5,wd.Shift_TimeInPeriod5,wd.Shift_TimeOut5,wd.Shift_TimeOutPeriod5,wd.Shift_TimeInOvertime,wd.Shift_TimeOutOvertime INTO Shift_ID, Shift_Day, Shift_TimeIn1, Shift_TimeInPeriod1, Shift_TimeOut1, Shift_TimeOutPeriod1, Shift_TimeIn2, Shift_TimeInPeriod2, Shift_TimeOut2, Shift_TimeOutPeriod2, Shift_TimeIn3, Shift_TimeInPeriod3, Shift_TimeOut3, Shift_TimeOutPeriod3, Shift_TimeIn4, Shift_TimeInPeriod4, Shift_TimeOut4, Shift_TimeOutPeriod4, Shift_TimeIn5, Shift_TimeInPeriod5, Shift_TimeOut5, Shift_TimeOutPeriod5, Shift_TimeInOvertime, Shift_TimeOutOvertime FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID = ShiftID AND LOWER(wd.Shift_Day) = LOWER(DAYNAME(TempDate));
		ELSE
			SELECT wd.Shift_ID,wd.Shift_Day,wd.Shift_TimeIn1,wd.Shift_TimeInPeriod1,wd.Shift_TimeOut1,wd.Shift_TimeOutPeriod1,wd.Shift_TimeIn2,wd.Shift_TimeInPeriod2,wd.Shift_TimeOut2,wd.Shift_TimeOutPeriod2,wd.Shift_TimeIn3,wd.Shift_TimeInPeriod3,wd.Shift_TimeOut3,wd.Shift_TimeOutPeriod3,wd.Shift_TimeIn4,wd.Shift_TimeInPeriod4,wd.Shift_TimeOut4,wd.Shift_TimeOutPeriod4,wd.Shift_TimeIn5,wd.Shift_TimeInPeriod5,wd.Shift_TimeOut5,wd.Shift_TimeOutPeriod5,wd.Shift_TimeInOvertime,wd.Shift_TimeOutOvertime INTO Shift_ID, Shift_Day, Shift_TimeIn1, Shift_TimeInPeriod1, Shift_TimeOut1, Shift_TimeOutPeriod1, Shift_TimeIn2, Shift_TimeInPeriod2, Shift_TimeOut2, Shift_TimeOutPeriod2, Shift_TimeIn3, Shift_TimeInPeriod3, Shift_TimeOut3, Shift_TimeOutPeriod3, Shift_TimeIn4, Shift_TimeInPeriod4, Shift_TimeOut4, Shift_TimeOutPeriod4, Shift_TimeIn5, Shift_TimeInPeriod5, Shift_TimeOut5, Shift_TimeOutPeriod5, Shift_TimeInOvertime, Shift_TimeOutOvertime FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID = (SELECT Roster_ShiftID FROM hrm_timesheet_roster WHERE Roster_Date = TempDate AND Roster_EmpID = SEmpID);
		END IF;
		
		SET S = 'HO';

		IF CheckExist	> 0 THEN
			UPDATE hrm_timesheet_attendance SET 
			Att_In1= IF(Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Att_In1 = '00:00:00', '00:00:02', Att_In1),
			Att_Out1=IF(Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Att_Out1 = '00:00:00', '00:00:02', Att_Out1),
			Att_In2=IF(Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Att_In2 = '00:00:00', '00:00:02', Att_In2),
			Att_Out2=IF(Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Att_Out2 = '00:00:00', '00:00:02', Att_Out2),
			Att_In3=IF(Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND Att_In3 = '00:00:00', '00:00:02', Att_In3),
			Att_Out3=IF(Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND Att_Out3 = '00:00:00', '00:00:02', Att_Out3),
			Att_In4=IF(Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND Att_In4 = '00:00:00', '00:00:02', Att_In4),
			Att_Out4=IF(Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND Att_Out4 = '00:00:00', '00:00:02', Att_Out4),
			Att_In5=IF(Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND Att_In5 = '00:00:00', '00:00:02', Att_In5),
			Att_Out5=IF(Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND Att_Out5 = '00:00:00', '00:00:02', Att_Out5),
			Att_OvertimeIn=OverIn,
			Att_OvertimeOut=OverOut,
			Att_Other1=O1,
			Att_Other2=O2,Att_Status=S,Att_RStatus=S WHERE Att_FPID=FPID AND Att_Date=FPDate;

		ELSE
			INSERT INTO hrm_timesheet_attendance(Att_EmpID,Att_FPID,Att_Date,Att_In1,Att_Out1,Att_In2,Att_Out2,Att_In3,Att_Out3,Att_In4,Att_Out4,Att_In5,Att_Out5,Att_OvertimeIn,Att_OvertimeOut,Att_Other1,Att_Other2,Att_LateAmount,Att_ABAmount,Att_Status,Att_RStatus, Att_WorkHour, Att_LateDuration, Att_LateDurationDeduct, Att_ABDurationDeduct) VALUES (SEmpID,FPID,TempDate,
			IF(Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Att_In1 = '00:00:00', '00:00:02', '00:00:00'),
			IF(Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Att_Out1 = '00:00:00', '00:00:02', '00:00:00'),
			IF(Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Att_In2 = '00:00:00', '00:00:02', '00:00:00'),
			IF(Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Att_Out2 = '00:00:00', '00:00:02', '00:00:00'),
			IF(Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND Att_In3 = '00:00:00', '00:00:02', '00:00:00'),
			IF(Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND Att_Out3 = '00:00:00', '00:00:02', '00:00:00'),
			IF(Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND Att_In4 = '00:00:00', '00:00:02', '00:00:00'),
			IF(Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND Att_Out4 = '00:00:00', '00:00:02', '00:00:00'),
			IF(Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND Att_In5 = '00:00:00', '00:00:02', '00:00:00'),
			IF(Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND Att_Out5 = '00:00:00', '00:00:02', '00:00:00'),
			'00:00:00','00:00:00','00:00:00','00:00:00',0,0,S,S,0,'00:00:00','00:00:00','00:00:00');
		END IF;
		SET TempDate = DATE_ADD(TempDate,INTERVAL 1 DAY);
	END WHILE;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAttendanceLeaveDeleteFullDay`;
DELIMITER |
CREATE PROCEDURE `spHRMAttendanceLeaveDeleteFullDay`(SEmpID varchar(255),SFrom datetime, STo datetime)
    DETERMINISTIC
BEGIN
	DECLARE ShiftType VARCHAR(255) DEFAULT('');	
	DECLARE ShiftID VARCHAR(255) DEFAULT('');	

	DECLARE Shift_ID VARCHAR(255);
	DECLARE Shift_Day VARCHAR(255);
	DECLARE Shift_TimeIn1 TIME;
	DECLARE Shift_TimeInPeriod1 TIME;
	DECLARE Shift_TimeOut1 TIME;
	DECLARE Shift_TimeOutPeriod1 TIME;
	DECLARE Shift_TimeIn2 TIME;
	DECLARE Shift_TimeInPeriod2 TIME;
	DECLARE Shift_TimeOut2 TIME;
	DECLARE Shift_TimeOutPeriod2 TIME;
	DECLARE Shift_TimeIn3 TIME;
	DECLARE Shift_TimeInPeriod3 TIME;
	DECLARE Shift_TimeOut3 TIME;
	DECLARE Shift_TimeOutPeriod3 TIME;
	DECLARE Shift_TimeIn4 TIME;
	DECLARE Shift_TimeInPeriod4 TIME;
	DECLARE Shift_TimeOut4 TIME;
	DECLARE Shift_TimeOutPeriod4 TIME;
	DECLARE Shift_TimeIn5 TIME;
	DECLARE Shift_TimeInPeriod5 TIME;
	DECLARE Shift_TimeOut5 TIME;
	DECLARE Shift_TimeOutPeriod5 TIME;
	DECLARE Shift_TimeInOvertime TIME;
	DECLARE Shift_TimeOutOvertime TIME;

	DECLARE LeaveDurationInOut1 TIME DEFAULT('00:00:00');
	DECLARE LeaveDurationInOut2 TIME DEFAULT('00:00:00');
	DECLARE LeaveDurationInOut3 TIME DEFAULT('00:00:00');
	DECLARE LeaveDurationInOut4 TIME DEFAULT('00:00:00');
	DECLARE LeaveDurationInOut5 TIME DEFAULT('00:00:00');

	DECLARE FPID VARCHAR(255)DEFAULT('');
	DECLARE FPDate DATE;
	DECLARE In1 TIME DEFAULT('00:00:00');
	DECLARE In2 TIME DEFAULT('00:00:00');
	DECLARE In3 TIME DEFAULT('00:00:00');
	DECLARE In4 TIME DEFAULT('00:00:00');
	DECLARE In5 TIME DEFAULT('00:00:00');
	DECLARE Out1 TIME DEFAULT('00:00:00');
	DECLARE Out2 TIME DEFAULT('00:00:00');
	DECLARE Out3 TIME DEFAULT('00:00:00');
	DECLARE Out4 TIME DEFAULT('00:00:00');
	DECLARE Out5 TIME DEFAULT('00:00:00');
	DECLARE OverIn TIME DEFAULT('00:00:00');
	DECLARE OverOut TIME DEFAULT('00:00:00');
	DECLARE O1 TIME DEFAULT('00:00:00');
	DECLARE O2 TIME DEFAULT('00:00:00');
	DECLARE CheckLate TINYINT DEFAULT(0);
	DECLARE CheckAb TINYINT DEFAULT(0);
	DECLARE CheckL TINYINT DEFAULT(0);
	DECLARE S VARCHAR(255);
	
	DECLARE TempDate DATE;
	DECLARE CheckExist TINYINT DEFAULT(0);
	
	SET TempDate = DATE(SFrom);

	SELECT e.var_hrm_shift_type,e.var_hrm_shift_id,e.var_hrm_fpid INTO ShiftType,ShiftID,FPID FROM ame_mt_emp e WHERE e.var_id = SEmpID;

	WHILE TempDate <= DATE(STo) DO

	SET In1 = '00:00:00';
	SET In2 = '00:00:00';
	SET In3 = '00:00:00';
	SET In4 = '00:00:00';
	SET In5 = '00:00:00';
	SET Out1 = '00:00:00';
	SET Out2 = '00:00:00';
	SET Out3 = '00:00:00';
	SET Out4 = '00:00:00';
	SET Out5 = '00:00:00';

		SELECT COUNT(*) INTO CheckExist FROM  hrm_timesheet_attendance att WHERE att.Att_FPID = FPID AND att.Att_Date = TempDate;
		IF CheckExist > 0 THEN
			SELECT Att_FPID,Att_Date,Att_In1,Att_Out1,Att_In2,Att_Out2,Att_In3,Att_Out3,Att_In4,Att_Out4,Att_In5,Att_Out5,Att_OvertimeIn,Att_OvertimeOut,Att_Other1,Att_Other2,Att_LateAmount,Att_Status INTO FPID,FPDate,In1,Out1,In2,Out2,In3,Out3,In4,Out4,In5,Out5,OverIn,OverOut,O1,O2,CheckLate,S FROM hrm_timesheet_attendance att WHERE att.Att_FPID = FPID AND att.Att_Date = TempDate;
		END IF;
		IF LOWER(ShiftType) = 'normal' THEN
			SELECT wd.Shift_ID,wd.Shift_Day,wd.Shift_TimeIn1,wd.Shift_TimeInPeriod1,wd.Shift_TimeOut1,wd.Shift_TimeOutPeriod1,wd.Shift_TimeIn2,wd.Shift_TimeInPeriod2,wd.Shift_TimeOut2,wd.Shift_TimeOutPeriod2,wd.Shift_TimeIn3,wd.Shift_TimeInPeriod3,wd.Shift_TimeOut3,wd.Shift_TimeOutPeriod3,wd.Shift_TimeIn4,wd.Shift_TimeInPeriod4,wd.Shift_TimeOut4,wd.Shift_TimeOutPeriod4,wd.Shift_TimeIn5,wd.Shift_TimeInPeriod5,wd.Shift_TimeOut5,wd.Shift_TimeOutPeriod5,wd.Shift_TimeInOvertime,wd.Shift_TimeOutOvertime INTO Shift_ID, Shift_Day, Shift_TimeIn1, Shift_TimeInPeriod1, Shift_TimeOut1, Shift_TimeOutPeriod1, Shift_TimeIn2, Shift_TimeInPeriod2, Shift_TimeOut2, Shift_TimeOutPeriod2, Shift_TimeIn3, Shift_TimeInPeriod3, Shift_TimeOut3, Shift_TimeOutPeriod3, Shift_TimeIn4, Shift_TimeInPeriod4, Shift_TimeOut4, Shift_TimeOutPeriod4, Shift_TimeIn5, Shift_TimeInPeriod5, Shift_TimeOut5, Shift_TimeOutPeriod5, Shift_TimeInOvertime, Shift_TimeOutOvertime FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID = ShiftID AND LOWER(wd.Shift_Day) = LOWER(DAYNAME(TempDate));
		ELSE
			SELECT wd.Shift_ID,wd.Shift_Day,wd.Shift_TimeIn1,wd.Shift_TimeInPeriod1,wd.Shift_TimeOut1,wd.Shift_TimeOutPeriod1,wd.Shift_TimeIn2,wd.Shift_TimeInPeriod2,wd.Shift_TimeOut2,wd.Shift_TimeOutPeriod2,wd.Shift_TimeIn3,wd.Shift_TimeInPeriod3,wd.Shift_TimeOut3,wd.Shift_TimeOutPeriod3,wd.Shift_TimeIn4,wd.Shift_TimeInPeriod4,wd.Shift_TimeOut4,wd.Shift_TimeOutPeriod4,wd.Shift_TimeIn5,wd.Shift_TimeInPeriod5,wd.Shift_TimeOut5,wd.Shift_TimeOutPeriod5,wd.Shift_TimeInOvertime,wd.Shift_TimeOutOvertime INTO Shift_ID, Shift_Day, Shift_TimeIn1, Shift_TimeInPeriod1, Shift_TimeOut1, Shift_TimeOutPeriod1, Shift_TimeIn2, Shift_TimeInPeriod2, Shift_TimeOut2, Shift_TimeOutPeriod2, Shift_TimeIn3, Shift_TimeInPeriod3, Shift_TimeOut3, Shift_TimeOutPeriod3, Shift_TimeIn4, Shift_TimeInPeriod4, Shift_TimeOut4, Shift_TimeOutPeriod4, Shift_TimeIn5, Shift_TimeInPeriod5, Shift_TimeOut5, Shift_TimeOutPeriod5, Shift_TimeInOvertime, Shift_TimeOutOvertime FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID = (SELECT Roster_ShiftID FROM hrm_timesheet_roster WHERE Roster_Date = TempDate AND Roster_EmpID = SEmpID);
		END IF;

		IF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' THEN
			SET LeaveDurationInOut1 = TIMEDIFF(Shift_TimeOut1,Shift_TimeIn1);
		END IF;
		IF Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' THEN
			SET LeaveDurationInOut2 = TIMEDIFF(Shift_TimeOut2,Shift_TimeIn2);
		END IF;
		IF Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' THEN
			SET LeaveDurationInOut3 = TIMEDIFF(Shift_TimeOut3,Shift_TimeIn3);
		END IF;
		IF Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' THEN
			SET LeaveDurationInOut4 = TIMEDIFF(Shift_TimeOut4,Shift_TimeIn4);
		END IF;
		IF Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' THEN
			SET LeaveDurationInOut5 = TIMEDIFF(Shift_TimeOut5,Shift_TimeIn5);
		END IF;

		IF CheckExist	> 0 THEN
			UPDATE hrm_timesheet_attendance SET 
			Att_In1= IF(Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Att_In1 = '00:00:01', '00:00:00', Att_In1),
			Att_Out1=IF(Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Att_Out1 = '00:00:01', '00:00:00', Att_Out1),
			Att_In2=IF(Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Att_In2 = '00:00:01', '00:00:00', Att_In2),
			Att_Out2=IF(Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Att_Out2 = '00:00:01', '00:00:00', Att_Out2),
			Att_In3=IF(Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND Att_In3 = '00:00:01', '00:00:00', Att_In3),
			Att_Out3=IF(Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND Att_Out3 = '00:00:01', '00:00:00', Att_Out3),
			Att_In4=IF(Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND Att_In4 = '00:00:01', '00:00:00', Att_In4),
			Att_Out4=IF(Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND Att_Out4 = '00:00:01', '00:00:00', Att_Out4),
			Att_In5=IF(Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND Att_In5 = '00:00:01', '00:00:00', Att_In5),
			Att_Out5=IF(Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND Att_Out5 = '00:00:01', '00:00:00', Att_Out5),
			Att_OvertimeIn=OverIn,
			Att_OvertimeOut=OverOut,
			Att_Other1=O1,
			Att_Other2=O2,
			Att_LeaveDurationInOut1=LeaveDurationInOut1,
			Att_LeaveDurationInOut2=LeaveDurationInOut2,
			Att_LeaveDurationInOut3=LeaveDurationInOut3,
			Att_LeaveDurationInOut4=LeaveDurationInOut4,
			Att_LeaveDurationInOut5=LeaveDurationInOut5 WHERE Att_FPID=FPID AND Att_Date=TempDate;

			IF LOWER(ShiftType) = 'normal' THEN
				CALL spHRMCheckAttendanceNormal(SEmpID,ShiftID,FPID,TempDate);
			ELSE
				CALL spHRMCheckAttendanceRoster(SEmpID,ShiftID,FPID,TempDate);
			END IF;
		END IF;

		SET TempDate = DATE_ADD(TempDate,INTERVAL 1 DAY);
	END WHILE;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAttendanceLeaveDeleteHourly`;
DELIMITER |
CREATE PROCEDURE `spHRMAttendanceLeaveDeleteHourly`(SEmpID varchar(255),SFrom datetime, STo datetime)
    DETERMINISTIC
BEGIN
	DECLARE ShiftType VARCHAR(255) DEFAULT('');	
	DECLARE ShiftID VARCHAR(255) DEFAULT('');	

	DECLARE Shift_ID VARCHAR(255);
	DECLARE Shift_Day VARCHAR(255);
	DECLARE Shift_TimeIn1 TIME;
	DECLARE Shift_TimeInPeriod1 TIME;
	DECLARE Shift_TimeOut1 TIME;
	DECLARE Shift_TimeOutPeriod1 TIME;
	DECLARE Shift_TimeIn2 TIME;
	DECLARE Shift_TimeInPeriod2 TIME;
	DECLARE Shift_TimeOut2 TIME;
	DECLARE Shift_TimeOutPeriod2 TIME;
	DECLARE Shift_TimeIn3 TIME;
	DECLARE Shift_TimeInPeriod3 TIME;
	DECLARE Shift_TimeOut3 TIME;
	DECLARE Shift_TimeOutPeriod3 TIME;
	DECLARE Shift_TimeIn4 TIME;
	DECLARE Shift_TimeInPeriod4 TIME;
	DECLARE Shift_TimeOut4 TIME;
	DECLARE Shift_TimeOutPeriod4 TIME;
	DECLARE Shift_TimeIn5 TIME;
	DECLARE Shift_TimeInPeriod5 TIME;
	DECLARE Shift_TimeOut5 TIME;
	DECLARE Shift_TimeOutPeriod5 TIME;
	DECLARE Shift_TimeInOvertime TIME;
	DECLARE Shift_TimeOutOvertime TIME;

	DECLARE LeaveDurationStatus VARCHAR(255) DEFAULT('');
	DECLARE LeaveDurationInOut1 TIME DEFAULT('00:00:00');
	DECLARE LeaveDurationInOut2 TIME DEFAULT('00:00:00');
	DECLARE LeaveDurationInOut3 TIME DEFAULT('00:00:00');
	DECLARE LeaveDurationInOut4 TIME DEFAULT('00:00:00');
	DECLARE LeaveDurationInOut5 TIME DEFAULT('00:00:00');

	DECLARE FPID VARCHAR(255)DEFAULT('');
	DECLARE FPDate DATE;
	DECLARE In1 TIME DEFAULT('00:00:00');
	DECLARE In2 TIME DEFAULT('00:00:00');
	DECLARE In3 TIME DEFAULT('00:00:00');
	DECLARE In4 TIME DEFAULT('00:00:00');
	DECLARE In5 TIME DEFAULT('00:00:00');
	DECLARE Out1 TIME DEFAULT('00:00:00');
	DECLARE Out2 TIME DEFAULT('00:00:00');
	DECLARE Out3 TIME DEFAULT('00:00:00');
	DECLARE Out4 TIME DEFAULT('00:00:00');
	DECLARE Out5 TIME DEFAULT('00:00:00');
	DECLARE OverIn TIME DEFAULT('00:00:00');
	DECLARE OverOut TIME DEFAULT('00:00:00');
	DECLARE O1 TIME DEFAULT('00:00:00');
	DECLARE O2 TIME DEFAULT('00:00:00');

	DECLARE TimeBreak1 VARCHAR(255) DEFAULT('');
	DECLARE TimeBreak2 VARCHAR(255) DEFAULT('');
	DECLARE TimeBreak3 VARCHAR(255) DEFAULT('');
	DECLARE TimeBreak4 VARCHAR(255) DEFAULT('');
	DECLARE TimeBreak5 VARCHAR(255) DEFAULT('');

	DECLARE ReadyIn1 TINYINT DEFAULT(0);
	DECLARE ReadyIn2 TINYINT DEFAULT(0);
	DECLARE ReadyIn3 TINYINT DEFAULT(0);
	DECLARE ReadyIn4 TINYINT DEFAULT(0);
	DECLARE ReadyIn5 TINYINT DEFAULT(0);
	DECLARE ReadyOut1 TINYINT DEFAULT(0);
	DECLARE ReadyOut2 TINYINT DEFAULT(0);
	DECLARE ReadyOut3 TINYINT DEFAULT(0);
	DECLARE ReadyOut4 TINYINT DEFAULT(0);
	DECLARE ReadyOut5 TINYINT DEFAULT(0);

	DECLARE CheckOutLeave VARCHAR(255) DEFAULT('');
	DECLARE CheckAttendanceOutLeaveReady TINYINT DEFAULT(0);
	
	DECLARE CheckExist TINYINT DEFAULT(0);

	SELECT e.var_hrm_shift_type,e.var_hrm_shift_id,e.var_hrm_fpid INTO ShiftType,ShiftID,FPID FROM ame_mt_emp e WHERE e.var_id = SEmpID;

		SELECT COUNT(*) INTO CheckExist FROM  hrm_timesheet_attendance att WHERE att.Att_FPID = FPID AND att.Att_Date = DATE(SFrom);
		IF CheckExist > 0 THEN
			SELECT Att_FPID,Att_Date,Att_In1,Att_Out1,Att_In2,Att_Out2,Att_In3,Att_Out3,Att_In4,Att_Out4,Att_In5,Att_Out5,Att_OvertimeIn,Att_OvertimeOut,Att_Other1,Att_Other2,Att_OutLeave INTO FPID,FPDate,In1,Out1,In2,Out2,In3,Out3,In4,Out4,In5,Out5,OverIn,OverOut,O1,O2,CheckOutLeave FROM hrm_timesheet_attendance att WHERE att.Att_FPID = FPID AND att.Att_Date = DATE(SFrom);
		END IF;
		IF LOWER(ShiftType) = 'normal' THEN
			SELECT wd.Shift_ID,wd.Shift_Day,wd.Shift_TimeIn1,wd.Shift_TimeInPeriod1,wd.Shift_TimeOut1,wd.Shift_TimeOutPeriod1,wd.Shift_TimeIn2,wd.Shift_TimeInPeriod2,wd.Shift_TimeOut2,wd.Shift_TimeOutPeriod2,wd.Shift_TimeIn3,wd.Shift_TimeInPeriod3,wd.Shift_TimeOut3,wd.Shift_TimeOutPeriod3,wd.Shift_TimeIn4,wd.Shift_TimeInPeriod4,wd.Shift_TimeOut4,wd.Shift_TimeOutPeriod4,wd.Shift_TimeIn5,wd.Shift_TimeInPeriod5,wd.Shift_TimeOut5,wd.Shift_TimeOutPeriod5,wd.Shift_TimeInOvertime,wd.Shift_TimeOutOvertime,Shift_TimeBreak1,Shift_TimeBreak2,Shift_TimeBreak3,Shift_TimeBreak4,Shift_TimeBreak5 INTO Shift_ID, Shift_Day, Shift_TimeIn1, Shift_TimeInPeriod1, Shift_TimeOut1, Shift_TimeOutPeriod1, Shift_TimeIn2, Shift_TimeInPeriod2, Shift_TimeOut2, Shift_TimeOutPeriod2, Shift_TimeIn3, Shift_TimeInPeriod3, Shift_TimeOut3, Shift_TimeOutPeriod3, Shift_TimeIn4, Shift_TimeInPeriod4, Shift_TimeOut4, Shift_TimeOutPeriod4, Shift_TimeIn5, Shift_TimeInPeriod5, Shift_TimeOut5, Shift_TimeOutPeriod5, Shift_TimeInOvertime, Shift_TimeOutOvertime, TimeBreak1, TimeBreak2, TimeBreak3, TimeBreak4, TimeBreak5 FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID = ShiftID AND LOWER(wd.Shift_Day) = LOWER(DAYNAME(DATE(SFrom)));
		ELSE
			SELECT wd.Shift_ID,wd.Shift_Day,wd.Shift_TimeIn1,wd.Shift_TimeInPeriod1,wd.Shift_TimeOut1,wd.Shift_TimeOutPeriod1,wd.Shift_TimeIn2,wd.Shift_TimeInPeriod2,wd.Shift_TimeOut2,wd.Shift_TimeOutPeriod2,wd.Shift_TimeIn3,wd.Shift_TimeInPeriod3,wd.Shift_TimeOut3,wd.Shift_TimeOutPeriod3,wd.Shift_TimeIn4,wd.Shift_TimeInPeriod4,wd.Shift_TimeOut4,wd.Shift_TimeOutPeriod4,wd.Shift_TimeIn5,wd.Shift_TimeInPeriod5,wd.Shift_TimeOut5,wd.Shift_TimeOutPeriod5,wd.Shift_TimeInOvertime,wd.Shift_TimeOutOvertime,Shift_TimeBreak1,Shift_TimeBreak2,Shift_TimeBreak3,Shift_TimeBreak4,Shift_TimeBreak5 INTO Shift_ID, Shift_Day, Shift_TimeIn1, Shift_TimeInPeriod1, Shift_TimeOut1, Shift_TimeOutPeriod1, Shift_TimeIn2, Shift_TimeInPeriod2, Shift_TimeOut2, Shift_TimeOutPeriod2, Shift_TimeIn3, Shift_TimeInPeriod3, Shift_TimeOut3, Shift_TimeOutPeriod3, Shift_TimeIn4, Shift_TimeInPeriod4, Shift_TimeOut4, Shift_TimeOutPeriod4, Shift_TimeIn5, Shift_TimeInPeriod5, Shift_TimeOut5, Shift_TimeOutPeriod5, Shift_TimeInOvertime, Shift_TimeOutOvertime, TimeBreak1, TimeBreak2, TimeBreak3, TimeBreak4, TimeBreak5 FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID = (SELECT Roster_ShiftID FROM hrm_timesheet_roster WHERE Roster_Date = DATE(SFrom) AND Roster_EmpID = SEmpID);
		END IF;

		IF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND In1 = '00:00:01' AND ((TIME(SFrom) <= Shift_TimeIn1 AND TIME(STo) >= Shift_TimeIn1) OR (TIME(SFrom) <= Shift_TimeInPeriod1 AND TIME(STo) >= Shift_TimeInPeriod1)) THEN
			SET In1 = '00:00:00';
		END IF;

		IF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Out1 = '00:00:01' AND ((TIME(SFrom) <= Shift_TimeOut1 AND TIME(STo) >= Shift_TimeOut1) OR (TIME(SFrom) <= Shift_TimeOutPeriod1 AND TIME(STo) >= Shift_TimeOutPeriod1)) THEN
			SET Out1 = '00:00:00';
		END IF;

		IF Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND In2 = '00:00:01' AND ((TIME(SFrom) <= Shift_TimeIn2 AND TIME(STo) >= Shift_TimeIn2) OR (TIME(SFrom) <= Shift_TimeInPeriod2 AND TIME(STo) >= Shift_TimeInPeriod2)) THEN
			SET In2 = '00:00:00';
		END IF;

		IF Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Out2 = '00:00:01' AND ((TIME(SFrom) <= Shift_TimeOut2 AND TIME(STo) >= Shift_TimeOut2) OR (TIME(SFrom) <= Shift_TimeOutPeriod2 AND TIME(STo) >= Shift_TimeOutPeriod2)) THEN
			SET Out2 = '00:00:00';
		END IF;

		IF Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND In3 = '00:00:01' AND ((TIME(SFrom) <= Shift_TimeIn3 AND TIME(STo) >= Shift_TimeIn3) OR (TIME(SFrom) <= Shift_TimeInPeriod3 AND TIME(STo) >= Shift_TimeInPeriod3)) THEN
			SET In3 = '00:00:00';
		END IF;

		IF Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND Out3 = '00:00:01' AND ((TIME(SFrom) <= Shift_TimeOut3 AND TIME(STo) >= Shift_TimeOut3) OR (TIME(SFrom) <= Shift_TimeOutPeriod3 AND TIME(STo) >= Shift_TimeOutPeriod3)) THEN
			SET Out3 = '00:00:00';
		END IF;

		IF Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND In4 = '00:00:01' AND ((TIME(SFrom) <= Shift_TimeIn4 AND TIME(STo) >= Shift_TimeIn4) OR (TIME(SFrom) <= Shift_TimeInPeriod4 AND TIME(STo) >= Shift_TimeInPeriod4)) THEN
			SET In4 = '00:00:00';
		END IF;

		IF Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND Out4 = '00:00:01' AND ((TIME(SFrom) <= Shift_TimeOut4 AND TIME(STo) >= Shift_TimeOut4) OR (TIME(SFrom) <= Shift_TimeOutPeriod4 AND TIME(STo) >= Shift_TimeOutPeriod4)) THEN
			SET Out4 = '00:00:00';
		END IF;

		IF Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND In5 = '00:00:01' AND ((TIME(SFrom) <= Shift_TimeIn5 AND TIME(STo) >= Shift_TimeIn5) OR (TIME(SFrom) <= Shift_TimeInPeriod5 AND TIME(STo) >= Shift_TimeInPeriod5)) THEN
			SET In5 = '00:00:00';
		END IF;

		IF Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND Out5 = '00:00:01' AND ((TIME(SFrom) <= Shift_TimeOut5 AND TIME(STo) >= Shift_TimeOut5) OR (TIME(SFrom) <= Shift_TimeOutPeriod5 AND TIME(STo) >= Shift_TimeOutPeriod5))  THEN
			SET Out5 = '00:00:00';
		END IF;

		IF In1 = '00:00:00' AND Out1 = '00:00:00' AND In2 = '00:00:00' AND Out2 = '00:00:00' AND In3 = '00:00:00' AND Out3 = '00:00:00' AND In4 = '00:00:00' AND Out4 = '00:00:00' AND In5 = '00:00:00' AND Out5 = '00:00:00' AND O1 <> '00:00:01' THEN
			SET O1 = '00:00:00';
		ELSEIF In1 = '00:00:00' AND Out1 = '00:00:00' AND In2 = '00:00:00' AND Out2 = '00:00:00' AND In3 = '00:00:00' AND Out3 = '00:00:00' AND In4 = '00:00:00' AND Out4 = '00:00:00' AND In5 = '00:00:00' AND Out5 = '00:00:00' AND O1 = '00:00:01' AND O2 <> '00:00:01' THEN
			SET O2 = '00:00:00';
		END IF;

		-- Check Leave Duration
		IF (In1 = '00:00:01' AND Out1 = '00:00:00') OR (In1 = '00:00:00' AND Out1 = '00:00:01') THEN
			IF In1 = '00:00:01' THEN
				SET LeaveDurationInOut1 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo), Shift_TimeIn1), TIME(STo), TimeBreak1, 'TimeIn');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In1;'); 
			ELSEIF Out1 = '00:00:01' THEN
				SET LeaveDurationInOut1 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut1, TIME(SFrom)), TIME(SFrom), TimeBreak1, 'TimeOut');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out1;'); 
			END IF;
			SET In1 = '00:00:00';
			SET Out1 = '00:00:00';
		ELSEIF In1 = '00:00:01' AND Out1 = '00:00:01' THEN
			SET LeaveDurationInOut1 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut1,Shift_TimeIn1), '00:00:00', TimeBreak1, 'TimeLeave');
		ELSEIF In1 = '00:00:01' AND Out1 <> '00:00:01' AND Out1 <> '00:00:00' THEN
			SET LeaveDurationInOut1 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo), Shift_TimeIn1), TIME(STo), TimeBreak1, 'TimeIn');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In1;'); 
			SET In1 = '00:00:00';
		ELSEIF In1 <> '00:00:01' AND In1 <> '00:00:00' AND  Out1 = '00:00:01' THEN
			SET LeaveDurationInOut1 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut1, TIME(SFrom)), TIME(SFrom), TimeBreak1, 'TimeOut');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out1;'); 
			SET Out1 = '00:00:00';
		END IF;

		IF (In2 = '00:00:01' AND Out2 = '00:00:00') OR (In2 = '00:00:00' AND Out2 = '00:00:01') THEN
			IF In2 = '00:00:01' THEN
				SET LeaveDurationInOut2 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo),Shift_TimeIn2), TIME(STo), TimeBreak2, 'TimeIn');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In2;'); 
			ELSEIF Out2 = '00:00:01' THEN
				SET LeaveDurationInOut2 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut2, TIME(SFrom)), TIME(SFrom), TimeBreak2, 'TimeOut');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out2;'); 
			END IF;
			SET In2 = '00:00:00';
			SET Out2 = '00:00:00';
		ELSEIF In2 = '00:00:01' AND Out2 = '00:00:01' THEN
			SET LeaveDurationInOut2 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut2,Shift_TimeIn2), '00:00:00', TimeBreak2, 'TimeLeave');
		ELSEIF In2 = '00:00:01' AND Out2 <> '00:00:01' AND Out2 <> '00:00:00' THEN
			SET LeaveDurationInOut2 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo), Shift_TimeIn2), TIME(STo), TimeBreak2, 'TimeIn');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In2;'); 
			SET In2 = '00:00:00';
		ELSEIF In2 <> '00:00:01' AND In2 <> '00:00:00' AND  Out2 = '00:00:01' THEN
			SET LeaveDurationInOut2 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut2, TIME(SFrom)), TIME(SFrom), TimeBreak2, 'TimeOut');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out2;'); 
			SET Out2 = '00:00:00';
		END IF;

		IF (In3 = '00:00:01' AND Out3 = '00:00:00') OR (In3 = '00:00:00' AND Out3 = '00:00:01') THEN
			IF In3 = '00:00:01' THEN
				SET LeaveDurationInOut3 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo),Shift_TimeIn3), TIME(STo), TimeBreak3, 'TimeIn');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In3;'); 
			ELSEIF Out3 = '00:00:01' THEN
				SET LeaveDurationInOut3 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut3, TIME(SFrom)), TIME(SFrom), TimeBreak3, 'TimeOut');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out3;'); 
			END IF;
			SET In3 = '00:00:00';
			SET Out3 = '00:00:00';
		ELSEIF In3 = '00:00:01' AND Out3 = '00:00:01' THEN
			SET LeaveDurationInOut3 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut3,Shift_TimeIn3), '00:00:00', TimeBreak3, 'TimeLeave');
		ELSEIF In3 = '00:00:01' AND Out3 <> '00:00:01' AND Out3 <> '00:00:00' THEN
			SET LeaveDurationInOut3 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo), Shift_TimeIn3), TIME(STo), TimeBreak3, 'TimeIn');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In3;'); 
			SET In3 = '00:00:00';
		ELSEIF In3 <> '00:00:01' AND In3 <> '00:00:00' AND  Out3 = '00:00:01' THEN
			SET LeaveDurationInOut3 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut3, TIME(SFrom)), TIME(SFrom), TimeBreak3, 'TimeOut');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out3;'); 
			SET Out3 = '00:00:00';
		END IF;

		IF (In4 = '00:00:01' AND Out4 = '00:00:00') OR (In4 = '00:00:00' AND Out4 = '00:00:01') THEN
			IF In4 = '00:00:01' THEN
				SET LeaveDurationInOut4 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo),Shift_TimeIn4), TIME(STo), TimeBreak4, 'TimeIn');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In4;');
			ELSEIF Out4 = '00:00:01' THEN
				SET LeaveDurationInOut4 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut4, TIME(SFrom)), TIME(SFrom), TimeBreak4, 'TimeOut');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out4;');
			END IF;
			SET In4 = '00:00:00';
			SET Out4 = '00:00:00';
		ELSEIF In4 = '00:00:01' AND Out4 = '00:00:01' THEN
			SET LeaveDurationInOut4 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut4,Shift_TimeIn4), '00:00:00', TimeBreak4, 'TimeLeave');
		ELSEIF In4 = '00:00:01' AND Out4 <> '00:00:01' AND Out4 <> '00:00:00' THEN
			SET LeaveDurationInOut4 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo), Shift_TimeIn4), TIME(STo), TimeBreak4, 'TimeIn');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In4;'); 
			SET In4 = '00:00:00';
		ELSEIF In4 <> '00:00:01' AND In4 <> '00:00:00' AND  Out4 = '00:00:01' THEN
			SET LeaveDurationInOut4 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut4, TIME(SFrom)), TIME(SFrom), TimeBreak4, 'TimeOut');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out4;'); 
			SET Out4 = '00:00:00';
		END IF;

		IF (In5 = '00:00:01' AND Out5 = '00:00:00') OR (In5 = '00:00:00' AND Out5 = '00:00:01') THEN
			IF In5 = '00:00:01' THEN
				SET LeaveDurationInOut5 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo),Shift_TimeIn5), TIME(STo), TimeBreak5, 'TimeIn');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In5;');
			ELSEIF Out5 = '00:00:01' THEN
				SET LeaveDurationInOut5 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut5, TIME(SFrom)), TIME(SFrom), TimeBreak5, 'TimeOut');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out5;');
			END IF;
			SET In5 = '00:00:00';
			SET Out5 = '00:00:00';
		ELSEIF In5 = '00:00:01' AND Out5 = '00:00:01' THEN
			SET LeaveDurationInOut5 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut5,Shift_TimeIn5), '00:00:00', TimeBreak5, 'TimeLeave');
		ELSEIF In5 = '00:00:01' AND Out5 <> '00:00:01' AND Out5 <> '00:00:00' THEN
			SET LeaveDurationInOut5 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo), Shift_TimeIn5), TIME(STo), TimeBreak5, 'TimeIn');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In5;'); 
			SET In5 = '00:00:00';
		ELSEIF In5 <> '00:00:01' AND In5 <> '00:00:00' AND  Out5 = '00:00:01' THEN
			SET LeaveDurationInOut5 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut5, TIME(SFrom)), TIME(SFrom), TimeBreak5, 'TimeOut');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out5;'); 
			SET Out5 = '00:00:00';
		END IF;
		
		IF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND In1 <> '00:00:00' AND In1 <> '00:00:01' AND Out1 <> '00:00:00' AND Out1 <> '00:00:01' AND In2 <> '00:00:00' AND In2 <> '00:00:01' AND Out2 <> '00:00:00' AND Out2 <> '00:00:01' AND In3 <> '00:00:00' AND In3 <> '00:00:01' AND Out3 <> '00:00:00' AND Out3 <> '00:00:01'AND In4 <> '00:00:00' AND In4 <> '00:00:01' AND Out4 <> '00:00:00' AND Out4 <> '00:00:01' AND In5 <> '00:00:00' AND In5 <> '00:00:01' AND Out5 <> '00:00:00' AND Out5 <> '00:00:01' THEN
			SET CheckAttendanceOutLeaveReady = 1;
		ELSEIF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND In1 <> '00:00:00' AND In1 <> '00:00:01' AND Out1 <> '00:00:00' AND Out1 <> '00:00:01' AND In2 <> '00:00:00' AND In2 <> '00:00:01' AND Out2 <> '00:00:00' AND Out2 <> '00:00:01' AND In3 <> '00:00:00' AND In3 <> '00:00:01' AND Out3 <> '00:00:00' AND Out3 <> '00:00:01' AND In4 <> '00:00:00' AND In4 <> '00:00:01' AND Out4 <> '00:00:00' AND Out4 <> '00:00:01' THEN
			SET CheckAttendanceOutLeaveReady = 1;
		ELSEIF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND In1 <> '00:00:00' AND In1 <> '00:00:01' AND Out1 <> '00:00:00' AND Out1 <> '00:00:01' AND In2 <> '00:00:00' AND In2 <> '00:00:01' AND Out2 <> '00:00:00' AND Out2 <> '00:00:01' AND In3 <> '00:00:00' AND In3 <> '00:00:01' AND Out3 <> '00:00:00' AND Out3 <> '00:00:01' THEN
			SET CheckAttendanceOutLeaveReady = 1;
		ELSEIF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND In1 <> '00:00:00' AND In1 <> '00:00:01' AND Out1 <> '00:00:00' AND Out1 <> '00:00:01' AND In2 <> '00:00:00' AND In2 <> '00:00:01' AND Out2 <> '00:00:00' AND Out2 <> '00:00:01' THEN
			SET CheckAttendanceOutLeaveReady = 1;
		ELSEIF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND In1 <> '00:00:00' AND In1 <> '00:00:01' AND Out1 <> '00:00:00' AND Out1 <> '00:00:01' THEN
			SET CheckAttendanceOutLeaveReady = 1;
		END IF;
		
		IF CheckAttendanceOutLeaveReady = 1 THEN
			IF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeIn1 AND TIME(STo) >= Shift_TimeIn1) OR (TIME(SFrom) <= Shift_TimeInPeriod1 AND TIME(STo) >= Shift_TimeInPeriod1)) THEN
				SET ReadyIn1 = 1;
			END IF;
			IF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeOut1 AND TIME(STo) >= Shift_TimeOut1) OR (TIME(SFrom) <= Shift_TimeOutPeriod1 AND TIME(STo) >= Shift_TimeOutPeriod1)) THEN
				SET ReadyOut1 = 1;
			END IF;
			IF Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeIn2 AND TIME(STo) >= Shift_TimeIn2) OR (TIME(SFrom) <= Shift_TimeInPeriod2 AND TIME(STo) >= Shift_TimeInPeriod2)) THEN
				SET ReadyIn2 = 1;
			END IF;
			IF Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeOut2 AND TIME(STo) >= Shift_TimeOut2) OR (TIME(SFrom) <= Shift_TimeOutPeriod2 AND TIME(STo) >= Shift_TimeOutPeriod2)) THEN
				SET ReadyOut2 = 1;
			END IF;
			IF Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeIn3 AND TIME(STo) >= Shift_TimeIn3) OR (TIME(SFrom) <= Shift_TimeInPeriod3 AND TIME(STo) >= Shift_TimeInPeriod3)) THEN
				SET ReadyIn3 = 1;
			END IF;
			IF Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeOut3 AND TIME(STo) >= Shift_TimeOut3) OR (TIME(SFrom) <= Shift_TimeOutPeriod3 AND TIME(STo) >= Shift_TimeOutPeriod3)) THEN
				SET ReadyOut3 = 1;
			END IF;
			IF Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeIn4 AND TIME(STo) >= Shift_TimeIn4) OR (TIME(SFrom) <= Shift_TimeInPeriod4 AND TIME(STo) >= Shift_TimeInPeriod4)) THEN
				SET ReadyIn4 = 1;
			END IF;
			IF Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeOut4 AND TIME(STo) >= Shift_TimeOut4) OR (TIME(SFrom) <= Shift_TimeOutPeriod4 AND TIME(STo) >= Shift_TimeOutPeriod4)) THEN
				SET ReadyOut4 = 1;
			END IF;
			IF Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeIn5 AND TIME(STo) >= Shift_TimeIn5) OR (TIME(SFrom) <= Shift_TimeInPeriod5 AND TIME(STo) >= Shift_TimeInPeriod5)) THEN
				SET ReadyIn5 = 1;
			END IF;
			IF Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeOut5 AND TIME(STo) >= Shift_TimeOut5) OR (TIME(SFrom) <= Shift_TimeOutPeriod5 AND TIME(STo) >= Shift_TimeOutPeriod5))  THEN
				SET ReadyOut5 = 1;
			END IF;
			
			IF (ReadyIn1 = 1 AND ReadyOut1 = 0) OR (ReadyIn1 = 0 AND ReadyOut1 = 1) THEN
				IF ReadyIn1 = 1 THEN
					SET LeaveDurationInOut1 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo), Shift_TimeIn1), TIME(STo), TimeBreak1, 'TimeIn');
					SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In1;'); 
				ELSEIF ReadyOut1 = 1 THEN
					SET LeaveDurationInOut1 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut1, TIME(SFrom)), TIME(SFrom), TimeBreak1, 'TimeOut');
					SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out1;'); 
				END IF;
			ELSEIF ReadyIn1 = 1 AND ReadyOut1 = 1 THEN
				SET LeaveDurationInOut1 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut1,Shift_TimeIn1), '00:00:00', TimeBreak1, 'TimeLeave');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out1;'); 
			END IF;

			IF (ReadyIn2 = 1 AND ReadyOut2 = 0) OR (ReadyIn2 = 0 AND ReadyOut2 = 1) THEN
				IF ReadyIn2 = 1 THEN
					SET LeaveDurationInOut2 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo),Shift_TimeIn2), TIME(STo), TimeBreak2, 'TimeIn');
					SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In2;'); 
				ELSEIF ReadyOut2 = 1 THEN
					SET LeaveDurationInOut2 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut2, TIME(SFrom)), TIME(SFrom), TimeBreak2, 'TimeOut');
					SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out2;'); 
				END IF;
			ELSEIF ReadyIn2 = 1 AND ReadyOut2 = 1 THEN
				SET LeaveDurationInOut2 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut2,Shift_TimeIn2), '00:00:00', TimeBreak2, 'TimeLeave');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out2;'); 
			END IF;

			IF (ReadyIn3 = 1 AND ReadyOut3 = 0) OR (ReadyIn3 = 0 AND ReadyOut3 = 1) THEN
				IF ReadyIn3 = 1 THEN
					SET LeaveDurationInOut3 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo),Shift_TimeIn3), TIME(STo), TimeBreak3, 'TimeIn');
					SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In3;'); 
				ELSEIF ReadyOut3 = 1 THEN
					SET LeaveDurationInOut3 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut3, TIME(SFrom)), TIME(SFrom), TimeBreak3, 'TimeOut');
					SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out3;'); 
				END IF;
			ELSEIF ReadyIn3 = 1 AND ReadyOut3 = 1 THEN
				SET LeaveDurationInOut3 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut3,Shift_TimeIn3), '00:00:00', TimeBreak3, 'TimeLeave');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out3;'); 
			END IF;

			IF (ReadyIn4 = 1 AND ReadyOut4 = 0) OR (ReadyIn4 = 0 AND ReadyOut4 = 1) THEN
				IF ReadyIn4 = 1 THEN
					SET LeaveDurationInOut4 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo),Shift_TimeIn4), TIME(STo), TimeBreak4, 'TimeIn');
				ELSEIF ReadyOut4 = 1 THEN
					SET LeaveDurationInOut4 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut4, TIME(SFrom)), TIME(SFrom), TimeBreak4, 'TimeOut');
				END IF;
			ELSEIF ReadyIn4 = 1 AND ReadyOut4 = 1 THEN
				SET LeaveDurationInOut4 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut4,Shift_TimeIn4), '00:00:00', TimeBreak4, 'TimeLeave');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out4;'); 
			END IF;

			IF (ReadyIn5 = 1 AND ReadyOut5 = 0) OR (ReadyIn5 = 0 AND ReadyOut5 = 1) THEN
				IF ReadyIn5 = 1 THEN
					SET LeaveDurationInOut5 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo),Shift_TimeIn5), TIME(STo), TimeBreak5, 'TimeIn');
					SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In5;');
				ELSEIF ReadyOut5 = 1 THEN
					SET LeaveDurationInOut5 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut5, TIME(SFrom)), TIME(SFrom), TimeBreak5, 'TimeOut');
					SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out5;');
				END IF;
			ELSEIF ReadyIn5 = 1 AND ReadyOut5 = 1 THEN
				SET LeaveDurationInOut5 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut5,Shift_TimeIn5), '00:00:00', TimeBreak5, 'TimeLeave');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out5;'); 
			END IF;

		END IF;

		IF CheckOutLeave LIKE CONCAT('%', TIME(SFrom), '-', TIME(STo), ';%') THEN
			SET CheckOutLeave = REPLACE(CheckOutLeave, CONCAT(TIME(SFrom), '-', TIME(STo), ';'), '');
		END IF;

		IF CheckExist	> 0 THEN
			UPDATE hrm_timesheet_attendance SET Att_In1=In1,Att_Out1=Out1,Att_In2=In2,Att_Out2=Out2,Att_In3=In3,Att_Out3=Out3,Att_In4=In4,Att_Out4=Out4,Att_In5=In5,Att_Out5=Out5,Att_OvertimeIn=OverIn,Att_OvertimeOut=OverOut,Att_Other1=O1,Att_Other2=O2,Att_LeaveDurationInOut1=LeaveDurationInOut1,Att_LeaveDurationInOut2=LeaveDurationInOut2,Att_LeaveDurationInOut3=LeaveDurationInOut3,Att_LeaveDurationInOut4=LeaveDurationInOut4,Att_LeaveDurationInOut5=LeaveDurationInOut5,Att_LeaveDurationStatus=LeaveDurationStatus,Att_OutLeave=CheckOutLeave WHERE Att_FPID=FPID AND Att_Date=FPDate;
		ELSE
			INSERT INTO hrm_timesheet_attendance(Att_EmpID,Att_FPID,Att_Date,Att_In1,Att_Out1,Att_In2,Att_Out2,Att_In3,Att_Out3,Att_In4,Att_Out4,Att_In5,Att_Out5,Att_OvertimeIn,Att_OvertimeOut,Att_Other1,Att_Other2,Att_LeaveDurationInOut1,Att_LeaveDurationInOut2,Att_LeaveDurationInOut3,Att_LeaveDurationInOut4,Att_LeaveDurationInOut5,Att_LeaveDurationStatus,Att_OutLeave) VALUES (SEmpID,FPID,DATE(SFrom),In1,Out1,In2,Out2,In3,Out3,In4,Out4,In5,Out5,OverIn,OverOut,O1,O2,LeaveDurationInOut1,LeaveDurationInOut2,LeaveDurationInOut3,LeaveDurationInOut4,LeaveDurationInOut5,LeaveDurationStatus,CheckOutLeave);
		END IF;
		
		IF LOWER(ShiftType) = 'normal' THEN
			CALL spHRMCheckAttendanceNormal(SEmpID,ShiftID,FPID,DATE(SFrom));
		ELSE
			CALL spHRMCheckAttendanceRoster(SEmpID,ShiftID,FPID,DATE(SFrom));
		END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAttendanceLeaveFullDay`;
DELIMITER |
CREATE PROCEDURE `spHRMAttendanceLeaveFullDay`(SEmpID varchar(255),SFrom datetime, STo datetime)
    DETERMINISTIC
BEGIN
	DECLARE ShiftType VARCHAR(255) DEFAULT('');	
	DECLARE ShiftID VARCHAR(255) DEFAULT('');	

	DECLARE Shift_ID VARCHAR(255);
	DECLARE Shift_Day VARCHAR(255);
	DECLARE Shift_TimeIn1 TIME;
	DECLARE Shift_TimeInPeriod1 TIME;
	DECLARE Shift_TimeOut1 TIME;
	DECLARE Shift_TimeOutPeriod1 TIME;
	DECLARE Shift_TimeIn2 TIME;
	DECLARE Shift_TimeInPeriod2 TIME;
	DECLARE Shift_TimeOut2 TIME;
	DECLARE Shift_TimeOutPeriod2 TIME;
	DECLARE Shift_TimeIn3 TIME;
	DECLARE Shift_TimeInPeriod3 TIME;
	DECLARE Shift_TimeOut3 TIME;
	DECLARE Shift_TimeOutPeriod3 TIME;
	DECLARE Shift_TimeIn4 TIME;
	DECLARE Shift_TimeInPeriod4 TIME;
	DECLARE Shift_TimeOut4 TIME;
	DECLARE Shift_TimeOutPeriod4 TIME;
	DECLARE Shift_TimeIn5 TIME;
	DECLARE Shift_TimeInPeriod5 TIME;
	DECLARE Shift_TimeOut5 TIME;
	DECLARE Shift_TimeOutPeriod5 TIME;
	DECLARE Shift_TimeInOvertime TIME;
	DECLARE Shift_TimeOutOvertime TIME;

	DECLARE LeaveDurationInOut1 TIME DEFAULT('00:00:00');
	DECLARE LeaveDurationInOut2 TIME DEFAULT('00:00:00');
	DECLARE LeaveDurationInOut3 TIME DEFAULT('00:00:00');
	DECLARE LeaveDurationInOut4 TIME DEFAULT('00:00:00');
	DECLARE LeaveDurationInOut5 TIME DEFAULT('00:00:00');

	DECLARE FPID VARCHAR(255)DEFAULT('');
	DECLARE FPDate DATE;
	DECLARE In1 TIME DEFAULT('00:00:00');
	DECLARE In2 TIME DEFAULT('00:00:00');
	DECLARE In3 TIME DEFAULT('00:00:00');
	DECLARE In4 TIME DEFAULT('00:00:00');
	DECLARE In5 TIME DEFAULT('00:00:00');
	DECLARE Out1 TIME DEFAULT('00:00:00');
	DECLARE Out2 TIME DEFAULT('00:00:00');
	DECLARE Out3 TIME DEFAULT('00:00:00');
	DECLARE Out4 TIME DEFAULT('00:00:00');
	DECLARE Out5 TIME DEFAULT('00:00:00');
	DECLARE OverIn TIME DEFAULT('00:00:00');
	DECLARE OverOut TIME DEFAULT('00:00:00');
	DECLARE O1 TIME DEFAULT('00:00:00');
	DECLARE O2 TIME DEFAULT('00:00:00');

	DECLARE TimeBreak1 VARCHAR(255) DEFAULT('');
	DECLARE TimeBreak2 VARCHAR(255) DEFAULT('');
	DECLARE TimeBreak3 VARCHAR(255) DEFAULT('');
	DECLARE TimeBreak4 VARCHAR(255) DEFAULT('');
	DECLARE TimeBreak5 VARCHAR(255) DEFAULT('');
	
	DECLARE TempDate DATE;
	DECLARE CheckExist TINYINT DEFAULT(0);
	
	SET TempDate = DATE(SFrom);

	SELECT e.var_hrm_shift_type,e.var_hrm_shift_id,e.var_hrm_fpid INTO ShiftType,ShiftID,FPID FROM ame_mt_emp e WHERE e.var_id = SEmpID;

	WHILE TempDate <= DATE(STo) DO

	SET In1 = '00:00:00';
	SET In2 = '00:00:00';
	SET In3 = '00:00:00';
	SET In4 = '00:00:00';
	SET In5 = '00:00:00';
	SET Out1 = '00:00:00';
	SET Out2 = '00:00:00';
	SET Out3 = '00:00:00';
	SET Out4 = '00:00:00';
	SET Out5 = '00:00:00';

		SELECT COUNT(*) INTO CheckExist FROM  hrm_timesheet_attendance att WHERE att.Att_FPID = FPID AND att.Att_Date = TempDate;
		IF CheckExist > 0 THEN
			SELECT Att_FPID,Att_Date,Att_In1,Att_Out1,Att_In2,Att_Out2,Att_In3,Att_Out3,Att_In4,Att_Out4,Att_In5,Att_Out5,Att_OvertimeIn,Att_OvertimeOut,Att_Other1,Att_Other2 INTO FPID,FPDate,In1,Out1,In2,Out2,In3,Out3,In4,Out4,In5,Out5,OverIn,OverOut,O1,O2 FROM hrm_timesheet_attendance att WHERE att.Att_FPID = FPID AND att.Att_Date = TempDate;
		END IF;
		IF LOWER(ShiftType) = 'normal' THEN
			SELECT wd.Shift_ID,wd.Shift_Day,wd.Shift_TimeIn1,wd.Shift_TimeInPeriod1,wd.Shift_TimeOut1,wd.Shift_TimeOutPeriod1,wd.Shift_TimeIn2,wd.Shift_TimeInPeriod2,wd.Shift_TimeOut2,wd.Shift_TimeOutPeriod2,wd.Shift_TimeIn3,wd.Shift_TimeInPeriod3,wd.Shift_TimeOut3,wd.Shift_TimeOutPeriod3,wd.Shift_TimeIn4,wd.Shift_TimeInPeriod4,wd.Shift_TimeOut4,wd.Shift_TimeOutPeriod4,wd.Shift_TimeIn5,wd.Shift_TimeInPeriod5,wd.Shift_TimeOut5,wd.Shift_TimeOutPeriod5,wd.Shift_TimeInOvertime,wd.Shift_TimeOutOvertime,Shift_TimeBreak1,Shift_TimeBreak2,Shift_TimeBreak3,Shift_TimeBreak4,Shift_TimeBreak5 INTO Shift_ID, Shift_Day, Shift_TimeIn1, Shift_TimeInPeriod1, Shift_TimeOut1, Shift_TimeOutPeriod1, Shift_TimeIn2, Shift_TimeInPeriod2, Shift_TimeOut2, Shift_TimeOutPeriod2, Shift_TimeIn3, Shift_TimeInPeriod3, Shift_TimeOut3, Shift_TimeOutPeriod3, Shift_TimeIn4, Shift_TimeInPeriod4, Shift_TimeOut4, Shift_TimeOutPeriod4, Shift_TimeIn5, Shift_TimeInPeriod5, Shift_TimeOut5, Shift_TimeOutPeriod5, Shift_TimeInOvertime, Shift_TimeOutOvertime, TimeBreak1, TimeBreak2, TimeBreak3, TimeBreak4, TimeBreak5 FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID = ShiftID AND LOWER(wd.Shift_Day) = LOWER(DAYNAME(TempDate));
		ELSE
			SELECT wd.Shift_ID,wd.Shift_Day,wd.Shift_TimeIn1,wd.Shift_TimeInPeriod1,wd.Shift_TimeOut1,wd.Shift_TimeOutPeriod1,wd.Shift_TimeIn2,wd.Shift_TimeInPeriod2,wd.Shift_TimeOut2,wd.Shift_TimeOutPeriod2,wd.Shift_TimeIn3,wd.Shift_TimeInPeriod3,wd.Shift_TimeOut3,wd.Shift_TimeOutPeriod3,wd.Shift_TimeIn4,wd.Shift_TimeInPeriod4,wd.Shift_TimeOut4,wd.Shift_TimeOutPeriod4,wd.Shift_TimeIn5,wd.Shift_TimeInPeriod5,wd.Shift_TimeOut5,wd.Shift_TimeOutPeriod5,wd.Shift_TimeInOvertime,wd.Shift_TimeOutOvertime,Shift_TimeBreak1,Shift_TimeBreak2,Shift_TimeBreak3,Shift_TimeBreak4,Shift_TimeBreak5 INTO Shift_ID, Shift_Day, Shift_TimeIn1, Shift_TimeInPeriod1, Shift_TimeOut1, Shift_TimeOutPeriod1, Shift_TimeIn2, Shift_TimeInPeriod2, Shift_TimeOut2, Shift_TimeOutPeriod2, Shift_TimeIn3, Shift_TimeInPeriod3, Shift_TimeOut3, Shift_TimeOutPeriod3, Shift_TimeIn4, Shift_TimeInPeriod4, Shift_TimeOut4, Shift_TimeOutPeriod4, Shift_TimeIn5, Shift_TimeInPeriod5, Shift_TimeOut5, Shift_TimeOutPeriod5, Shift_TimeInOvertime, Shift_TimeOutOvertime, TimeBreak1, TimeBreak2, TimeBreak3, TimeBreak4, TimeBreak5 FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID = (SELECT Roster_ShiftID FROM hrm_timesheet_roster WHERE Roster_Date = TempDate AND Roster_EmpID = SEmpID);
		END IF;

		IF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' THEN
			SET LeaveDurationInOut1 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut1,Shift_TimeIn1), '00:00:00', TimeBreak1, 'TimeLeave');
		END IF;
		IF Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' THEN
			SET LeaveDurationInOut2 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut2,Shift_TimeIn2), '00:00:00', TimeBreak2, 'TimeLeave');
		END IF;
		IF Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' THEN
			SET LeaveDurationInOut3 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut3,Shift_TimeIn3), '00:00:00', TimeBreak3, 'TimeLeave');
		END IF;
		IF Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' THEN
			SET LeaveDurationInOut4 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut4,Shift_TimeIn4), '00:00:00', TimeBreak4, 'TimeLeave');
		END IF;
		IF Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' THEN
			SET LeaveDurationInOut5 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut5,Shift_TimeIn5), '00:00:00', TimeBreak5, 'TimeLeave');
		END IF;

		IF CheckExist	> 0 THEN
			UPDATE hrm_timesheet_attendance SET 
			Att_In1= IF(Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Att_In1 = '00:00:00', '00:00:01', Att_In1),
			Att_Out1=IF(Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Att_Out1 = '00:00:00', '00:00:01', Att_Out1),
			Att_In2=IF(Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Att_In2 = '00:00:00', '00:00:01', Att_In2),
			Att_Out2=IF(Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Att_Out2 = '00:00:00', '00:00:01', Att_Out2),
			Att_In3=IF(Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND Att_In3 = '00:00:00', '00:00:01', Att_In3),
			Att_Out3=IF(Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND Att_Out3 = '00:00:00', '00:00:01', Att_Out3),
			Att_In4=IF(Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND Att_In4 = '00:00:00', '00:00:01', Att_In4),
			Att_Out4=IF(Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND Att_Out4 = '00:00:00', '00:00:01', Att_Out4),
			Att_In5=IF(Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND Att_In5 = '00:00:00', '00:00:01', Att_In5),
			Att_Out5=IF(Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND Att_Out5 = '00:00:00', '00:00:01', Att_Out5),
			Att_OvertimeIn=OverIn,
			Att_OvertimeOut=OverOut,
			Att_Other1=O1,
			Att_Other2=O2,
			Att_Status='',
			Att_RStatus='',
			Att_LeaveDurationInOut1=LeaveDurationInOut1,
			Att_LeaveDurationInOut2=LeaveDurationInOut2,
			Att_LeaveDurationInOut3=LeaveDurationInOut3,
			Att_LeaveDurationInOut4=LeaveDurationInOut4,
			Att_LeaveDurationInOut5=LeaveDurationInOut5
			WHERE Att_FPID=FPID AND Att_Date=TempDate;
		ELSE
			INSERT INTO hrm_timesheet_attendance(Att_EmpID,Att_FPID,Att_Date,Att_In1,Att_Out1,Att_In2,Att_Out2,Att_In3,Att_Out3,Att_In4,Att_Out4,Att_In5,Att_Out5,Att_OvertimeIn,Att_OvertimeOut,Att_Other1,Att_Other2,Att_Status,Att_RStatus,Att_LeaveDurationInOut1,Att_LeaveDurationInOut2,Att_LeaveDurationInOut3,Att_LeaveDurationInOut4,Att_LeaveDurationInOut5) VALUES (SEmpID,FPID,TempDate,
			IF(Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Att_In1 = '00:00:00', '00:00:01', '00:00:00'),
			IF(Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Att_Out1 = '00:00:00', '00:00:01', '00:00:00'),
			IF(Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Att_In2 = '00:00:00', '00:00:01', '00:00:00'),
			IF(Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Att_Out2 = '00:00:00', '00:00:01', '00:00:00'),
			IF(Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND Att_In3 = '00:00:00', '00:00:01', '00:00:00'),
			IF(Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND Att_Out3 = '00:00:00', '00:00:01', '00:00:00'),
			IF(Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND Att_In4 = '00:00:00', '00:00:01', '00:00:00'),
			IF(Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND Att_Out4 = '00:00:00', '00:00:01', '00:00:00'),
			IF(Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND Att_In5 = '00:00:00', '00:00:01', '00:00:00'),
			IF(Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND Att_Out5 = '00:00:00', '00:00:01', '00:00:00'),OverIn,OverOut,O1,O2,'','',LeaveDurationInOut1,LeaveDurationInOut2,LeaveDurationInOut3,LeaveDurationInOut4,LeaveDurationInOut5);
		END IF;

		IF LOWER(ShiftType) = 'normal' THEN
			CALL spHRMCheckAttendanceNormal(SEmpID,ShiftID,FPID,TempDate);
		ELSE
			CALL spHRMCheckAttendanceRoster(SEmpID,ShiftID,FPID,TempDate);
		END IF;

		SET TempDate = DATE_ADD(TempDate,INTERVAL 1 DAY);
	END WHILE;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAttendanceLeaveHourly`;
DELIMITER |
CREATE PROCEDURE `spHRMAttendanceLeaveHourly`(SEmpID varchar(255),SFrom datetime, STo datetime)
    DETERMINISTIC
BEGIN
	DECLARE ShiftType VARCHAR(255) DEFAULT('');	
	DECLARE ShiftID VARCHAR(255) DEFAULT('');	

	DECLARE Shift_ID VARCHAR(255);
	DECLARE Shift_Day VARCHAR(255);
	DECLARE Shift_TimeIn1 TIME;
	DECLARE Shift_TimeInPeriod1 TIME;
	DECLARE Shift_TimeOut1 TIME;
	DECLARE Shift_TimeOutPeriod1 TIME;
	DECLARE Shift_TimeIn2 TIME;
	DECLARE Shift_TimeInPeriod2 TIME;
	DECLARE Shift_TimeOut2 TIME;
	DECLARE Shift_TimeOutPeriod2 TIME;
	DECLARE Shift_TimeIn3 TIME;
	DECLARE Shift_TimeInPeriod3 TIME;
	DECLARE Shift_TimeOut3 TIME;
	DECLARE Shift_TimeOutPeriod3 TIME;
	DECLARE Shift_TimeIn4 TIME;
	DECLARE Shift_TimeInPeriod4 TIME;
	DECLARE Shift_TimeOut4 TIME;
	DECLARE Shift_TimeOutPeriod4 TIME;
	DECLARE Shift_TimeIn5 TIME;
	DECLARE Shift_TimeInPeriod5 TIME;
	DECLARE Shift_TimeOut5 TIME;
	DECLARE Shift_TimeOutPeriod5 TIME;
	DECLARE Shift_TimeInOvertime TIME;
	DECLARE Shift_TimeOutOvertime TIME;

	DECLARE LeaveDurationStatus VARCHAR(255) DEFAULT('');
	DECLARE LeaveDurationInOut1 TIME DEFAULT('00:00:00');
	DECLARE LeaveDurationInOut2 TIME DEFAULT('00:00:00');
	DECLARE LeaveDurationInOut3 TIME DEFAULT('00:00:00');
	DECLARE LeaveDurationInOut4 TIME DEFAULT('00:00:00');
	DECLARE LeaveDurationInOut5 TIME DEFAULT('00:00:00');

	DECLARE FPID VARCHAR(255)DEFAULT('');
	DECLARE FPDate DATE;
	DECLARE In1 TIME DEFAULT('00:00:00');
	DECLARE In2 TIME DEFAULT('00:00:00');
	DECLARE In3 TIME DEFAULT('00:00:00');
	DECLARE In4 TIME DEFAULT('00:00:00');
	DECLARE In5 TIME DEFAULT('00:00:00');
	DECLARE Out1 TIME DEFAULT('00:00:00');
	DECLARE Out2 TIME DEFAULT('00:00:00');
	DECLARE Out3 TIME DEFAULT('00:00:00');
	DECLARE Out4 TIME DEFAULT('00:00:00');
	DECLARE Out5 TIME DEFAULT('00:00:00');
	DECLARE OverIn TIME DEFAULT('00:00:00');
	DECLARE OverOut TIME DEFAULT('00:00:00');
	DECLARE O1 TIME DEFAULT('00:00:00');
	DECLARE O2 TIME DEFAULT('00:00:00');

	DECLARE TimeBreak1 VARCHAR(255) DEFAULT('');
	DECLARE TimeBreak2 VARCHAR(255) DEFAULT('');
	DECLARE TimeBreak3 VARCHAR(255) DEFAULT('');
	DECLARE TimeBreak4 VARCHAR(255) DEFAULT('');
	DECLARE TimeBreak5 VARCHAR(255) DEFAULT('');

	DECLARE CheckAttendanceOutLeave TINYINT DEFAULT(1);
	DECLARE CheckOutLeave VARCHAR(255) DEFAULT('');
	DECLARE CheckAttendanceOutLeaveReady TINYINT DEFAULT(0);

	DECLARE ReadyIn1 TINYINT DEFAULT(0);
	DECLARE ReadyIn2 TINYINT DEFAULT(0);
	DECLARE ReadyIn3 TINYINT DEFAULT(0);
	DECLARE ReadyIn4 TINYINT DEFAULT(0);
	DECLARE ReadyIn5 TINYINT DEFAULT(0);
	DECLARE ReadyOut1 TINYINT DEFAULT(0);
	DECLARE ReadyOut2 TINYINT DEFAULT(0);
	DECLARE ReadyOut3 TINYINT DEFAULT(0);
	DECLARE ReadyOut4 TINYINT DEFAULT(0);
	DECLARE ReadyOut5 TINYINT DEFAULT(0);
	
	DECLARE CheckExist TINYINT DEFAULT(0);

	SELECT e.Emp_ShiftType,e.Emp_ShiftID,e.Emp_FPID INTO ShiftType,ShiftID,FPID FROM tblemployee e WHERE e.EmpID = SEmpID;

		SELECT COUNT(*) INTO CheckExist FROM  hrm_timesheet_attendance att WHERE att.Att_FPID = FPID AND att.Att_Date = DATE(SFrom);
		IF CheckExist > 0 THEN
			SELECT Att_FPID,Att_Date,Att_In1,Att_Out1,Att_In2,Att_Out2,Att_In3,Att_Out3,Att_In4,Att_Out4,Att_In5,Att_Out5,Att_OvertimeIn,Att_OvertimeOut,Att_Other1,Att_Other2,Att_OutLeave INTO FPID,FPDate,In1,Out1,In2,Out2,In3,Out3,In4,Out4,In5,Out5,OverIn,OverOut,O1,O2,CheckOutLeave FROM hrm_timesheet_attendance att WHERE att.Att_FPID = FPID AND att.Att_Date = DATE(SFrom);
		END IF;
		IF LOWER(ShiftType) = 'normal' THEN
			SELECT wd.Shift_ID,wd.Shift_Day,wd.Shift_TimeIn1,wd.Shift_TimeInPeriod1,wd.Shift_TimeOut1,wd.Shift_TimeOutPeriod1,wd.Shift_TimeIn2,wd.Shift_TimeInPeriod2,wd.Shift_TimeOut2,wd.Shift_TimeOutPeriod2,wd.Shift_TimeIn3,wd.Shift_TimeInPeriod3,wd.Shift_TimeOut3,wd.Shift_TimeOutPeriod3,wd.Shift_TimeIn4,wd.Shift_TimeInPeriod4,wd.Shift_TimeOut4,wd.Shift_TimeOutPeriod4,wd.Shift_TimeIn5,wd.Shift_TimeInPeriod5,wd.Shift_TimeOut5,wd.Shift_TimeOutPeriod5,wd.Shift_TimeInOvertime,wd.Shift_TimeOutOvertime,Shift_TimeBreak1,Shift_TimeBreak2,Shift_TimeBreak3,Shift_TimeBreak4,Shift_TimeBreak5 INTO Shift_ID, Shift_Day, Shift_TimeIn1, Shift_TimeInPeriod1, Shift_TimeOut1, Shift_TimeOutPeriod1, Shift_TimeIn2, Shift_TimeInPeriod2, Shift_TimeOut2, Shift_TimeOutPeriod2, Shift_TimeIn3, Shift_TimeInPeriod3, Shift_TimeOut3, Shift_TimeOutPeriod3, Shift_TimeIn4, Shift_TimeInPeriod4, Shift_TimeOut4, Shift_TimeOutPeriod4, Shift_TimeIn5, Shift_TimeInPeriod5, Shift_TimeOut5, Shift_TimeOutPeriod5, Shift_TimeInOvertime, Shift_TimeOutOvertime, TimeBreak1, TimeBreak2, TimeBreak3, TimeBreak4, TimeBreak5 FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID = ShiftID AND LOWER(wd.Shift_Day) = LOWER(DAYNAME(DATE(SFrom)));
		ELSE
			SELECT wd.Shift_ID,wd.Shift_Day,wd.Shift_TimeIn1,wd.Shift_TimeInPeriod1,wd.Shift_TimeOut1,wd.Shift_TimeOutPeriod1,wd.Shift_TimeIn2,wd.Shift_TimeInPeriod2,wd.Shift_TimeOut2,wd.Shift_TimeOutPeriod2,wd.Shift_TimeIn3,wd.Shift_TimeInPeriod3,wd.Shift_TimeOut3,wd.Shift_TimeOutPeriod3,wd.Shift_TimeIn4,wd.Shift_TimeInPeriod4,wd.Shift_TimeOut4,wd.Shift_TimeOutPeriod4,wd.Shift_TimeIn5,wd.Shift_TimeInPeriod5,wd.Shift_TimeOut5,wd.Shift_TimeOutPeriod5,wd.Shift_TimeInOvertime,wd.Shift_TimeOutOvertime,Shift_TimeBreak1,Shift_TimeBreak2,Shift_TimeBreak3,Shift_TimeBreak4,Shift_TimeBreak5 INTO Shift_ID, Shift_Day, Shift_TimeIn1, Shift_TimeInPeriod1, Shift_TimeOut1, Shift_TimeOutPeriod1, Shift_TimeIn2, Shift_TimeInPeriod2, Shift_TimeOut2, Shift_TimeOutPeriod2, Shift_TimeIn3, Shift_TimeInPeriod3, Shift_TimeOut3, Shift_TimeOutPeriod3, Shift_TimeIn4, Shift_TimeInPeriod4, Shift_TimeOut4, Shift_TimeOutPeriod4, Shift_TimeIn5, Shift_TimeInPeriod5, Shift_TimeOut5, Shift_TimeOutPeriod5, Shift_TimeInOvertime, Shift_TimeOutOvertime, TimeBreak1, TimeBreak2, TimeBreak3, TimeBreak4, TimeBreak5 FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID = (SELECT Roster_ShiftID FROM hrm_timesheet_roster WHERE Roster_Date = DATE(SFrom) AND Roster_EmpID = SEmpID);
		END IF;


		IF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND In1 = '00:00:00' AND ((TIME(SFrom) <= Shift_TimeIn1 AND TIME(STo) >= Shift_TimeIn1) OR (TIME(SFrom) <= Shift_TimeInPeriod1 AND TIME(STo) >= Shift_TimeInPeriod1)) THEN
			SET In1 = '00:00:01';
			SET CheckAttendanceOutLeave = 0; 
		END IF;

		IF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Out1 = '00:00:00' AND ((TIME(SFrom) <= Shift_TimeOut1 AND TIME(STo) >= Shift_TimeOut1) OR (TIME(SFrom) <= Shift_TimeOutPeriod1 AND TIME(STo) >= Shift_TimeOutPeriod1)) THEN
			SET Out1 = '00:00:01';
			SET CheckAttendanceOutLeave = 0;
		END IF;

		IF Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND In2 = '00:00:00' AND ((TIME(SFrom) <= Shift_TimeIn2 AND TIME(STo) >= Shift_TimeIn2) OR (TIME(SFrom) <= Shift_TimeInPeriod2 AND TIME(STo) >= Shift_TimeInPeriod2)) THEN
			SET In2 = '00:00:01';
			SET CheckAttendanceOutLeave = 0;
		END IF;

		IF Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Out2 = '00:00:00' AND ((TIME(SFrom) <= Shift_TimeOut2 AND TIME(STo) >= Shift_TimeOut2) OR (TIME(SFrom) <= Shift_TimeOutPeriod2 AND TIME(STo) >= Shift_TimeOutPeriod2)) THEN
			SET Out2 = '00:00:01';
			SET CheckAttendanceOutLeave = 0;
		END IF;

		IF Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND In3 = '00:00:00' AND ((TIME(SFrom) <= Shift_TimeIn3 AND TIME(STo) >= Shift_TimeIn3) OR (TIME(SFrom) <= Shift_TimeInPeriod3 AND TIME(STo) >= Shift_TimeInPeriod3)) THEN
			SET In3 = '00:00:01';
			SET CheckAttendanceOutLeave = 0;
		END IF;

		IF Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND Out3 = '00:00:00' AND ((TIME(SFrom) <= Shift_TimeOut3 AND TIME(STo) >= Shift_TimeOut3) OR (TIME(SFrom) <= Shift_TimeOutPeriod3 AND TIME(STo) >= Shift_TimeOutPeriod3)) THEN
			SET Out3 = '00:00:01';
			SET CheckAttendanceOutLeave = 0;
		END IF;

		IF Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND In4 = '00:00:00' AND ((TIME(SFrom) <= Shift_TimeIn4 AND TIME(STo) >= Shift_TimeIn4) OR (TIME(SFrom) <= Shift_TimeInPeriod4 AND TIME(STo) >= Shift_TimeInPeriod4)) THEN
			SET In4 = '00:00:01';
			SET CheckAttendanceOutLeave = 0;
		END IF;

		IF Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND Out4 = '00:00:00' AND ((TIME(SFrom) <= Shift_TimeOut4 AND TIME(STo) >= Shift_TimeOut4) OR (TIME(SFrom) <= Shift_TimeOutPeriod4 AND TIME(STo) >= Shift_TimeOutPeriod4)) THEN
			SET Out4 = '00:00:01';
			SET CheckAttendanceOutLeave = 0;
		END IF;

		IF Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND In5 = '00:00:00' AND ((TIME(SFrom) <= Shift_TimeIn5 AND TIME(STo) >= Shift_TimeIn5) OR (TIME(SFrom) <= Shift_TimeInPeriod5 AND TIME(STo) >= Shift_TimeInPeriod5)) THEN
			SET In5 = '00:00:01';
			SET CheckAttendanceOutLeave = 0;
		END IF;

		IF Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND Out5 = '00:00:00' AND ((TIME(SFrom) <= Shift_TimeOut5 AND TIME(STo) >= Shift_TimeOut5) OR (TIME(SFrom) <= Shift_TimeOutPeriod5 AND TIME(STo) >= Shift_TimeOutPeriod5))  THEN
			SET Out5 = '00:00:01';
			SET CheckAttendanceOutLeave = 0;
		END IF;

		/*IF In1 = '00:00:00' AND Out1 = '00:00:00' AND In2 = '00:00:00' AND Out2 = '00:00:00' AND In3 = '00:00:00' AND Out3 = '00:00:00' AND In4 = '00:00:00' AND Out4 = '00:00:00' AND In5 = '00:00:00' AND Out5 = '00:00:00' AND O1 <> '00:00:01' THEN
			SET O1 = '00:00:01';
		ELSEIF In1 = '00:00:00' AND Out1 = '00:00:00' AND In2 = '00:00:00' AND Out2 = '00:00:00' AND In3 = '00:00:00' AND Out3 = '00:00:00' AND In4 = '00:00:00' AND Out4 = '00:00:00' AND In5 = '00:00:00' AND Out5 = '00:00:00' AND O1 = '00:00:01' AND O2 <> '00:00:01' THEN
			SET O2 = '00:00:01';
		END IF;*/

		-- Check Leave Duration
		IF (In1 = '00:00:01' AND Out1 = '00:00:00') OR (In1 = '00:00:00' AND Out1 = '00:00:01') THEN
			IF In1 = '00:00:01' THEN
				SET LeaveDurationInOut1 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo), Shift_TimeIn1), TIME(STo), TimeBreak1, 'TimeIn');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In1;'); 
			ELSEIF Out1 = '00:00:01' THEN
				SET LeaveDurationInOut1 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut1, TIME(SFrom)), TIME(SFrom), TimeBreak1, 'TimeOut');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out1;'); 
			END IF;
			SET In1 = '00:00:00';
			SET Out1 = '00:00:00';
		ELSEIF In1 = '00:00:01' AND Out1 = '00:00:01' THEN
			SET LeaveDurationInOut1 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut1,Shift_TimeIn1), '00:00:00', TimeBreak1, 'TimeLeave');
		ELSEIF In1 = '00:00:01' AND Out1 <> '00:00:01' AND Out1 <> '00:00:00' THEN
			SET LeaveDurationInOut1 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo), Shift_TimeIn1), TIME(STo), TimeBreak1, 'TimeIn');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In1;'); 
			SET In1 = '00:00:00';
		ELSEIF In1 <> '00:00:01' AND In1 <> '00:00:00' AND  Out1 = '00:00:01' THEN
			SET LeaveDurationInOut1 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut1, TIME(SFrom)), TIME(SFrom), TimeBreak1, 'TimeOut');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out1;'); 
			SET Out1 = '00:00:00';
		END IF;

		IF (In2 = '00:00:01' AND Out2 = '00:00:00') OR (In2 = '00:00:00' AND Out2 = '00:00:01') THEN
			IF In2 = '00:00:01' THEN
				SET LeaveDurationInOut2 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo),Shift_TimeIn2), TIME(STo), TimeBreak2, 'TimeIn');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In2;'); 
			ELSEIF Out2 = '00:00:01' THEN
				SET LeaveDurationInOut2 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut2, TIME(SFrom)), TIME(SFrom), TimeBreak2, 'TimeOut');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out2;'); 
			END IF;
			SET In2 = '00:00:00';
			SET Out2 = '00:00:00';
		ELSEIF In2 = '00:00:01' AND Out2 = '00:00:01' THEN
			SET LeaveDurationInOut2 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut2,Shift_TimeIn2), '00:00:00', TimeBreak2, 'TimeLeave');
		ELSEIF In2 = '00:00:01' AND Out2 <> '00:00:01' AND Out2 <> '00:00:00' THEN
			SET LeaveDurationInOut2 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo), Shift_TimeIn2), TIME(STo), TimeBreak2, 'TimeIn');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In2;'); 
			SET In2 = '00:00:00';
		ELSEIF In2 <> '00:00:01' AND In2 <> '00:00:00' AND  Out2 = '00:00:01' THEN
			SET LeaveDurationInOut2 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut2, TIME(SFrom)), TIME(SFrom), TimeBreak2, 'TimeOut');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out2;'); 
			SET Out2 = '00:00:00';
		END IF;

		IF (In3 = '00:00:01' AND Out3 = '00:00:00') OR (In3 = '00:00:00' AND Out3 = '00:00:01') THEN
			IF In3 = '00:00:01' THEN
				SET LeaveDurationInOut3 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo),Shift_TimeIn3), TIME(STo), TimeBreak3, 'TimeIn');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In3;'); 
			ELSEIF Out3 = '00:00:01' THEN
				SET LeaveDurationInOut3 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut3, TIME(SFrom)), TIME(SFrom), TimeBreak3, 'TimeOut');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out3;'); 
			END IF;
			SET In3 = '00:00:00';
			SET Out3 = '00:00:00';
		ELSEIF In3 = '00:00:01' AND Out3 = '00:00:01' THEN
			SET LeaveDurationInOut3 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut3,Shift_TimeIn3), '00:00:00', TimeBreak3, 'TimeLeave');
		ELSEIF In3 = '00:00:01' AND Out3 <> '00:00:01' AND Out3 <> '00:00:00' THEN
			SET LeaveDurationInOut3 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo), Shift_TimeIn3), TIME(STo), TimeBreak3, 'TimeIn');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In3;'); 
			SET In3 = '00:00:00';
		ELSEIF In3 <> '00:00:01' AND In3 <> '00:00:00' AND  Out3 = '00:00:01' THEN
			SET LeaveDurationInOut3 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut3, TIME(SFrom)), TIME(SFrom), TimeBreak3, 'TimeOut');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out3;'); 
			SET Out3 = '00:00:00';
		END IF;

		IF (In4 = '00:00:01' AND Out4 = '00:00:00') OR (In4 = '00:00:00' AND Out4 = '00:00:01') THEN
			IF In4 = '00:00:01' THEN
				SET LeaveDurationInOut4 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo),Shift_TimeIn4), TIME(STo), TimeBreak4, 'TimeIn');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In4;');
			ELSEIF Out4 = '00:00:01' THEN
				SET LeaveDurationInOut4 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut4, TIME(SFrom)), TIME(SFrom), TimeBreak4, 'TimeOut');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out4;');
			END IF;
			SET In4 = '00:00:00';
			SET Out4 = '00:00:00';
		ELSEIF In4 = '00:00:01' AND Out4 = '00:00:01' THEN
			SET LeaveDurationInOut4 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut4,Shift_TimeIn4), '00:00:00', TimeBreak4, 'TimeLeave');
		ELSEIF In4 = '00:00:01' AND Out4 <> '00:00:01' AND Out4 <> '00:00:00' THEN
			SET LeaveDurationInOut4 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo), Shift_TimeIn4), TIME(STo), TimeBreak4, 'TimeIn');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In4;'); 
			SET In4 = '00:00:00';
		ELSEIF In4 <> '00:00:01' AND In4 <> '00:00:00' AND  Out4 = '00:00:01' THEN
			SET LeaveDurationInOut4 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut4, TIME(SFrom)), TIME(SFrom), TimeBreak4, 'TimeOut');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out4;'); 
			SET Out4 = '00:00:00';
		END IF;

		IF (In5 = '00:00:01' AND Out5 = '00:00:00') OR (In5 = '00:00:00' AND Out5 = '00:00:01') THEN
			IF In5 = '00:00:01' THEN
				SET LeaveDurationInOut5 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo),Shift_TimeIn5), TIME(STo), TimeBreak5, 'TimeIn');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In5;');
			ELSEIF Out5 = '00:00:01' THEN
				SET LeaveDurationInOut5 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut5, TIME(SFrom)), TIME(SFrom), TimeBreak5, 'TimeOut');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out5;');
			END IF;
			SET In5 = '00:00:00';
			SET Out5 = '00:00:00';
		ELSEIF In5 = '00:00:01' AND Out5 = '00:00:01' THEN
			SET LeaveDurationInOut5 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut5,Shift_TimeIn5), '00:00:00', TimeBreak5, 'TimeLeave');
		ELSEIF In5 = '00:00:01' AND Out5 <> '00:00:01' AND Out5 <> '00:00:00' THEN
			SET LeaveDurationInOut5 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo), Shift_TimeIn5), TIME(STo), TimeBreak5, 'TimeIn');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In5;'); 
			SET In5 = '00:00:00';
		ELSEIF In5 <> '00:00:01' AND In5 <> '00:00:00' AND  Out5 = '00:00:01' THEN
			SET LeaveDurationInOut5 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut5, TIME(SFrom)), TIME(SFrom), TimeBreak5, 'TimeOut');
			SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out5;'); 
			SET Out5 = '00:00:00';
		END IF;
		
		IF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND In1 <> '00:00:00' AND In1 <> '00:00:01' AND Out1 <> '00:00:00' AND Out1 <> '00:00:01' AND In2 <> '00:00:00' AND In2 <> '00:00:01' AND Out2 <> '00:00:00' AND Out2 <> '00:00:01' AND In3 <> '00:00:00' AND In3 <> '00:00:01' AND Out3 <> '00:00:00' AND Out3 <> '00:00:01'AND In4 <> '00:00:00' AND In4 <> '00:00:01' AND Out4 <> '00:00:00' AND Out4 <> '00:00:01' AND In5 <> '00:00:00' AND In5 <> '00:00:01' AND Out5 <> '00:00:00' AND Out5 <> '00:00:01' THEN
			SET CheckAttendanceOutLeaveReady = 1;
		ELSEIF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND In1 <> '00:00:00' AND In1 <> '00:00:01' AND Out1 <> '00:00:00' AND Out1 <> '00:00:01' AND In2 <> '00:00:00' AND In2 <> '00:00:01' AND Out2 <> '00:00:00' AND Out2 <> '00:00:01' AND In3 <> '00:00:00' AND In3 <> '00:00:01' AND Out3 <> '00:00:00' AND Out3 <> '00:00:01' AND In4 <> '00:00:00' AND In4 <> '00:00:01' AND Out4 <> '00:00:00' AND Out4 <> '00:00:01' THEN
			SET CheckAttendanceOutLeaveReady = 1;
		ELSEIF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND In1 <> '00:00:00' AND In1 <> '00:00:01' AND Out1 <> '00:00:00' AND Out1 <> '00:00:01' AND In2 <> '00:00:00' AND In2 <> '00:00:01' AND Out2 <> '00:00:00' AND Out2 <> '00:00:01' AND In3 <> '00:00:00' AND In3 <> '00:00:01' AND Out3 <> '00:00:00' AND Out3 <> '00:00:01' THEN
			SET CheckAttendanceOutLeaveReady = 1;
		ELSEIF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND In1 <> '00:00:00' AND In1 <> '00:00:01' AND Out1 <> '00:00:00' AND Out1 <> '00:00:01' AND In2 <> '00:00:00' AND In2 <> '00:00:01' AND Out2 <> '00:00:00' AND Out2 <> '00:00:01' THEN
			SET CheckAttendanceOutLeaveReady = 1;
		ELSEIF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND In1 <> '00:00:00' AND In1 <> '00:00:01' AND Out1 <> '00:00:00' AND Out1 <> '00:00:01' THEN
			SET CheckAttendanceOutLeaveReady = 1;
		END IF;
		
		IF CheckAttendanceOutLeaveReady = 1 THEN
			IF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeIn1 AND TIME(STo) >= Shift_TimeIn1) OR (TIME(SFrom) <= Shift_TimeInPeriod1 AND TIME(STo) >= Shift_TimeInPeriod1)) THEN
				SET ReadyIn1 = 1;
			END IF;
			IF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeOut1 AND TIME(STo) >= Shift_TimeOut1) OR (TIME(SFrom) <= Shift_TimeOutPeriod1 AND TIME(STo) >= Shift_TimeOutPeriod1)) THEN
				SET ReadyOut1 = 1;
			END IF;
			IF Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeIn2 AND TIME(STo) >= Shift_TimeIn2) OR (TIME(SFrom) <= Shift_TimeInPeriod2 AND TIME(STo) >= Shift_TimeInPeriod2)) THEN
				SET ReadyIn2 = 1;
			END IF;
			IF Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeOut2 AND TIME(STo) >= Shift_TimeOut2) OR (TIME(SFrom) <= Shift_TimeOutPeriod2 AND TIME(STo) >= Shift_TimeOutPeriod2)) THEN
				SET ReadyOut2 = 1;
			END IF;
			IF Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeIn3 AND TIME(STo) >= Shift_TimeIn3) OR (TIME(SFrom) <= Shift_TimeInPeriod3 AND TIME(STo) >= Shift_TimeInPeriod3)) THEN
				SET ReadyIn3 = 1;
			END IF;
			IF Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeOut3 AND TIME(STo) >= Shift_TimeOut3) OR (TIME(SFrom) <= Shift_TimeOutPeriod3 AND TIME(STo) >= Shift_TimeOutPeriod3)) THEN
				SET ReadyOut3 = 1;
			END IF;
			IF Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeIn4 AND TIME(STo) >= Shift_TimeIn4) OR (TIME(SFrom) <= Shift_TimeInPeriod4 AND TIME(STo) >= Shift_TimeInPeriod4)) THEN
				SET ReadyIn4 = 1;
			END IF;
			IF Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeOut4 AND TIME(STo) >= Shift_TimeOut4) OR (TIME(SFrom) <= Shift_TimeOutPeriod4 AND TIME(STo) >= Shift_TimeOutPeriod4)) THEN
				SET ReadyOut4 = 1;
			END IF;
			IF Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeIn5 AND TIME(STo) >= Shift_TimeIn5) OR (TIME(SFrom) <= Shift_TimeInPeriod5 AND TIME(STo) >= Shift_TimeInPeriod5)) THEN
				SET ReadyIn5 = 1;
			END IF;
			IF Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND ((TIME(SFrom) <= Shift_TimeOut5 AND TIME(STo) >= Shift_TimeOut5) OR (TIME(SFrom) <= Shift_TimeOutPeriod5 AND TIME(STo) >= Shift_TimeOutPeriod5))  THEN
				SET ReadyOut5 = 1;
			END IF;
			
			IF (ReadyIn1 = 1 AND ReadyOut1 = 0) OR (ReadyIn1 = 0 AND ReadyOut1 = 1) THEN
				IF ReadyIn1 = 1 THEN
					SET LeaveDurationInOut1 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo), Shift_TimeIn1), TIME(STo), TimeBreak1, 'TimeIn');
					SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In1;'); 
				ELSEIF ReadyOut1 = 1 THEN
					SET LeaveDurationInOut1 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut1, TIME(SFrom)), TIME(SFrom), TimeBreak1, 'TimeOut');
					SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out1;'); 
				END IF;
			ELSEIF ReadyIn1 = 1 AND ReadyOut1 = 1 THEN
				SET LeaveDurationInOut1 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut1,Shift_TimeIn1), '00:00:00', TimeBreak1, 'TimeLeave');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out1;'); 
			END IF;

			IF (ReadyIn2 = 1 AND ReadyOut2 = 0) OR (ReadyIn2 = 0 AND ReadyOut2 = 1) THEN
				IF ReadyIn2 = 1 THEN
					SET LeaveDurationInOut2 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo),Shift_TimeIn2), TIME(STo), TimeBreak2, 'TimeIn');
					SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In2;'); 
				ELSEIF ReadyOut2 = 1 THEN
					SET LeaveDurationInOut2 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut2, TIME(SFrom)), TIME(SFrom), TimeBreak2, 'TimeOut');
					SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out2;'); 
				END IF;
			ELSEIF ReadyIn2 = 1 AND ReadyOut2 = 1 THEN
				SET LeaveDurationInOut2 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut2,Shift_TimeIn2), '00:00:00', TimeBreak2, 'TimeLeave');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out2;'); 
			END IF;

			IF (ReadyIn3 = 1 AND ReadyOut3 = 0) OR (ReadyIn3 = 0 AND ReadyOut3 = 1) THEN
				IF ReadyIn3 = 1 THEN
					SET LeaveDurationInOut3 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo),Shift_TimeIn3), TIME(STo), TimeBreak3, 'TimeIn');
					SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In3;'); 
				ELSEIF ReadyOut3 = 1 THEN
					SET LeaveDurationInOut3 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut3, TIME(SFrom)), TIME(SFrom), TimeBreak3, 'TimeOut');
					SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out3;'); 
				END IF;
			ELSEIF ReadyIn3 = 1 AND ReadyOut3 = 1 THEN
				SET LeaveDurationInOut3 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut3,Shift_TimeIn3), '00:00:00', TimeBreak3, 'TimeLeave');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out3;'); 
			END IF;

			IF (ReadyIn4 = 1 AND ReadyOut4 = 0) OR (ReadyIn4 = 0 AND ReadyOut4 = 1) THEN
				IF ReadyIn4 = 1 THEN
					SET LeaveDurationInOut4 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo),Shift_TimeIn4), TIME(STo), TimeBreak4, 'TimeIn');
				ELSEIF ReadyOut4 = 1 THEN
					SET LeaveDurationInOut4 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut4, TIME(SFrom)), TIME(SFrom), TimeBreak4, 'TimeOut');
				END IF;
			ELSEIF ReadyIn4 = 1 AND ReadyOut4 = 1 THEN
				SET LeaveDurationInOut4 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut4,Shift_TimeIn4), '00:00:00', TimeBreak4, 'TimeLeave');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out4;'); 
			END IF;

			IF (ReadyIn5 = 1 AND ReadyOut5 = 0) OR (ReadyIn5 = 0 AND ReadyOut5 = 1) THEN
				IF ReadyIn5 = 1 THEN
					SET LeaveDurationInOut5 = fnHRMCheckBreakTime(TIMEDIFF(TIME(STo),Shift_TimeIn5), TIME(STo), TimeBreak5, 'TimeIn');
					SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'In5;');
				ELSEIF ReadyOut5 = 1 THEN
					SET LeaveDurationInOut5 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut5, TIME(SFrom)), TIME(SFrom), TimeBreak5, 'TimeOut');
					SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out5;');
				END IF;
			ELSEIF ReadyIn5 = 1 AND ReadyOut5 = 1 THEN
				SET LeaveDurationInOut5 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut5,Shift_TimeIn5), '00:00:00', TimeBreak5, 'TimeLeave');
				SET LeaveDurationStatus = CONCAT(LeaveDurationStatus, 'Out5;'); 
			END IF;

		END IF;

		IF CheckAttendanceOutLeaveReady = 0 AND CheckAttendanceOutLeave = 1 AND CheckOutLeave NOT LIKE CONCAT('%', TIME(SFrom), '-', TIME(STo), ';%') THEN
			SET CheckOutLeave = CONCAT(CheckOutLeave, TIME(SFrom), '-', TIME(STo), ';');
		END IF;

		IF CheckExist	> 0 THEN
			UPDATE hrm_timesheet_attendance SET Att_In1=In1,Att_Out1=Out1,Att_In2=In2,Att_Out2=Out2,Att_In3=In3,Att_Out3=Out3,Att_In4=In4,Att_Out4=Out4,Att_In5=In5,Att_Out5=Out5,Att_OvertimeIn=OverIn,Att_OvertimeOut=OverOut,Att_Other1=O1,Att_Other2=O2,Att_LeaveDurationInOut1=LeaveDurationInOut1,Att_LeaveDurationInOut2=LeaveDurationInOut2,Att_LeaveDurationInOut3=LeaveDurationInOut3,Att_LeaveDurationInOut4=LeaveDurationInOut4,Att_LeaveDurationInOut5=LeaveDurationInOut5,Att_LeaveDurationStatus=LeaveDurationStatus,Att_OutLeave=CheckOutLeave WHERE Att_FPID=FPID AND Att_Date=DATE(SFrom);
		ELSE
			INSERT INTO hrm_timesheet_attendance(Att_EmpID,Att_FPID,Att_Date,Att_In1,Att_Out1,Att_In2,Att_Out2,Att_In3,Att_Out3,Att_In4,Att_Out4,Att_In5,Att_Out5,Att_OvertimeIn,Att_OvertimeOut,Att_Other1,Att_Other2,Att_Status,Att_RStatus,Att_LeaveDurationInOut1,Att_LeaveDurationInOut2,Att_LeaveDurationInOut3,Att_LeaveDurationInOut4,Att_LeaveDurationInOut5,Att_LeaveDurationStatus,Att_OutLeave) VALUES (SEmpID,FPID,DATE(SFrom),In1,Out1,In2,Out2,In3,Out3,In4,Out4,In5,Out5,OverIn,OverOut,O1,O2,'','',LeaveDurationInOut1,LeaveDurationInOut2,LeaveDurationInOut3,LeaveDurationInOut4,LeaveDurationInOut5,LeaveDurationStatus,CheckOutLeave);
		END IF;
		IF LOWER(ShiftType) = 'normal' THEN
			CALL spHRMCheckAttendanceNormal(SEmpID,ShiftID,FPID,DATE(SFrom));
		ELSE
			CALL spHRMCheckAttendanceRoster(SEmpID,ShiftID,FPID,DATE(SFrom));
		END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAuthGetDayoff`;
DELIMITER |
CREATE PROCEDURE `spHRMAuthGetDayoff`(userid varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE CheckU VARCHAR(255) DEFAULT("");
	DECLARE SYear INT DEFAULT(0);
	DECLARE SEmpID VARCHAR(255) DEFAULT("");
	DECLARE SAuthID VARCHAR(255) DEFAULT("");

	SELECT var_hrm_utype, var_empid INTO CheckU, SEmpID FROM ame_user u WHERE u.var_id = userid;

	SELECT Dayoff_AuthID INTO SAuthID FROM hrm_timesheet_dayoff WHERE Dayoff_ID = ID;
	
	IF CheckU = "ESS" THEN
		SELECT df.Dayoff_ID,df.Dayoff_Date,df.Dayoff_EmpID,df.Dayoff_Description,df.Dayoff_Status FROM hrm_timesheet_dayoff df WHERE df.Dayoff_ID = ID AND (df.Dayoff_ID IN(SELECT RecordID FROM hrm_log WHERE RecordID = ID AND FrmSysName = "Dayoff" AND ActionType = "insert" AND UID = userid) OR df.Dayoff_EmpID = SEmpID OR df.Dayoff_ID IN (SELECT Auth_ProcessID FROM hrm_authorisation_approved WHERE Auth_ProcessName = 'Dayoff' AND Auth_ProcessID = ID AND Auth_EmpID = SEmpID));

		SELECT a.Auth_ID,a.Auth_Name,a.Auth_Type,a.Auth_AndOr,a.Auth_Amount, fnHRMCheckAuthorisationApproved(ID, 'Dayoff', SAuthID) AS 'Auth_Approved' FROM hrm_authorisation_temp a WHERE a.Auth_ID = SAuthID AND a.Auth_TranID = ID;

		SELECT a.Auth_ID,a.Auth_EmpID,a.Auth_GroupID,a.Auth_GroupAndOr,a.Auth_GroupAmount,
		COALESCE(b.var_id, '') AS EmpID, COALESCE(b.var_name, '') AS EmpName, COALESCE(b.var_email, '') AS EmpEmail, COALESCE(b.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level',COALESCE(u.var_name, '') AS UName,app.Auth_Status 
		FROM hrm_authorisation_detail_temp a
		LEFT JOIN hrm_authorisation_approved app ON(app.Auth_ID = SAuthID AND app.Auth_ProcessID = ID AND app.Auth_ProcessName = "Dayoff" AND a.Auth_EmpID = app.Auth_EmpID AND a.Auth_GroupID = app.Auth_GroupID AND a.Auth_TranID = app.Auth_ProcessID)
		LEFT JOIN ame_mt_emp b ON(a.Auth_EmpID = b.var_id) 
		LEFT JOIN ame_user u ON(u.var_empid = b.var_id) 
		LEFT JOIN ame_mt_pos pos ON(b.var_posid = pos.var_id)
		WHERE a.Auth_TranID = ID AND a.Auth_ID = SAuthID;
		
		SELECT a.AuthGroup_ID,a.AuthGroup_Name,a.AuthGroup_Description,d.Auth_GroupID,COALESCE(d.Auth_GroupAndOr,"") as "Auth_GroupAndOr",COALESCE(d.Auth_GroupAmount,"") as "AuthGroup_Amount",(SELECT COUNT(ds.AuthGroup_ID) FROM hrm_authorisation_group_detail_temp ds WHERE ds.AuthGroup_ID = a.AuthGroup_ID AND ds.Auth_TranID = ID) as 'Count'
		,(SELECT COUNT(ds.Auth_GroupID) FROM hrm_authorisation_approved ds WHERE ds.Auth_ProcessID = ID AND ds.Auth_GroupID = a.AuthGroup_ID AND ds.Auth_ID = SAuthID AND ds.Auth_Status = "approved") AS 'AuthGroup_Approved'
		FROM hrm_authorisation_group_temp a
		INNER JOIN hrm_authorisation_detail_temp d ON(d.Auth_GroupID = a.AuthGroup_ID AND d.Auth_ID = SAuthID AND a.Auth_TranID = ID)
		WHERE a.Auth_TranID = ID
		ORDER BY a.AuthGroup_ID DESC;
		
		SELECT a.AuthGroup_ID,a.AuthGroup_EmpID,
		COALESCE(b.var_id, '') AS EmpID, COALESCE(b.var_name, '') AS EmpName, COALESCE(b.var_email, '') AS EmpEmail, COALESCE(b.var_hrm_company_email, '') AS Emp_CompanyEmail,COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level',COALESCE(u.var_name, '') AS UName,app.Auth_Status
		FROM hrm_authorisation_group_detail_temp a
		INNER JOIN hrm_authorisation_detail_temp d ON(a.AuthGroup_ID = d.Auth_GroupID AND d.Auth_ID = SAuthID AND a.Auth_TranID = d.Auth_TranID)
		LEFT JOIN hrm_authorisation_approved app ON(app.Auth_ID = SAuthID AND app.Auth_GroupID = a.AuthGroup_ID AND app.Auth_ProcessID = ID AND app.Auth_ProcessName = "Dayoff" AND app.Auth_EmpID = a.AuthGroup_EmpID)
		LEFT JOIN ame_mt_emp b ON(a.AuthGroup_EmpID = b.var_id)  
		LEFT JOIN ame_user u ON(u.var_empid = b.var_id) 
		LEFT JOIN ame_mt_pos pos ON(b.var_posid = pos.var_id)
		WHERE a.Auth_TranID = ID AND d.Auth_ID = SAuthID
		ORDER BY a.AuthGroup_EmpID, a.AuthGroup_ID;
		
	
		CALL spHRMGetDayoffSub(userid);

	ELSEIF CheckU = "Normal" OR CheckU = "Administrator" THEN
		SELECT df.Dayoff_ID,df.Dayoff_Date,df.Dayoff_EmpID,df.Dayoff_Description,df.Dayoff_Status FROM hrm_timesheet_dayoff df WHERE df.Dayoff_ID = ID ;

		SELECT a.Auth_ID,a.Auth_Name,a.Auth_Type,a.Auth_AndOr,a.Auth_Amount, fnHRMCheckAuthorisationApproved(ID, 'Dayoff', SAuthID) AS 'Auth_Approved' FROM hrm_authorisation_temp a WHERE a.Auth_ID = SAuthID AND a.Auth_TranID = ID;

		SELECT a.Auth_ID,a.Auth_EmpID,a.Auth_GroupID,a.Auth_GroupAndOr,a.Auth_GroupAmount,
		COALESCE(b.var_id, '') AS EmpID, COALESCE(b.var_name, '') AS EmpName, COALESCE(b.var_email, '') AS EmpEmail, COALESCE(b.var_hrm_company_email, '') AS Emp_CompanyEmail,COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level',COALESCE(u.var_name, '') AS UName,app.Auth_Status
		FROM hrm_authorisation_detail_temp a
		LEFT JOIN hrm_authorisation_approved app ON(app.Auth_ID = SAuthID AND app.Auth_ProcessID = ID AND app.Auth_ProcessName = "Dayoff" AND a.Auth_EmpID = app.Auth_EmpID AND a.Auth_GroupID = app.Auth_GroupID AND a.Auth_TranID = app.Auth_ProcessID)
		LEFT JOIN ame_mt_emp b ON(a.Auth_EmpID = b.var_id)  
		LEFT JOIN ame_user u ON(u.var_empid = b.var_id) 
		LEFT JOIN ame_mt_pos pos ON(b.var_posid = pos.var_id)
		WHERE a.Auth_TranID = ID AND a.Auth_ID = SAuthID;

		SELECT a.AuthGroup_ID,a.AuthGroup_Name,a.AuthGroup_Description,d.Auth_GroupID,COALESCE(d.Auth_GroupAndOr,"") as "Auth_GroupAndOr",COALESCE(d.Auth_GroupAmount,"") as "AuthGroup_Amount",(SELECT COUNT(ds.AuthGroup_ID) FROM hrm_authorisation_group_detail_temp ds WHERE ds.AuthGroup_ID = a.AuthGroup_ID AND ds.Auth_TranID = ID) as 'Count'
		,(SELECT COUNT(ds.Auth_GroupID) FROM hrm_authorisation_approved ds WHERE ds.Auth_ProcessID = ID AND ds.Auth_GroupID = a.AuthGroup_ID AND ds.Auth_ID = SAuthID AND ds.Auth_Status = "approved") AS 'AuthGroup_Approved'
		FROM hrm_authorisation_group_temp a
		INNER JOIN hrm_authorisation_detail_temp d ON(d.Auth_GroupID = a.AuthGroup_ID AND d.Auth_ID = SAuthID AND a.Auth_TranID = ID)
		WHERE a.Auth_TranID = ID
		ORDER BY a.AuthGroup_ID DESC;

		SELECT a.AuthGroup_ID,a.AuthGroup_EmpID,
		COALESCE(b.var_id, '') AS EmpID, COALESCE(b.var_name, '') AS EmpName, COALESCE(b.var_email, '') AS EmpEmail, COALESCE(b.var_hrm_company_email, '') AS Emp_CompanyEmail,COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level',COALESCE(u.var_name, '') AS UName,app.Auth_Status
		FROM hrm_authorisation_group_detail_temp a
		INNER JOIN hrm_authorisation_detail_temp d ON(a.AuthGroup_ID = d.Auth_GroupID AND d.Auth_ID = SAuthID AND a.Auth_TranID = d.Auth_TranID)
		LEFT JOIN hrm_authorisation_approved app ON(app.Auth_ID = SAuthID AND app.Auth_GroupID = a.AuthGroup_ID AND app.Auth_ProcessID = ID AND app.Auth_ProcessName = "Dayoff" AND app.Auth_EmpID = a.AuthGroup_EmpID)
		LEFT JOIN ame_mt_emp b ON(a.AuthGroup_EmpID = b.var_id) 
		LEFT JOIN ame_user u ON(u.var_empid = b.var_id) 
		LEFT JOIN ame_mt_pos pos ON(b.var_posid = pos.var_id)
		WHERE a.Auth_TranID = ID AND d.Auth_ID = SAuthID
		ORDER BY a.AuthGroup_EmpID, a.AuthGroup_ID;
	
		CALL spHRMGetDayoffSub(userid);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAuthGetLeaveID`;
DELIMITER |
CREATE PROCEDURE `spHRMAuthGetLeaveID`(userid varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE CheckU VARCHAR(255) DEFAULT("");
	DECLARE SYear INT DEFAULT(0);
	DECLARE SEmpID VARCHAR(255) DEFAULT("");
	DECLARE SDuration VARCHAR(255) DEFAULT("");
	DECLARE SAuthID VARCHAR(255) DEFAULT("");

	DECLARE WorkHour FLOAT DEFAULT(8);
	DECLARE Deduct_Leave_Balance_Hourly VARCHAR(255);

	DECLARE SNow DATE;
	DECLARE tz VARCHAR(20) DEFAULT('');

	SELECT Setting_Value INTO tz FROM hrm_setting WHERE Setting_Type = 'TimeZone' AND Setting_Name = 'TimeZone';
	SET SNow = convert_tz(now(), @@session.time_zone, tz);

	SELECT u.var_hrm_utype INTO CheckU FROM ame_user u WHERE u.var_id = userid;
	SELECT Leave_AuthID INTO SAuthID FROM hrm_timesheet_leave WHERE Leave_ID = ID;

	BEGIN
			DECLARE Cur CURSOR FOR
			SELECT SQL_CALC_FOUND_ROWS Leave_EmpID FROM hrm_timesheet_leave WHERE Leave_ID = ID LIMIT 1;
			OPEN Cur;
				SET @C = FOUND_ROWS();
				IF @C > 0 THEN
						FETCH Cur INTO SEmpID;
				END IF;
			CLOSE Cur;
	END;
	BEGIN
			DECLARE Cur CURSOR FOR
			SELECT SQL_CALC_FOUND_ROWS Payroll_AmtWorkingHourPerDay FROM hrm_payroll_salary
			LEFT JOIN hrm_payroll ON(Payroll_ID = Salary_PayrollID)
			WHERE Salary_EmpID = SEmpID AND LOWER(Salary_Status) = 'active';
			OPEN Cur;
				SET @C = FOUND_ROWS();
				IF @C > 0 THEN
						FETCH Cur INTO WorkHour;
				END IF;
			CLOSE Cur;
	END;

	SELECT Setting_Value INTO Deduct_Leave_Balance_Hourly FROM hrm_setting WHERE Setting_Type = 'Leave' AND Setting_Name = 'Deduct_Leave_Balance_Hourly';
	
	
	IF CheckU = "ESS" THEN
		SELECT Leave_ID,Leave_EmpID,Leave_Tel,Leave_Email,Leave_Reason,Leave_From,Leave_To,Leave_Description,Leave_AttachmentName,Leave_AttachmentPath,Leave_Status,
		COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level',COALESCE(u.var_name, '') AS UName, COALESCE(e.var_hrm_department_id, '') AS Emp_DepartmentID, d.Department_Name, COALESCE(e.var_hrm_branch_id, '') AS Emp_BranchID, br.Branch_Name, COALESCE(e.var_hrm_grade, '') AS Emp_Grade, COALESCE(e.var_hrm_type, '') AS Emp_Type, COALESCE(e.var_hrm_category, '') AS Emp_Category, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, COALESCE(e.var_hrm_sex, '') AS EmpSex
		FROM hrm_timesheet_leave l
		LEFT JOIN ame_mt_emp e ON(l.Leave_EmpID = e.var_id)  
		LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
		LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
		LEFT JOIN hrm_emp_department d ON(d.Department_ID = e.var_hrm_department_id)
		LEFT JOIN hrm_emp_branch br ON(br.Branch_ID = e.var_hrm_branch_id)
		WHERE Leave_ID = ID AND (Leave_ID IN(SELECT RecordID FROM hrm_log WHERE RecordID = ID AND FrmSysName = "Leave" AND ActionType = "insert" AND UID = userid) OR Leave_EmpID = (SELECT var_empid FROM ame_user WHERE var_id = userid) OR Leave_ID IN(SELECT Auth_ProcessID FROM hrm_authorisation_approved WHERE Auth_ProcessName = 'Leave' AND Auth_ProcessID = ID AND Auth_EmpID =(SELECT var_empid FROM ame_user WHERE var_id = userid)));

		SELECT LeaveD_ID,LeaveD_Date,LeaveD_Duration,LeaveD_TypeID,LeaveD_TimeFrom,LeaveD_TimeTo 
		,lt.LeaveType_ID,lt.LeaveType_Name,lt.LeaveType_PayStatus,lt.LeaveType_Year,lt.LeaveType_AmountAllowed,lt.LeaveType_GenderRestriction,lt.LeaveType_PayType,lt.LeaveType_PayAmount
		FROM hrm_timesheet_leave_detail ld 
		LEFT JOIN hrm_timesheet_leave_type lt ON(lt.LeaveType_ID = ld.LeaveD_TypeID)
		WHERE ld.LeaveD_ID = ID AND (LeaveD_ID IN(SELECT RecordID FROM hrm_log WHERE RecordID = ID AND FrmSysName = "Leave" AND ActionType = "insert" AND UID = userid) OR ld.LeaveD_ID IN(SELECT Leave_ID FROM hrm_timesheet_leave WHERE Leave_ID = ID AND Leave_EmpID = (SELECT var_empid FROM ame_user WHERE var_id = userid)) OR ld.LeaveD_ID IN(SELECT Auth_ProcessID FROM hrm_authorisation_approved WHERE Auth_ProcessName = 'Leave' AND Auth_ProcessID = ID AND Auth_EmpID =(SELECT var_empid FROM ame_user WHERE var_id = userid)));

		-- SELECT YEAR(Leave_From),Leave_EmpID,Leave_Duration INTO SYear,SEmpID,SDuration FROM hrm_timesheet_leave WHERE Leave_ID = ID;
		-- CALL spHRMGetLeaveSubSearch(SEmpID, SYear, SDuration);

	ELSEIF CheckU = "Normal" OR CheckU = "Administrator" THEN
		SELECT Leave_ID,Leave_EmpID,Leave_Tel,Leave_Email,Leave_Reason,Leave_From,Leave_To,Leave_Description,Leave_AttachmentName,Leave_AttachmentPath,Leave_Status,
		COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level',COALESCE(u.var_name, '') AS UName, COALESCE(e.var_hrm_department_id, '') AS Emp_DepartmentID, d.Department_Name, COALESCE(e.var_hrm_branch_id, '') AS Emp_BranchID, br.Branch_Name, COALESCE(e.var_hrm_grade, '') AS Emp_Grade, COALESCE(e.var_hrm_type, '') AS Emp_Type, COALESCE(e.var_hrm_category, '') AS Emp_Category, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, COALESCE(e.var_hrm_sex, '') AS EmpSex
		FROM hrm_timesheet_leave l
		LEFT JOIN ame_mt_emp e ON(l.Leave_EmpID = e.var_id)  
		LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
		LEFT JOIN hrm_emp_department d ON(d.Department_ID = e.var_hrm_department_id)
		LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
		LEFT JOIN hrm_emp_branch br ON(br.Branch_ID = e.var_hrm_branch_id)
		WHERE Leave_ID = ID ;

		SELECT LeaveD_ID,LeaveD_Date,LeaveD_Duration,LeaveD_TypeID,LeaveD_TimeFrom,LeaveD_TimeTo 
		,lt.LeaveType_ID,lt.LeaveType_Name,lt.LeaveType_PayStatus,lt.LeaveType_Year,lt.LeaveType_AmountAllowed,lt.LeaveType_GenderRestriction,lt.LeaveType_PayType,lt.LeaveType_PayAmount
		FROM hrm_timesheet_leave_detail ld
		LEFT JOIN hrm_timesheet_leave_type lt ON(lt.LeaveType_ID = ld.LeaveD_TypeID)
		WHERE ld.LeaveD_ID = ID ;
	
		-- SELECT YEAR(Leave_From),Leave_EmpID,Leave_Duration INTO SYear,SEmpID,SDuration FROM hrm_timesheet_leave WHERE Leave_ID = ID;
		-- CALL spHRMGetLeaveSubSearch(SEmpID, SYear, SDuration);

	END IF;

	SELECT a.Auth_ID,a.Auth_Name,a.Auth_Type,a.Auth_AndOr,a.Auth_Amount, fnHRMCheckAuthorisationApproved(ID, 'Leave', SAuthID) AS 'Auth_Approved' FROM hrm_authorisation_temp a WHERE a.Auth_ID = SAuthID AND a.Auth_TranID = ID;

	SELECT a.Auth_ID,a.Auth_EmpID,a.Auth_GroupID,a.Auth_GroupAndOr,a.Auth_GroupAmount,
	COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level',COALESCE(u.var_name, '') AS UName,app.Auth_Status 
	FROM hrm_authorisation_detail_temp a
	LEFT JOIN hrm_authorisation_approved app ON(app.Auth_ID = SAuthID AND app.Auth_ProcessID = ID AND app.Auth_ProcessName = "Leave" AND a.Auth_EmpID = app.Auth_EmpID AND a.Auth_GroupID = app.Auth_GroupID AND a.Auth_TranID = app.Auth_ProcessID)
	LEFT JOIN ame_mt_emp e ON(a.Auth_EmpID = e.var_id) 
	LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
	LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id) 
	WHERE a.Auth_TranID = ID AND a.Auth_ID = SAuthID;

	SELECT a.AuthGroup_ID,a.AuthGroup_Name,a.AuthGroup_Description,d.Auth_GroupID,COALESCE(d.Auth_GroupAndOr,"") as "Auth_GroupAndOr",COALESCE(d.Auth_GroupAmount,"") as "AuthGroup_Amount",(SELECT COUNT(ds.AuthGroup_ID) FROM hrm_authorisation_group_detail_temp ds WHERE ds.AuthGroup_ID = a.AuthGroup_ID AND ds.Auth_TranID = ID) as 'Count'
	,(SELECT COUNT(ds.Auth_GroupID) FROM hrm_authorisation_approved ds WHERE ds.Auth_ProcessID = ID AND ds.Auth_GroupID = a.AuthGroup_ID AND ds.Auth_ID = SAuthID AND ds.Auth_Status = "approved") AS 'AuthGroup_Approved'
	FROM hrm_authorisation_group_temp a
	INNER JOIN hrm_authorisation_detail_temp d ON(d.Auth_GroupID = a.AuthGroup_ID AND d.Auth_ID = SAuthID AND a.Auth_TranID = ID)
	WHERE a.Auth_TranID = ID
	ORDER BY a.AuthGroup_ID DESC;

	SELECT a.AuthGroup_ID,a.AuthGroup_EmpID,
	COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level',COALESCE(u.var_name, '') AS UName,app.Auth_Status  
	FROM hrm_authorisation_group_detail_temp a
	INNER JOIN hrm_authorisation_detail_temp d ON(a.AuthGroup_ID = d.Auth_GroupID AND d.Auth_ID = SAuthID AND a.Auth_TranID = d.Auth_TranID)
	LEFT JOIN hrm_authorisation_approved app ON(app.Auth_ID = SAuthID AND app.Auth_GroupID = a.AuthGroup_ID AND app.Auth_ProcessID = ID AND app.Auth_ProcessName = "Leave" AND app.Auth_EmpID = a.AuthGroup_EmpID)
	LEFT JOIN ame_mt_emp e ON(a.AuthGroup_EmpID = e.var_id) 
	LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
	LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
	WHERE a.Auth_TranID = ID AND d.Auth_ID = SAuthID
	ORDER BY a.AuthGroup_EmpID, a.AuthGroup_ID;

	IF Deduct_Leave_Balance_Hourly = 'Half of Day' THEN
			SELECT Deduct_Leave_Balance_Hourly, lt.LeaveType_ID, lt.LeaveType_Name, fnHRMCheckLeaveBaanceRate(SEmpID, lt.LeaveType_BaseBalance, COALESCE(lt.LeaveType_AmountAllowed, 0)) AS 'AmountAllowed', fnHRMCheckLeaveBaanceRate(SEmpID, lt.LeaveType_BaseBalance, COALESCE(lt.LeaveType_AmountAllowed, 0)) - SUM(COALESCE(ld.Leave_Amount, 0)) AS 'Balance', fnHRMCheckLeaveBaanceRate(SEmpID, lt.LeaveType_BaseBalance, COALESCE(lt.LeaveType_AmountAllowed, 0)) - SUM(COALESCE(IF(l.Leave_ID <> ID, ld.Leave_Amount, 0), 0)) AS 'OldBalance',
			SUM(IF(LOWER(l.Leave_Status) = 'requested' AND l.Leave_ID <> ID, COALESCE(ld.Leave_Amount, 0), 0)) 'Pending', SUM(IF(LOWER(l.Leave_Status) = 'approved' AND l.Leave_ID <> ID, COALESCE(ld.Leave_Amount, 0), 0)) 'Taken', SUM(IF(l.Leave_ID = ID, COALESCE(ld.Leave_Amount, 0), 0)) 'ThisApp'
			FROM hrm_timesheet_leave_type lt
			INNER JOIN hrm_timesheet_leave_type_employee lte ON(lte.Leave_TypeID = lt.LeaveType_ID AND lte.Leave_EmpID = SEmpID)
			LEFT JOIN (hrm_timesheet_leave_detail ld LEFT JOIN hrm_timesheet_leave l ON(l.Leave_ID = ld.LeaveD_ID AND LOWER(l.Leave_Status) <> 'rejected')) ON(ld.LeaveD_TypeID = lt.LeaveType_ID AND l.Leave_EmpID = SEmpID)
			WHERE LOWER(lt.LeaveType_PayStatus) = 'paid' AND lt.LeaveType_Year = YEAR(SNow) AND l.Leave_EmpID = SEmpID AND lt.LeaveType_ID IN(SELECT DISTINCT LeaveD_TypeID FROM hrm_timesheet_leave_detail WHERE LeaveD_ID = ID)
			GROUP BY lt.LeaveType_ID
			ORDER BY lt.LeaveType_ID;
		ELSE
			SELECT Deduct_Leave_Balance_Hourly, lt.LeaveType_ID, lt.LeaveType_Name, fnHRMCheckLeaveBaanceRate(SEmpID, lt.LeaveType_BaseBalance, COALESCE(lt.LeaveType_AmountAllowed, 0)) AS 'AmountAllowed', fnHRMCheckLeaveBaanceRate(SEmpID, lt.LeaveType_BaseBalance, COALESCE(lt.LeaveType_AmountAllowed, 0)) - COALESCE(SUM(IF(LOWER(ld.LeaveD_Duration) = 'full day', COALESCE(ld.Leave_Total, 0), 0)) + FLOOR(SUM(IF(LOWER(ld.LeaveD_Duration) = 'hourly', COALESCE(ld.Leave_Total, 0), 0))/WorkHour) + IF(MOD(SUM(IF(LOWER(ld.LeaveD_Duration) = 'hourly', COALESCE(ld.Leave_Total, 0), 0)), WorkHour) > 0, 1, 0), 0) AS 'Balance',
			IF(MOD(SUM(IF(LOWER(ld.LeaveD_Duration) = 'hourly', COALESCE(ld.Leave_Total, 0), 0)), WorkHour) > 0, WorkHour - MOD(SUM(IF(LOWER(ld.LeaveD_Duration) = 'hourly', COALESCE(ld.Leave_Total, 0), 0)), WorkHour), 0) AS 'Balance_H',
			fnHRMCheckLeaveBaanceRate(SEmpID, lt.LeaveType_BaseBalance, COALESCE(lt.LeaveType_AmountAllowed, 0)) - COALESCE(SUM(IF(LOWER(ld.LeaveD_Duration) = 'full day' AND l.Leave_ID <> ID, COALESCE(ld.Leave_Total, 0), 0)) + FLOOR(SUM(IF(LOWER(ld.LeaveD_Duration) = 'hourly' AND l.Leave_ID <> ID, COALESCE(ld.Leave_Total, 0), 0))/WorkHour) + IF(MOD(SUM(IF(LOWER(ld.LeaveD_Duration) = 'hourly' AND l.Leave_ID <> ID, COALESCE(ld.Leave_Total, 0), 0)), WorkHour) > 0, 1, 0), 0) AS 'OldBalance',
			IF(MOD(SUM(IF(LOWER(ld.LeaveD_Duration) = 'hourly' AND l.Leave_ID <> ID, COALESCE(ld.Leave_Total, 0), 0)), WorkHour) > 0, WorkHour - MOD(SUM(IF(LOWER(ld.LeaveD_Duration) = 'hourly' AND l.Leave_ID <> ID, COALESCE(ld.Leave_Total, 0), 0)), WorkHour), 0) AS 'OldBalance_H',
			SUM(IF(LOWER(l.Leave_Status) = 'requested' AND LOWER(ld.LeaveD_Duration) = 'full day' AND l.Leave_ID <> ID, COALESCE(ld.Leave_Total, 0), 0)) + FLOOR(SUM(IF(LOWER(l.Leave_Status) = 'requested' AND LOWER(ld.LeaveD_Duration) = 'hourly' AND l.Leave_ID <> ID, COALESCE(ld.Leave_Total, 0), 0))/WorkHour) 'Pending', 
			MOD(SUM(IF(LOWER(l.Leave_Status) = 'requested' AND LOWER(ld.LeaveD_Duration) = 'hourly' AND l.Leave_ID <> ID, COALESCE(ld.Leave_Total, 0), 0)), WorkHour) 'Pending_H', 
			SUM(IF(LOWER(l.Leave_Status) = 'approved' AND LOWER(ld.LeaveD_Duration) = 'full day' AND l.Leave_ID <> ID, COALESCE(ld.Leave_Total, 0), 0)) + FLOOR(SUM(IF(LOWER(l.Leave_Status) = 'approved' AND LOWER(ld.LeaveD_Duration) = 'hourly' AND l.Leave_ID <> ID, COALESCE(ld.Leave_Total, 0), 0))/WorkHour) 'Taken', 
			MOD(SUM(IF(LOWER(l.Leave_Status) = 'approved' AND LOWER(ld.LeaveD_Duration) = 'hourly' AND l.Leave_ID <> ID, COALESCE(ld.Leave_Total, 0), 0)), WorkHour) 'Taken_H',
			SUM(IF(LOWER(ld.LeaveD_Duration) = 'full day' AND l.Leave_ID = ID, COALESCE(ld.Leave_Total, 0), 0)) + FLOOR(SUM(IF(LOWER(ld.LeaveD_Duration) = 'hourly' AND l.Leave_ID = ID, COALESCE(ld.Leave_Total, 0), 0))/WorkHour) 'ThisApp', 
			MOD(SUM(IF(LOWER(ld.LeaveD_Duration) = 'hourly' AND l.Leave_ID = ID, COALESCE(ld.Leave_Total, 0), 0)), WorkHour) 'ThisApp_H'
			FROM hrm_timesheet_leave_type lt
			INNER JOIN hrm_timesheet_leave_type_employee lte ON(lte.Leave_TypeID = lt.LeaveType_ID AND lte.Leave_EmpID = SEmpID)
			LEFT JOIN (hrm_timesheet_leave_detail ld LEFT JOIN hrm_timesheet_leave l ON(l.Leave_ID = ld.LeaveD_ID AND LOWER(l.Leave_Status) <> 'rejected')) ON(ld.LeaveD_TypeID = lt.LeaveType_ID  AND l.Leave_EmpID = SEmpID)
			WHERE LOWER(lt.LeaveType_PayStatus) = 'paid' AND lt.LeaveType_Year = YEAR(SNow) AND l.Leave_EmpID = SEmpID AND lt.LeaveType_ID IN(SELECT DISTINCT LeaveD_TypeID FROM hrm_timesheet_leave_detail WHERE LeaveD_ID = ID)
			GROUP BY lt.LeaveType_ID
			ORDER BY lt.LeaveType_ID;
		END IF;		

	SELECT LeaveD_ID,LeaveD_Date,LeaveD_Duration,LeaveD_TypeID,LeaveD_TimeFrom,LeaveD_TimeTo 
	,lt.LeaveType_ID,lt.LeaveType_Name,lt.LeaveType_PayStatus,lt.LeaveType_Year,lt.LeaveType_AmountAllowed,lt.LeaveType_GenderRestriction,lt.LeaveType_PayType,lt.LeaveType_PayAmount
	FROM hrm_timesheet_leave_detail ld
	LEFT JOIN hrm_timesheet_leave_type lt ON(lt.LeaveType_ID = ld.LeaveD_TypeID)
	WHERE LeaveD_ID IN(SELECT DISTINCT Leave_ID FROM hrm_timesheet_leave WHERE Leave_EmpID = SEmpID AND LeaveD_ID <> ID) AND YEAR(LeaveD_Date) = YEAR(SNow);

	SELECT Leave_ID,Leave_EmpID,Leave_Tel,Leave_Email,Leave_Reason,Leave_From,Leave_To,Leave_Description,Leave_AttachmentName,Leave_AttachmentPath,Leave_Status,
	COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level',COALESCE(u.var_name, '') AS UName, COALESCE(e.var_hrm_department_id, '') AS Emp_DepartmentID, d.Department_Name, COALESCE(e.var_hrm_branch_id, '') AS Emp_BranchID, br.Branch_Name, COALESCE(e.var_hrm_grade, '') AS Emp_Grade, COALESCE(e.var_hrm_type, '') AS Emp_Type, COALESCE(e.var_hrm_category, '') AS Emp_Category, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, COALESCE(e.var_hrm_sex, '') AS EmpSex
	FROM hrm_timesheet_leave l
	LEFT JOIN ame_mt_emp e ON(l.Leave_EmpID = e.var_id)  
	LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
	LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
	LEFT JOIN hrm_emp_department d ON(d.Department_ID = e.var_hrm_department_id)
	LEFT JOIN hrm_emp_branch br ON(br.Branch_ID = e.var_hrm_branch_id)
	WHERE l.Leave_EmpID = SEmpID AND YEAR(l.Leave_From) = YEAR(SNow) AND l.Leave_ID <> ID;

	CALL spHRMGetLeaveSub(userid);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMAuthGetOvertimeID`;
DELIMITER |
CREATE PROCEDURE `spHRMAuthGetOvertimeID`(userid varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE CheckU VARCHAR(255) DEFAULT("");
	DECLARE SEmpID VARCHAR(255) DEFAULT("");
	DECLARE SAuthID VARCHAR(255) DEFAULT("");

	SELECT var_hrm_utype, var_empid INTO CheckU, SEmpID FROM ame_user u WHERE u.var_id = userid; 
	SELECT Overtime_AuthID INTO SAuthID FROM hrm_payroll_overtime WHERE Overtime_ID = ID;

	IF CheckU = "ESS" THEN

		SELECT b.Overtime_ID,b.Overtime_Reason,b.Overtime_Type,b.Overtime_Amount,b.Overtime_Multiplier,b.Overtime_DateFrom,b.Overtime_DateTo,b.Overtime_TimeIn,b.Overtime_TimeOut,b.Overtime_Description,b.Overtime_Status,b.Overtime_AuthID,b.Overtime_RequestBy,b.Overtime_CreateDate,
		COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level',COALESCE(u.var_name, '') AS UName, COALESCE(e.var_hrm_department_id, '') AS Emp_DepartmentID, d.Department_Name, COALESCE(e.var_hrm_branch_id, '') AS Emp_BranchID, br.Branch_Name, COALESCE(e.var_hrm_grade, '') AS Emp_Grade, COALESCE(e.var_hrm_type, '') AS Emp_Type, COALESCE(e.var_hrm_category, '') AS Emp_Category, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, COALESCE(e.var_hrm_sex, '') AS EmpSex
		FROM hrm_payroll_overtime b
		LEFT JOIN ame_mt_emp e ON(b.Overtime_RequestBy = e.var_id) 
		LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
		LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
		LEFT JOIN hrm_emp_department d ON(d.Department_ID = e.var_hrm_department_id)
		LEFT JOIN hrm_emp_branch br ON(br.Branch_ID = e.var_hrm_branch_id)
		WHERE Overtime_ID = ID AND (Overtime_ID IN(SELECT l.RecordID FROM hrm_log l WHERE l.RecordID = ID AND l.FrmSysName = "Overtime" AND l.ActionType = "insert" AND l.UID = userid) OR Overtime_ID IN(SELECT Auth_ProcessID FROM hrm_authorisation_approved WHERE Auth_ProcessName = 'Overtime' AND Auth_ProcessID = ID AND Auth_EmpID = SEmpID));

		SELECT od.od_id,od.od_date,od.od_timein,od.od_timeout,od.od_hours,od.od_multiplier 
		FROM hrm_payroll_overtime_detail od 
		WHERE od.od_id = ID AND (od_id IN(SELECT l.RecordID FROM hrm_log l WHERE l.RecordID = ID AND l.FrmSysName = "Overtime" AND l.ActionType = "insert" AND l.UID = userid) OR od_id IN(SELECT Auth_ProcessID FROM hrm_authorisation_approved WHERE Auth_ProcessName = 'Overtime' AND Auth_ProcessID = ID AND Auth_EmpID = SEmpID));

		SELECT ode.od_id,ode.od_empid,ode.od_status,
		COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level',COALESCE(u.var_name, '') AS UName, COALESCE(e.var_hrm_department_id, '') AS Emp_DepartmentID, d.Department_Name, COALESCE(e.var_hrm_branch_id, '') AS Emp_BranchID, br.Branch_Name, COALESCE(e.var_hrm_grade, '') AS Emp_Grade, COALESCE(e.var_hrm_type, '') AS Emp_Type, COALESCE(e.var_hrm_category, '') AS Emp_Category, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, COALESCE(e.var_hrm_sex, '') AS EmpSex
		FROM hrm_payroll_overtime_detail_employee ode 
		LEFT JOIN ame_mt_emp e ON(ode.od_empid = e.var_id) 
		LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
		LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
		LEFT JOIN hrm_emp_department d ON(d.Department_ID = e.var_hrm_department_id)
		LEFT JOIN hrm_emp_branch br ON(br.Branch_ID = e.var_hrm_branch_id)
		WHERE ode.od_id = ID AND od_id IN(SELECT l.RecordID FROM hrm_log l WHERE l.RecordID = ID AND l.FrmSysName = "Overtime" AND l.ActionType = "insert" AND l.UID = userid);

		SELECT a.Auth_ID,a.Auth_Name,a.Auth_Type,a.Auth_AndOr,a.Auth_Amount, fnHRMCheckAuthorisationApproved(ID, 'Overtime', SAuthID) AS 'Auth_Approved' FROM hrm_authorisation_temp a WHERE a.Auth_ID = SAuthID AND a.Auth_TranID = ID;

		SELECT a.Auth_ID,a.Auth_EmpID,a.Auth_GroupID,a.Auth_GroupAndOr,a.Auth_GroupAmount,
		COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level',COALESCE(u.var_name, '') AS UName,app.Auth_Status 
		FROM hrm_authorisation_detail_temp a
		LEFT JOIN hrm_authorisation_approved app ON(app.Auth_ID = SAuthID AND app.Auth_ProcessID = ID AND app.Auth_ProcessName = "Overtime" AND a.Auth_EmpID = app.Auth_EmpID AND a.Auth_GroupID = app.Auth_GroupID AND a.Auth_TranID = app.Auth_ProcessID)
		LEFT JOIN ame_mt_emp e ON(a.Auth_EmpID = e.var_id) 
		LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
		LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
		WHERE a.Auth_TranID = ID AND a.Auth_ID = SAuthID;

		SELECT a.AuthGroup_ID,a.AuthGroup_Name,a.AuthGroup_Description,d.Auth_GroupID,COALESCE(d.Auth_GroupAndOr,"") as "Auth_GroupAndOr",COALESCE(d.Auth_GroupAmount,"") as "AuthGroup_Amount",(SELECT COUNT(ds.AuthGroup_ID) FROM hrm_authorisation_group_detail_temp ds WHERE ds.AuthGroup_ID = a.AuthGroup_ID AND ds.Auth_TranID = ID) as 'Count'
		,(SELECT COUNT(ds.Auth_GroupID) FROM hrm_authorisation_approved ds WHERE ds.Auth_ProcessID = ID AND ds.Auth_GroupID = a.AuthGroup_ID AND ds.Auth_ID = SAuthID AND ds.Auth_Status = "approved") AS 'AuthGroup_Approved'
		FROM hrm_authorisation_group_temp a
		INNER JOIN hrm_authorisation_detail_temp d ON(d.Auth_GroupID = a.AuthGroup_ID AND d.Auth_ID = SAuthID AND a.Auth_TranID = ID)
		WHERE a.Auth_TranID = ID
		ORDER BY a.AuthGroup_ID DESC;

		SELECT a.AuthGroup_ID,a.AuthGroup_EmpID,
		COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level',COALESCE(u.var_name, '') AS UName,app.Auth_Status 
		FROM hrm_authorisation_group_detail_temp a
		INNER JOIN hrm_authorisation_detail_temp d ON(a.AuthGroup_ID = d.Auth_GroupID AND d.Auth_ID = SAuthID AND a.Auth_TranID = d.Auth_TranID)
		LEFT JOIN hrm_authorisation_approved app ON(app.Auth_ID = SAuthID AND app.Auth_GroupID = a.AuthGroup_ID AND app.Auth_ProcessID = ID AND app.Auth_ProcessName = "Overtime" AND app.Auth_EmpID = a.AuthGroup_EmpID)
		LEFT JOIN ame_mt_emp e ON(a.AuthGroup_EmpID = e.var_id)  
		LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
		LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
		WHERE a.Auth_TranID = ID AND d.Auth_ID = SAuthID
		ORDER BY a.AuthGroup_EmpID, a.AuthGroup_ID;
		
		DELETE FROM hrm_temp_supervisor WHERE UID = userid AND Type = 'Overtime';
		IF SEmpID != "" THEN
			INSERT INTO hrm_temp_supervisor(UID,EmpID,Type) VALUES (userid, SEmpID, 'Overtime');
			CALL spHRMGetEmpInSuper(SEmpID,userid, 'Overtime');
		END IF;

		SELECT COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level',COALESCE(u.var_name, '') AS UName, COALESCE(e.var_hrm_department_id, '') AS Emp_DepartmentID, d.Department_Name, COALESCE(e.var_hrm_branch_id, '') AS Emp_BranchID, br.Branch_Name, COALESCE(e.var_hrm_grade, '') AS Emp_Grade, COALESCE(e.var_hrm_type, '') AS Emp_Type, COALESCE(e.var_hrm_category, '') AS Emp_Category, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, COALESCE(e.var_hrm_sex, '') AS EmpSex
		FROM ame_mt_emp e  
		LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
		LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
		LEFT JOIN hrm_emp_department d ON(d.Department_ID = e.var_hrm_department_id)
		LEFT JOIN hrm_emp_branch br ON(br.Branch_ID = e.var_hrm_branch_id)
		WHERE e.var_id IN (SELECT ts.EmpID FROM hrm_temp_supervisor ts WHERE ts.UID = userid AND ts.Type = 'Overtime')
		ORDER BY e.var_id;

	ELSEIF CheckU = "Normal" OR CheckU = "Administrator" THEN

		SELECT b.Overtime_ID,b.Overtime_Reason,b.Overtime_Type,b.Overtime_Amount,b.Overtime_Multiplier,b.Overtime_DateFrom,b.Overtime_DateTo,b.Overtime_TimeIn,b.Overtime_TimeOut,b.Overtime_Description,b.Overtime_Status,b.Overtime_AuthID,b.Overtime_RequestBy,b.Overtime_CreateDate,
		COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level',COALESCE(u.var_name, '') AS UName, COALESCE(e.var_hrm_department_id, '') AS Emp_DepartmentID, d.Department_Name, COALESCE(e.var_hrm_branch_id, '') AS Emp_BranchID, br.Branch_Name, COALESCE(e.var_hrm_grade, '') AS Emp_Grade, COALESCE(e.var_hrm_type, '') AS Emp_Type, COALESCE(e.var_hrm_category, '') AS Emp_Category, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, COALESCE(e.var_hrm_sex, '') AS EmpSex
		FROM hrm_payroll_overtime b
		LEFT JOIN ame_mt_emp e ON(b.Overtime_RequestBy = e.var_id) 
		LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
		LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
		LEFT JOIN hrm_emp_department d ON(d.Department_ID = e.var_hrm_department_id)
		LEFT JOIN hrm_emp_branch br ON(br.Branch_ID = e.var_hrm_branch_id)
		WHERE Overtime_ID = ID;

		SELECT od.od_id,od.od_date,od.od_timein,od.od_timeout,od.od_hours,od.od_multiplier 
		FROM hrm_payroll_overtime_detail od 
		WHERE od.od_id = ID;

		SELECT ode.od_id,ode.od_empid,ode.od_status,
		COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level',COALESCE(u.var_name, '') AS UName, COALESCE(e.var_hrm_department_id, '') AS Emp_DepartmentID, d.Department_Name, COALESCE(e.var_hrm_branch_id, '') AS Emp_BranchID, br.Branch_Name, COALESCE(e.var_hrm_grade, '') AS Emp_Grade, COALESCE(e.var_hrm_type, '') AS Emp_Type, COALESCE(e.var_hrm_category, '') AS Emp_Category, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, COALESCE(e.var_hrm_sex, '') AS EmpSex
		FROM hrm_payroll_overtime_detail_employee ode 
		LEFT JOIN ame_mt_emp e ON(ode.od_empid = e.var_id) 
		LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
		LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
		LEFT JOIN hrm_emp_department d ON(d.Department_ID = e.var_hrm_department_id)
		LEFT JOIN hrm_emp_branch br ON(br.Branch_ID = e.var_hrm_branch_id)
		WHERE ode.od_id = ID;
		
		SELECT a.Auth_ID,a.Auth_Name,a.Auth_Type,a.Auth_AndOr,a.Auth_Amount, fnHRMCheckAuthorisationApproved(ID, 'Overtime', SAuthID) AS 'Auth_Approved' FROM hrm_authorisation_temp a WHERE a.Auth_ID = SAuthID AND a.Auth_TranID = ID;

		SELECT a.Auth_ID,a.Auth_EmpID,a.Auth_GroupID,a.Auth_GroupAndOr,a.Auth_GroupAmount,
		COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level',COALESCE(u.var_name, '') AS UName,app.Auth_Status 
		FROM hrm_authorisation_detail_temp a
		LEFT JOIN hrm_authorisation_approved app ON(app.Auth_ID = SAuthID AND app.Auth_ProcessID = ID AND app.Auth_ProcessName = "Overtime" AND a.Auth_EmpID = app.Auth_EmpID AND a.Auth_GroupID = app.Auth_GroupID AND a.Auth_TranID = app.Auth_ProcessID)
		LEFT JOIN ame_mt_emp e ON(a.Auth_EmpID = e.var_id) 
		LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
		LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
		WHERE a.Auth_TranID = ID AND a.Auth_ID = SAuthID;

		SELECT a.AuthGroup_ID,a.AuthGroup_Name,a.AuthGroup_Description,d.Auth_GroupID,COALESCE(d.Auth_GroupAndOr,"") as "Auth_GroupAndOr",COALESCE(d.Auth_GroupAmount,"") as "AuthGroup_Amount",(SELECT COUNT(ds.AuthGroup_ID) FROM hrm_authorisation_group_detail_temp ds WHERE ds.AuthGroup_ID = a.AuthGroup_ID AND ds.Auth_TranID = ID) as 'Count'
		,(SELECT COUNT(ds.Auth_GroupID) FROM hrm_authorisation_approved ds WHERE ds.Auth_ProcessID = ID AND ds.Auth_GroupID = a.AuthGroup_ID AND ds.Auth_ID = SAuthID AND ds.Auth_Status = "approved") AS 'AuthGroup_Approved'
		FROM hrm_authorisation_group_temp a
		INNER JOIN hrm_authorisation_detail_temp d ON(d.Auth_GroupID = a.AuthGroup_ID AND d.Auth_ID = SAuthID AND a.Auth_TranID = ID)
		WHERE a.Auth_TranID = ID
		ORDER BY a.AuthGroup_ID DESC;

		SELECT a.AuthGroup_ID,a.AuthGroup_EmpID,
		COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level',COALESCE(u.var_name, '') AS UName,app.Auth_Status 
		FROM hrm_authorisation_group_detail_temp a
		INNER JOIN hrm_authorisation_detail_temp d ON(a.AuthGroup_ID = d.Auth_GroupID AND d.Auth_ID = SAuthID AND a.Auth_TranID = d.Auth_TranID)
		LEFT JOIN hrm_authorisation_approved app ON(app.Auth_ID = SAuthID AND app.Auth_GroupID = a.AuthGroup_ID AND app.Auth_ProcessID = ID AND app.Auth_ProcessName = "Overtime" AND app.Auth_EmpID = a.AuthGroup_EmpID)
		LEFT JOIN ame_mt_emp e ON(a.AuthGroup_EmpID = e.var_id)  
		LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
		LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
		WHERE a.Auth_TranID = ID AND d.Auth_ID = SAuthID
		ORDER BY a.AuthGroup_EmpID, a.AuthGroup_ID;

		SELECT COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_email, '') AS EmpEmail, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(pos.var_name, '') AS 'Position', COALESCE(pos.var_addr, '') AS 'PositionKhmer', COALESCE(pos.int_level, 0) AS 'Position_Level',COALESCE(u.var_name, '') AS UName, COALESCE(e.var_hrm_department_id, '') AS Emp_DepartmentID, d.Department_Name, COALESCE(e.var_hrm_branch_id, '') AS Emp_BranchID, br.Branch_Name, COALESCE(e.var_hrm_grade, '') AS Emp_Grade, COALESCE(e.var_hrm_type, '') AS Emp_Type, COALESCE(e.var_hrm_category, '') AS Emp_Category, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, COALESCE(e.var_hrm_sex, '') AS EmpSex
		FROM ame_mt_emp e  
		LEFT JOIN ame_user u ON(u.var_empid = e.var_id) 
		LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
		LEFT JOIN hrm_emp_department d ON(d.Department_ID = e.var_hrm_department_id)
		LEFT JOIN hrm_emp_branch br ON(br.Branch_ID = e.var_hrm_branch_id)
		WHERE e.var_id NOT IN(SELECT od_empid FROM hrm_payroll_overtime_detail_employee WHERE od_id = ID)
		ORDER BY e.var_id;

	END IF;

	-- --------------------------------------------------------------------

	SELECT b.Branch_ID,b.Branch_Name,b.Branch_Tel,b.Branch_Description,b.Branch_Address,b.Branch_HomeNo,b.Branch_Street,b.Branch_Village,b.Branch_District,b.Branch_Commune,b.Branch_City,b.Branch_State,b.Branch_Country FROM hrm_emp_branch b ORDER BY b.Branch_ID;

	SELECT b.Department_ID,b.Department_Name,b.Department_Description,b.Department_Parent FROM hrm_emp_department b ORDER BY b.Department_ID;
	
	SELECT b.Type_Name FROM hrm_emp_type b ORDER BY b.Type_Name;

	SELECT b.Category_Name FROM hrm_emp_category b ORDER BY b.Category_Name;

	SELECT b.Grade_Name FROM hrm_emp_grade b ORDER BY b.Grade_Name;

	SELECT COALESCE(pos.var_name, '') AS Position, COALESCE(pos.var_addr, '') AS PositionKhmer, COALESCE(pos.int_level, 0) AS 'Position_Level', COALESCE(var_description, '') AS Position_Description FROM ame_mt_pos pos ORDER BY pos.var_id;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMChangePasswordUser`;
DELIMITER |
CREATE PROCEDURE `spHRMChangePasswordUser`(UserID varchar(255), OldPass varchar(255), NewPass varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);
	
	UPDATE ame_user SET var_pwd = NewPass WHERE var_id = UserID;
	
	SET Message = "success";
	SELECT Message;
	CALL hrm_message('1104406', 'User', 'change', UserID);
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckAddAttendanceLeave`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckAddAttendanceLeave`(SID varchar(255), SEmpID varchar(255))
    DETERMINISTIC
BEGIN
		DECLARE v_finished INTEGER DEFAULT 0;
		DECLARE SDuration varchar(255) DEFAULT("");
		DECLARE SDate DATE;
		DECLARE SFrom TIME;
		DECLARE STo TIME;
		DECLARE TempA VARCHAR(255);
		DECLARE TempB VARCHAR(255);

		DEClARE CustID_Cursor CURSOR FOR SELECT LeaveD_Duration,LeaveD_Date,LeaveD_TimeFrom,LeaveD_TimeTo FROM hrm_timesheet_leave_detail WHERE LeaveD_ID  = SID;
		DECLARE CONTINUE HANDLER
		FOR NOT FOUND SET v_finished = 1;
		OPEN CustID_Cursor;
			GetCustID: LOOP
				FETCH CustID_Cursor INTO SDuration,SDate,SFrom,STo;
				IF v_finished = 1 THEN
					LEAVE GetCustID;
				END IF;

				IF LOWER(SDuration) = 'full day' THEN
					Set TempA = CONCAT(SDate, ' 00:00:00');
					Set TempB = CONCAT(SDate, ' 00:00:00');
					CALL spHRMAttendanceLeaveFullDay(SEmpID, TempA, TempB);
				ELSE
					Set TempA = CONCAT(SDate, ' ', SFrom);
					Set TempB = CONCAT(SDate, ' ', STo);
					CALL spHRMAttendanceLeaveHourly(SEmpID, TempA, TempB);
				END IF;

			END LOOP GetCustID;
		CLOSE CustID_Cursor;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckAttendanceNormal`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckAttendanceNormal`(SEmpID varchar(255),ShiftID varchar(255), FP_ID varchar(255), FP_Date Date)
    DETERMINISTIC
BEGIN
		DECLARE Shift_ID VARCHAR(255);
		DECLARE Shift_Day VARCHAR(255);
		DECLARE Shift_TotalWorkHour FLOAT DEFAULT(0);
		DECLARE Shift_TimeIn1 TIME;
		DECLARE Shift_TimeInPeriod1 TIME;
		DECLARE Shift_TimeOut1 TIME;
		DECLARE Shift_TimeOutPeriod1 TIME;
		DECLARE Shift_TimeIn2 TIME;
		DECLARE Shift_TimeInPeriod2 TIME;
		DECLARE Shift_TimeOut2 TIME;
		DECLARE Shift_TimeOutPeriod2 TIME;
		DECLARE Shift_TimeIn3 TIME;
		DECLARE Shift_TimeInPeriod3 TIME;
		DECLARE Shift_TimeOut3 TIME;
		DECLARE Shift_TimeOutPeriod3 TIME;
		DECLARE Shift_TimeIn4 TIME;
		DECLARE Shift_TimeInPeriod4 TIME;
		DECLARE Shift_TimeOut4 TIME;
		DECLARE Shift_TimeOutPeriod4 TIME;
		DECLARE Shift_TimeIn5 TIME;
		DECLARE Shift_TimeInPeriod5 TIME;
		DECLARE Shift_TimeOut5 TIME;
		DECLARE Shift_TimeOutPeriod5 TIME;
		DECLARE Shift_TimeInOvertime TIME;
		DECLARE Shift_TimeOutOvertime TIME;

		DECLARE Shift_TimeIn1LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut1LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeIn2LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut2LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeIn3LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut3LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeIn4LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut4LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeIn5LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut5LateAmt INT DEFAULT(0);

		DECLARE CheckExist TINYINT DEFAULT(0);

		DECLARE TotalCheckLate TINYINT DEFAULT(0);
		DECLARE TotalCheckLateDuration TIME DEFAULT('00:00:00');
		DECLARE TotalcheckLateDurationDeduct TIME DEFAULT('00:00:00');

		DECLARE CheckLateIn1 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn1 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn1 TIME DEFAULT('00:00:00');
		DECLARE CheckLateIn2 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn2 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn2 TIME DEFAULT('00:00:00');
		DECLARE CheckLateIn3 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn3 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn3 TIME DEFAULT('00:00:00');
		DECLARE CheckLateIn4 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn4 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn4 TIME DEFAULT('00:00:00');
		DECLARE CheckLateIn5 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn5 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn5 TIME DEFAULT('00:00:00');

		DECLARE CheckLateOut1 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut1 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut1 TIME DEFAULT('00:00:00');
		DECLARE CheckLateOut2 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut2 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut2 TIME DEFAULT('00:00:00');
		DECLARE CheckLateOut3 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut3 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut3 TIME DEFAULT('00:00:00');
		DECLARE CheckLateOut4 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut4 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut4 TIME DEFAULT('00:00:00');
		DECLARE CheckLateOut5 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut5 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut5 TIME DEFAULT('00:00:00');

		DECLARE LeaveDurationStatus VARCHAR(255) DEFAULT('');
		DECLARE LeaveDurationInOut1 TIME DEFAULT('00:00:00');
		DECLARE LeaveDurationInOut2 TIME DEFAULT('00:00:00');
		DECLARE LeaveDurationInOut3 TIME DEFAULT('00:00:00');
		DECLARE LeaveDurationInOut4 TIME DEFAULT('00:00:00');
		DECLARE LeaveDurationInOut5 TIME DEFAULT('00:00:00');

		DECLARE CheckOutLeave VARCHAR(255) DEFAULT('');

		DECLARE CheckAb TINYINT DEFAULT(0);
		DECLARE checkAbDurationDeduct TIME DEFAULT('00:00:00');
		DECLARE CheckL TINYINT DEFAULT(0);
		DECLARE S VARCHAR(255) DEFAULT('');

		DECLARE In1 TIME DEFAULT('00:00:00');
		DECLARE In2 TIME DEFAULT('00:00:00');
		DECLARE In3 TIME DEFAULT('00:00:00');
		DECLARE In4 TIME DEFAULT('00:00:00');
		DECLARE In5 TIME DEFAULT('00:00:00');
		DECLARE Out1 TIME DEFAULT('00:00:00');
		DECLARE Out2 TIME DEFAULT('00:00:00');
		DECLARE Out3 TIME DEFAULT('00:00:00');
		DECLARE Out4 TIME DEFAULT('00:00:00');
		DECLARE Out5 TIME DEFAULT('00:00:00');
		DECLARE OverIn TIME DEFAULT('00:00:00');
		DECLARE OverOut TIME DEFAULT('00:00:00');
		DECLARE O1 TIME DEFAULT('00:00:00');
		DECLARE O2 TIME DEFAULT('00:00:00');
		DECLARE WorkHour INT DEFAULT(0);

		DECLARE TimeBreak1 VARCHAR(255) DEFAULT('');
		DECLARE TimeBreak2 VARCHAR(255) DEFAULT('');
		DECLARE TimeBreak3 VARCHAR(255) DEFAULT('');
		DECLARE TimeBreak4 VARCHAR(255) DEFAULT('');
		DECLARE TimeBreak5 VARCHAR(255) DEFAULT('');
	
		SELECT wd.Shift_ID,wd.Shift_Day,wd.Shift_TotalWorkHour,wd.Shift_TimeIn1,wd.Shift_TimeInPeriod1,wd.Shift_TimeOut1,wd.Shift_TimeOutPeriod1,wd.Shift_TimeIn2,wd.Shift_TimeInPeriod2,wd.Shift_TimeOut2,wd.Shift_TimeOutPeriod2,wd.Shift_TimeIn3,wd.Shift_TimeInPeriod3,wd.Shift_TimeOut3,wd.Shift_TimeOutPeriod3,wd.Shift_TimeIn4,wd.Shift_TimeInPeriod4,wd.Shift_TimeOut4,wd.Shift_TimeOutPeriod4,wd.Shift_TimeIn5,wd.Shift_TimeInPeriod5,wd.Shift_TimeOut5,wd.Shift_TimeOutPeriod5,wd.Shift_TimeInOvertime,wd.Shift_TimeOutOvertime,wd.Shift_TimeIn1LateDuration,wd.Shift_TimeOut1LateDuration,wd.Shift_TimeIn2LateDuration,wd.Shift_TimeOut2LateDuration,wd.Shift_TimeIn3LateDuration,wd.Shift_TimeOut3LateDuration,wd.Shift_TimeIn4LateDuration,wd.Shift_TimeOut4LateDuration,wd.Shift_TimeIn5LateDuration,wd.Shift_TimeOut5LateDuration,Shift_TimeBreak1,Shift_TimeBreak2,Shift_TimeBreak3,Shift_TimeBreak4,Shift_TimeBreak5 INTO Shift_ID, Shift_Day, Shift_TotalWorkHour, Shift_TimeIn1, Shift_TimeInPeriod1, Shift_TimeOut1, Shift_TimeOutPeriod1, Shift_TimeIn2, Shift_TimeInPeriod2, Shift_TimeOut2, Shift_TimeOutPeriod2, Shift_TimeIn3, Shift_TimeInPeriod3, Shift_TimeOut3, Shift_TimeOutPeriod3, Shift_TimeIn4, Shift_TimeInPeriod4, Shift_TimeOut4, Shift_TimeOutPeriod4, Shift_TimeIn5, Shift_TimeInPeriod5, Shift_TimeOut5, Shift_TimeOutPeriod5, Shift_TimeInOvertime, Shift_TimeOutOvertime, Shift_TimeIn1LateAmt, Shift_TimeOut1LateAmt, Shift_TimeIn2LateAmt, Shift_TimeOut2LateAmt, Shift_TimeIn3LateAmt, Shift_TimeOut3LateAmt, Shift_TimeIn4LateAmt, Shift_TimeOut4LateAmt, Shift_TimeIn5LateAmt, Shift_TimeOut5LateAmt, TimeBreak1, TimeBreak2, TimeBreak3, TimeBreak4, TimeBreak5 FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID = ShiftID AND LOWER(wd.Shift_Day) = LOWER(DAYNAME(FP_DATE)); 

		SELECT COUNT(*) INTO CheckExist FROM  hrm_timesheet_attendance att WHERE att.Att_FPID = FP_ID AND att.Att_Date = FP_Date;
		IF CheckExist > 0 THEN
			SELECT Att_FPID,Att_Date,Att_In1,Att_Out1,Att_In2,Att_Out2,Att_In3,Att_Out3,Att_In4,Att_Out4,Att_In5,Att_Out5,Att_OvertimeIn,Att_OvertimeOut,Att_Other1,Att_Other2,Att_Status,Att_LeaveDurationInOut1,Att_LeaveDurationInOut2,Att_LeaveDurationInOut3,Att_LeaveDurationInOut4,Att_LeaveDurationInOut5,Att_LeaveDurationStatus,Att_OutLeave INTO FP_ID,FP_Date,In1,Out1,In2,Out2,In3,Out3,In4,Out4,In5,Out5,OverIn,OverOut,O1,O2,S,LeaveDurationInOut1,LeaveDurationInOut2,LeaveDurationInOut3,LeaveDurationInOut4,LeaveDurationInOut5,LeaveDurationStatus,CheckOutLeave FROM hrm_timesheet_attendance att WHERE att.Att_FPID = FP_ID AND att.Att_Date = FP_Date;
		END IF;

			-- Check Late
			IF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 < In1 AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= In1 AND In1 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In1%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In1,Shift_TimeInPeriod1), In1, TimeBreak1, 'TimeIn') > LeaveDurationInOut1 THEN
						SET CheckLateIn1 = 1;
						SET CheckLateDurationIn1 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In1,Shift_TimeInPeriod1),LeaveDurationInOut1), In1, TimeBreak1, 'TimeIn');
						SET checkLateDurationDeductIn1 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn1);
					END IF;
				ELSE
					SET CheckLateIn1 = 1;
					SET CheckLateDurationIn1 = fnHRMCheckBreakTime(TIMEDIFF(In1,Shift_TimeInPeriod1), In1, TimeBreak1, 'TimeIn');
					SET checkLateDurationDeductIn1 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn1);
				END IF;
			END IF;

			IF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 > Out1 AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= Out1 AND In1 <> '00:00:00' AND Out1 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out1%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod1, Out1), Out1, TimeBreak1, 'TimeOut') > LeaveDurationInOut1 THEN
						SET CheckLateOut1 = 1;
						SET CheckLateDurationOut1 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod1, Out1),LeaveDurationInOut1), Out1, TimeBreak1, 'TimeOut');
						SET checkLateDurationDeductOut1 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut1);
					END IF;
				ELSE
					SET CheckLateOut1 = 1;
					SET CheckLateDurationOut1 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod1, Out1), Out1, TimeBreak1, 'TimeOut');
					SET checkLateDurationDeductOut1 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut1);
				END IF;
			END IF;
		
			IF Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 < In2 AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= In2 AND In2 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In2%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In2,Shift_TimeInPeriod2), In2, TimeBreak2, 'TimeIn') > LeaveDurationInOut2 THEN
						SET CheckLateIn2 = 1;
						SET CheckLateDurationIn2 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In2,Shift_TimeInPeriod2),LeaveDurationInOut2), In2, TimeBreak2, 'TimeIn');
						SET checkLateDurationDeductIn2 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn2);
					END IF;
				ELSE
					SET CheckLateIn2 = 1;
					SET CheckLateDurationIn2 = fnHRMCheckBreakTime(TIMEDIFF(In2,Shift_TimeInPeriod2), In2, TimeBreak2, 'TimeIn');
					SET checkLateDurationDeductIn2 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn2);
				END IF;
			END IF;

			IF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 > Out2 AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= Out2 AND In2 <> '00:00:00' AND Out2 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out2%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod2, Out2), Out2, TimeBreak2, 'TimeOut') > LeaveDurationInOut2 THEN
						SET CheckLateOut2 = 1;
						SET CheckLateDurationOut2 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod2, Out2),LeaveDurationInOut2), Out2, TimeBreak2, 'TimeOut');
						SET checkLateDurationDeductOut2 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut2);
					END IF;
				ELSE
					SET CheckLateOut2 = 1;
					SET CheckLateDurationOut2 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod2, Out2), Out2, TimeBreak2, 'TimeOut');
					SET checkLateDurationDeductOut2 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut2);
				END IF;
			END IF;
			
			IF Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 < In3 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= In3 AND In3 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In3%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In3,Shift_TimeInPeriod3), In3, TimeBreak3, 'TimeIn') > LeaveDurationInOut3 THEN
						SET CheckLateIn3 = 1;
						SET CheckLateDurationIn3 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In3,Shift_TimeInPeriod3),LeaveDurationInOut3), In3, TimeBreak3, 'TimeIn');
						SET checkLateDurationDeductIn3 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn3);
					END IF;
				ELSE
					SET CheckLateIn3 = 1;
					SET CheckLateDurationIn3 = fnHRMCheckBreakTime(TIMEDIFF(In3,Shift_TimeInPeriod3), In3, TimeBreak3, 'TimeIn');
					SET checkLateDurationDeductIn3 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn3);
				END IF;
			END IF;
			
			IF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 > Out3 AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= Out3 AND In3 <> '00:00:00' AND Out3 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out3%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod3, Out3), Out3, TimeBreak3, 'TimeOut') > LeaveDurationInOut3 THEN
						SET CheckLateOut3 = 1;
						SET CheckLateDurationOut3 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod3, Out3),LeaveDurationInOut3), Out3, TimeBreak3, 'TimeOut');
						SET checkLateDurationDeductOut3 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut3);
					END IF;
				ELSE
					SET CheckLateOut3 = 1;
					SET CheckLateDurationOut3 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod3, Out3), Out3, TimeBreak3, 'TimeOut');
					SET checkLateDurationDeductOut3 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut3);
				END IF;
			END IF;
			
			IF Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 < In4 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= In4 AND In4 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In4%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In4,Shift_TimeInPeriod4), In4, TimeBreak4, 'TimeIn') > LeaveDurationInOut4 THEN
						SET CheckLateIn4 = 1;
						SET CheckLateDurationIn4 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In4,Shift_TimeInPeriod4),LeaveDurationInOut4), In4, TimeBreak4, 'TimeIn');
						SET checkLateDurationDeductIn4 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn4);
					END IF;
				ELSE
					SET CheckLateIn4 = 1;
					SET CheckLateDurationIn4 = fnHRMCheckBreakTime(TIMEDIFF(In4,Shift_TimeInPeriod4), In4, TimeBreak4, 'TimeIn');
					SET checkLateDurationDeductIn4 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn4);
				END IF;
			END IF;
			
			IF Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 > Out4 AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= Out4 AND In4 <> '00:00:00' AND Out4 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out4%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod4, Out4), Out4, TimeBreak4, 'TimeOut') > LeaveDurationInOut4 THEN
						SET CheckLateOut4 = 1;
						SET CheckLateDurationOut4 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod4, Out4),LeaveDurationInOut4), Out4, TimeBreak4, 'TimeOut');
						SET checkLateDurationDeductOut4 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut4);
					END IF;
				ELSE
					SET CheckLateOut4 = 1;
					SET CheckLateDurationOut4 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod4, Out4), Out4, TimeBreak4, 'TimeOut');
					SET checkLateDurationDeductOut4 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut4);
				END IF;
			END IF;
			
			IF Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 < In5 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= In5 AND In5 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In5%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In5,Shift_TimeInPeriod5), In5, TimeBreak5, 'TimeIn') > LeaveDurationInOut5 THEN
						SET CheckLateIn5 = 1;
						SET CheckLateDurationIn5 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In5,Shift_TimeInPeriod5),LeaveDurationInOut5), In5, TimeBreak5, 'TimeIn');
						SET checkLateDurationDeductIn5 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn5);
					END IF;
				ELSE
					SET CheckLateIn5 = 1;
					SET CheckLateDurationIn5 = fnHRMCheckBreakTime(TIMEDIFF(In5,Shift_TimeInPeriod5), In5, TimeBreak5, 'TimeIn');
					SET checkLateDurationDeductIn5 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn5);
				END IF;
			END IF;
			
			IF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 > Out5 AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= Out5 AND In5 <> '00:00:00' AND Out5 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out5%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod5, Out5), Out5, TimeBreak5, 'TimeOut') > LeaveDurationInOut5 THEN
						SET CheckLateOut5 = 1;
						SET CheckLateDurationOut5 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod5, Out5),LeaveDurationInOut5), Out5, TimeBreak5, 'TimeOut');
						SET checkLateDurationDeductOut5 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut5);
					END IF;
				ELSE
					SET CheckLateOut5 = 1;
					SET CheckLateDurationOut5 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod5, Out5), Out5, TimeBreak5, 'TimeOut');
					SET checkLateDurationDeductOut5 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut5);	
				END IF;		
			END IF;

			IF S IS NULL THEN
				SET S = '';
			END IF;
			
			IF S <> 'HO' AND S <> 'B' THEN
				
				-- Check AB
				IF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND (In1 = '00:00:00' OR Out1 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct, fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut1,Shift_TimeIn1), '00:00:00', TimeBreak1, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn1 = '00:00:00' AND CheckLateDurationOut1 = '00:00:00' AND LeaveDurationInOut1 <> '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut1);
					END IF;

					SET CheckLateIn1 = 0;
					SET CheckLateDurationIn1 = '00:00:00';
					SET checkLateDurationDeductIn1 = '00:00:00';
					SET CheckLateOut1 = 0;
					SET CheckLateDurationOut1 = '00:00:00';
					SET checkLateDurationDeductOut1 = '00:00:00';
					
				END IF;
				IF Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND (In2 = '00:00:00' OR Out2 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct, fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut2,Shift_TimeIn2), '00:00:00', TimeBreak2, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn2 = '00:00:00' AND CheckLateDurationOut2 = '00:00:00' AND LeaveDurationInOut2 <> '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut2);
					END IF;

					SET CheckLateIn2 = 0;
					SET CheckLateDurationIn2 = '00:00:00';
					SET checkLateDurationDeductIn2 = '00:00:00';
					SET CheckLateOut2 = 0;
					SET CheckLateDurationOut2 = '00:00:00';
					SET checkLateDurationDeductOut2 = '00:00:00';
				END IF;
				IF Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND (In3 = '00:00:00' OR Out3 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct,fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut3,Shift_TimeIn3), '00:00:00', TimeBreak3, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn3 = '00:00:00' AND CheckLateDurationOut3 = '00:00:00' AND LeaveDurationInOut3 <> '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut3);
					END IF;

					SET CheckLateIn3 = 0;
					SET CheckLateDurationIn3 = '00:00:00';
					SET checkLateDurationDeductIn3 = '00:00:00';
					SET CheckLateOut3 = 0;
					SET CheckLateDurationOut3 = '00:00:00';
					SET checkLateDurationDeductOut3 = '00:00:00';
				END IF;
				IF Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND (In4 = '00:00:00' OR Out4 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct,fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut4,Shift_TimeIn4), '00:00:00', TimeBreak4, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn4 = '00:00:00' AND CheckLateDurationOut4 = '00:00:00' AND LeaveDurationInOut4 = '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut4);
					END IF;

					SET CheckLateIn4 = 0;
					SET CheckLateDurationIn4 = '00:00:00';
					SET checkLateDurationDeductIn4 = '00:00:00';
					SET CheckLateOut4 = 0;
					SET CheckLateDurationOut4 = '00:00:00';
					SET checkLateDurationDeductOut4 = '00:00:00';
				END IF;
				IF Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND (In5 = '00:00:00' OR Out5 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct,fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut5,Shift_TimeIn5), '00:00:00', TimeBreak5, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn5 = '00:00:00' AND CheckLateDurationOut5 = '00:00:00' AND LeaveDurationInOut5 = '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut5);
					END IF;

					SET CheckLateIn5 = 0;
					SET CheckLateDurationIn5 = '00:00:00';
					SET checkLateDurationDeductIn5 = '00:00:00';
					SET CheckLateOut5 = 0;
					SET CheckLateDurationOut5 = '00:00:00';
					SET checkLateDurationDeductOut5 = '00:00:00';
				END IF;
		
				IF fnHRMTimeToFloat(checkAbDurationDeduct) > Shift_TotalWorkHour THEN
					SET checkAbDurationDeduct = CONCAT(FLOOR(Shift_TotalWorkHour),':',(Shift_TotalWorkHour -FLOOR(Shift_TotalWorkHour))*60, ':00');
				END IF;
				
				-- Check Leave
				IF CheckOutLeave <> "" THEN
					SET CheckL = CheckL + 1;
				ELSEIF In1 = '00:00:01' OR LeaveDurationInOut1 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out1 = '00:00:01' OR LeaveDurationInOut1 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;	
				ELSEIF In2 = '00:00:01' OR LeaveDurationInOut2 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out2 = '00:00:01' OR LeaveDurationInOut2 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF In3 = '00:00:01' OR LeaveDurationInOut3 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out3 = '00:00:01' OR LeaveDurationInOut3 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF In4 = '00:00:01' OR LeaveDurationInOut4 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out4 = '00:00:01' OR LeaveDurationInOut4 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF In5 = '00:00:01' OR LeaveDurationInOut5 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out5 = '00:00:01' OR LeaveDurationInOut5 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF O1 = '00:00:01' THEN
					SET CheckL = CheckL + 1;
				ELSEIF O2 = '00:00:01' THEN
					SET CheckL = CheckL + 1; 
				END IF;

				-- Check Work Hour
				IF In1 <> '00:00:00' AND In1 <> '00:00:01' AND Out1 <> '00:00:00' AND Out1 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out1,IN1));
				END IF;
				IF In2 <> '00:00:00' AND In2 <> '00:00:01' AND Out2 <> '00:00:00' AND Out2 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out2,IN2));
				END IF;
				IF In3 <> '00:00:00' AND In3 <> '00:00:01' AND Out3 <> '00:00:00' AND Out3 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out3,IN3));
				END IF;
				IF In4 <> '00:00:00' AND In4 <> '00:00:01' AND Out4 <> '00:00:00' AND Out4 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out4,IN4));
				END IF;
				IF In5 <> '00:00:00' AND In5 <> '00:00:01' AND Out5 <> '00:00:00' AND Out5 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out5,IN5));
				END IF;
				IF WorkHour > Shift_TotalWorkHour THEN
					SET WorkHour = Shift_TotalWorkHour;
				END IF;

				SET TotalCheckLate = TotalCheckLate + CheckLateIn1 + CheckLateOut1 + CheckLateIn2 + CheckLateOut2 + CheckLateIn3 + CheckLateOut3 + CheckLateIn4 + CheckLateOut4 + CheckLateIn5 + CheckLateOut5;

				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn1);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut1);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn2);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut2);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn3);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut3);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn4);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut4);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn5);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut5);

				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn1);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut1);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn2);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut2);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn3);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut3);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn4);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut4);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn5);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut5);

				-- Check Negative AB & Late
				IF checkAbDurationDeduct <= '00:00:00' THEN
					SET checkAbDurationDeduct = '00:00:00';
					SET CheckAb = 0;
				END IF;
				IF TotalCheckLateDuration <= '00:00:00' THEN
					SET TotalCheckLateDuration = '00:00:00';
					SET TotalCheckLateDurationDeduct = '00:00:00';
					SET TotalCheckLate = 0;
				END IF;
				


				IF TotalCheckLate >0 AND CheckAb >0 AND CheckL > 0 THEN
					SET S = 'LA/AB/LE';
				ELSEIF TotalCheckLate >0 AND CheckAb >0 AND CheckL <= 0 THEN
					SET S = 'LA/AB';
				ELSEIF TotalCheckLate >0 AND CheckAb <= 0 AND CheckL > 0 THEN
					SET S = 'LA/LE';
				ELSEIF TotalCheckLate <= 0 AND CheckAb >0 AND CheckL > 0 THEN
					SET S = 'AB/LE';
				ELSEIF TotalCheckLate >0 AND CheckAb <= 0 AND CheckL <= 0 THEN
					SET S = 'LA';
				ELSEIF TotalCheckLate <=0 AND CheckAb > 0 AND CheckL <= 0 THEN
					SET S = 'AB';
				ELSEIF TotalCheckLate <=0 AND CheckAb <= 0 AND CheckL > 0 THEN
					SET S = 'LE';
				ELSE 
					SET S = 'P';
				END IF;

				IF In1 = '00:00:00' AND Out1 = '00:00:00' AND In2 = '00:00:00' AND Out2 = '00:00:00' AND In3 = '00:00:00' AND Out3 = '00:00:00' AND In4 = '00:00:00' AND Out4 = '00:00:00' AND In5 = '00:00:00' AND Out5 = '00:00:00' AND S = 'P' THEN
					SET S = 'B';
				END IF;

			END IF;

			IF CheckExist	> 0 THEN
					UPDATE hrm_timesheet_attendance SET Att_LateAmount=TotalCheckLate,Att_ABAmount=CheckAb,Att_Status=S,Att_RStatus=S,Att_WorkHour=WorkHour, Att_LateDuration=TotalCheckLateDuration, Att_LateDurationDeduct = TotalcheckLateDurationDeduct, Att_ABDurationDeduct = checkAbDurationDeduct  WHERE Att_FPID=FP_ID AND Att_Date=FP_Date;
			END IF;	

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckAttendanceRoster`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckAttendanceRoster`(SEmpID varchar(255), ShiftID varchar(255), FP_ID varchar(255), FP_Date Date)
    DETERMINISTIC
BEGIN
		DECLARE Shift_ID VARCHAR(255);
		DECLARE Shift_Day VARCHAR(255);
		DECLARE Shift_TotalWorkHour FLOAT DEFAULT(0);
		DECLARE Shift_TimeIn1 TIME;
		DECLARE Shift_TimeInPeriod1 TIME;
		DECLARE Shift_TimeOut1 TIME;
		DECLARE Shift_TimeOutPeriod1 TIME;
		DECLARE Shift_TimeIn2 TIME;
		DECLARE Shift_TimeInPeriod2 TIME;
		DECLARE Shift_TimeOut2 TIME;
		DECLARE Shift_TimeOutPeriod2 TIME;
		DECLARE Shift_TimeIn3 TIME;
		DECLARE Shift_TimeInPeriod3 TIME;
		DECLARE Shift_TimeOut3 TIME;
		DECLARE Shift_TimeOutPeriod3 TIME;
		DECLARE Shift_TimeIn4 TIME;
		DECLARE Shift_TimeInPeriod4 TIME;
		DECLARE Shift_TimeOut4 TIME;
		DECLARE Shift_TimeOutPeriod4 TIME;
		DECLARE Shift_TimeIn5 TIME;
		DECLARE Shift_TimeInPeriod5 TIME;
		DECLARE Shift_TimeOut5 TIME;
		DECLARE Shift_TimeOutPeriod5 TIME;
		DECLARE Shift_TimeInOvertime TIME;
		DECLARE Shift_TimeOutOvertime TIME;

		DECLARE Shift_TimeIn1LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut1LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeIn2LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut2LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeIn3LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut3LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeIn4LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut4LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeIn5LateAmt INT DEFAULT(0);
		DECLARE Shift_TimeOut5LateAmt INT DEFAULT(0);

		DECLARE CheckExist TINYINT DEFAULT(0);

		DECLARE TotalCheckLate TINYINT DEFAULT(0);
		DECLARE TotalCheckLateDuration TIME DEFAULT('00:00:00');
		DECLARE TotalcheckLateDurationDeduct TIME DEFAULT('00:00:00');

		DECLARE CheckLateIn1 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn1 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn1 TIME DEFAULT('00:00:00');
		DECLARE CheckLateIn2 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn2 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn2 TIME DEFAULT('00:00:00');
		DECLARE CheckLateIn3 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn3 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn3 TIME DEFAULT('00:00:00');
		DECLARE CheckLateIn4 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn4 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn4 TIME DEFAULT('00:00:00');
		DECLARE CheckLateIn5 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationIn5 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductIn5 TIME DEFAULT('00:00:00');

		DECLARE CheckLateOut1 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut1 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut1 TIME DEFAULT('00:00:00');
		DECLARE CheckLateOut2 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut2 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut2 TIME DEFAULT('00:00:00');
		DECLARE CheckLateOut3 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut3 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut3 TIME DEFAULT('00:00:00');
		DECLARE CheckLateOut4 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut4 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut4 TIME DEFAULT('00:00:00');
		DECLARE CheckLateOut5 TINYINT DEFAULT(0);
		DECLARE CheckLateDurationOut5 TIME DEFAULT('00:00:00');
		DECLARE checkLateDurationDeductOut5 TIME DEFAULT('00:00:00');

		DECLARE LeaveDurationStatus VARCHAR(255) DEFAULT('');
		DECLARE LeaveDurationInOut1 TIME DEFAULT('00:00:00');
		DECLARE LeaveDurationInOut2 TIME DEFAULT('00:00:00');
		DECLARE LeaveDurationInOut3 TIME DEFAULT('00:00:00');
		DECLARE LeaveDurationInOut4 TIME DEFAULT('00:00:00');
		DECLARE LeaveDurationInOut5 TIME DEFAULT('00:00:00');

		DECLARE CheckOutLeave VARCHAR(255) DEFAULT('');

		DECLARE CheckAb TINYINT DEFAULT(0);
		DECLARE checkAbDurationDeduct TIME DEFAULT('00:00:00');
		DECLARE CheckL TINYINT DEFAULT(0);
		DECLARE S VARCHAR(255) DEFAULT('');

		DECLARE In1 TIME DEFAULT('00:00:00');
		DECLARE In2 TIME DEFAULT('00:00:00');
		DECLARE In3 TIME DEFAULT('00:00:00');
		DECLARE In4 TIME DEFAULT('00:00:00');
		DECLARE In5 TIME DEFAULT('00:00:00');
		DECLARE Out1 TIME DEFAULT('00:00:00');
		DECLARE Out2 TIME DEFAULT('00:00:00');
		DECLARE Out3 TIME DEFAULT('00:00:00');
		DECLARE Out4 TIME DEFAULT('00:00:00');
		DECLARE Out5 TIME DEFAULT('00:00:00');
		DECLARE OverIn TIME DEFAULT('00:00:00');
		DECLARE OverOut TIME DEFAULT('00:00:00');
		DECLARE O1 TIME DEFAULT('00:00:00');
		DECLARE O2 TIME DEFAULT('00:00:00');
		DECLARE WorkHour INT DEFAULT(0);

		DECLARE TimeBreak1 VARCHAR(255) DEFAULT('');
		DECLARE TimeBreak2 VARCHAR(255) DEFAULT('');
		DECLARE TimeBreak3 VARCHAR(255) DEFAULT('');
		DECLARE TimeBreak4 VARCHAR(255) DEFAULT('');
		DECLARE TimeBreak5 VARCHAR(255) DEFAULT('');

		
		SELECT wd.Shift_ID,wd.Shift_Day,wd.Shift_TotalWorkHour,wd.Shift_TimeIn1,wd.Shift_TimeInPeriod1,wd.Shift_TimeOut1,wd.Shift_TimeOutPeriod1,wd.Shift_TimeIn2,wd.Shift_TimeInPeriod2,wd.Shift_TimeOut2,wd.Shift_TimeOutPeriod2,wd.Shift_TimeIn3,wd.Shift_TimeInPeriod3,wd.Shift_TimeOut3,wd.Shift_TimeOutPeriod3,wd.Shift_TimeIn4,wd.Shift_TimeInPeriod4,wd.Shift_TimeOut4,wd.Shift_TimeOutPeriod4,wd.Shift_TimeIn5,wd.Shift_TimeInPeriod5,wd.Shift_TimeOut5,wd.Shift_TimeOutPeriod5,wd.Shift_TimeInOvertime,wd.Shift_TimeOutOvertime,wd.Shift_TimeIn1LateDuration,wd.Shift_TimeOut1LateDuration,wd.Shift_TimeIn2LateDuration,wd.Shift_TimeOut2LateDuration,wd.Shift_TimeIn3LateDuration,wd.Shift_TimeOut3LateDuration,wd.Shift_TimeIn4LateDuration,wd.Shift_TimeOut4LateDuration,wd.Shift_TimeIn5LateDuration,wd.Shift_TimeOut5LateDuration,Shift_TimeBreak1,Shift_TimeBreak2,Shift_TimeBreak3,Shift_TimeBreak4,Shift_TimeBreak5 INTO Shift_ID, Shift_Day, Shift_TotalWorkHour, Shift_TimeIn1, Shift_TimeInPeriod1, Shift_TimeOut1, Shift_TimeOutPeriod1, Shift_TimeIn2, Shift_TimeInPeriod2, Shift_TimeOut2, Shift_TimeOutPeriod2, Shift_TimeIn3, Shift_TimeInPeriod3, Shift_TimeOut3, Shift_TimeOutPeriod3, Shift_TimeIn4, Shift_TimeInPeriod4, Shift_TimeOut4, Shift_TimeOutPeriod4, Shift_TimeIn5, Shift_TimeInPeriod5, Shift_TimeOut5, Shift_TimeOutPeriod5, Shift_TimeInOvertime, Shift_TimeOutOvertime, Shift_TimeIn1LateAmt, Shift_TimeOut1LateAmt, Shift_TimeIn2LateAmt, Shift_TimeOut2LateAmt, Shift_TimeIn3LateAmt, Shift_TimeOut3LateAmt, Shift_TimeIn4LateAmt, Shift_TimeOut4LateAmt, Shift_TimeIn5LateAmt, Shift_TimeOut5LateAmt, TimeBreak1, TimeBreak2, TimeBreak3, TimeBreak4, TimeBreak5 FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID = ShiftID LIMIT 1 OFFSET 1; 
		
		SELECT COUNT(*) INTO CheckExist FROM  hrm_timesheet_attendance att WHERE att.Att_FPID = FP_ID AND att.Att_Date = FP_Date;
		IF CheckExist > 0 THEN
			SELECT Att_FPID,Att_Date,Att_In1,Att_Out1,Att_In2,Att_Out2,Att_In3,Att_Out3,Att_In4,Att_Out4,Att_In5,Att_Out5,Att_OvertimeIn,Att_OvertimeOut,Att_Other1,Att_Other2,Att_Status,Att_LeaveDurationInOut1,Att_LeaveDurationInOut2,Att_LeaveDurationInOut3,Att_LeaveDurationInOut4,Att_LeaveDurationInOut5,Att_LeaveDurationStatus,Att_OutLeave INTO FP_ID,FP_Date,In1,Out1,In2,Out2,In3,Out3,In4,Out4,In5,Out5,OverIn,OverOut,O1,O2,S,LeaveDurationInOut1,LeaveDurationInOut2,LeaveDurationInOut3,LeaveDurationInOut4,LeaveDurationInOut5,LeaveDurationStatus,CheckOutLeave FROM hrm_timesheet_attendance att WHERE att.Att_FPID = FP_ID AND att.Att_Date = FP_Date;
		END IF;
				

			-- Check Late
			IF Shift_TimeInPeriod1 != "00:00:00" AND Shift_TimeInPeriod1 < In1 AND ADDTIME(Shift_TimeInPeriod1, SEC_TO_TIME(Shift_TimeIn1LateAmt *60)) >= In1 AND In1 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In1%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In1,Shift_TimeInPeriod1), In1, TimeBreak1, 'TimeIn') > LeaveDurationInOut1 THEN
						SET CheckLateIn1 = 1;
						SET CheckLateDurationIn1 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In1,Shift_TimeInPeriod1),LeaveDurationInOut1), In1, TimeBreak1, 'TimeIn');
						SET checkLateDurationDeductIn1 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn1);
					END IF;
				ELSE
					SET CheckLateIn1 = 1;
					SET CheckLateDurationIn1 = fnHRMCheckBreakTime(TIMEDIFF(In1,Shift_TimeInPeriod1), In1, TimeBreak1, 'TimeIn');
					SET checkLateDurationDeductIn1 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn1);
				END IF;
			END IF;

			IF Shift_TimeOutPeriod1 != "00:00:00" AND Shift_TimeOutPeriod1 > Out1 AND TIMEDIFF(Shift_TimeOutPeriod1, SEC_TO_TIME(Shift_TimeOut1LateAmt *60)) <= Out1 AND In1 <> '00:00:00' AND Out1 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out1%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod1, Out1), Out1, TimeBreak1, 'TimeOut') > LeaveDurationInOut1 THEN
						SET CheckLateOut1 = 1;
						SET CheckLateDurationOut1 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod1, Out1),LeaveDurationInOut1), Out1, TimeBreak1, 'TimeOut');
						SET checkLateDurationDeductOut1 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut1);
					END IF;
				ELSE
					SET CheckLateOut1 = 1;
					SET CheckLateDurationOut1 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod1, Out1), Out1, TimeBreak1, 'TimeOut');
					SET checkLateDurationDeductOut1 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut1);
				END IF;
			END IF;
		
			IF Shift_TimeInPeriod2 != "00:00:00" AND Shift_TimeInPeriod2 < In2 AND ADDTIME(Shift_TimeInPeriod2, SEC_TO_TIME(Shift_TimeIn2LateAmt *60)) >= In2 AND In2 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In2%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In2,Shift_TimeInPeriod2), In2, TimeBreak2, 'TimeIn') > LeaveDurationInOut2 THEN
						SET CheckLateIn2 = 1;
						SET CheckLateDurationIn2 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In2,Shift_TimeInPeriod2),LeaveDurationInOut2), In2, TimeBreak2, 'TimeIn');
						SET checkLateDurationDeductIn2 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn2);
					END IF;
				ELSE
					SET CheckLateIn2 = 1;
					SET CheckLateDurationIn2 = fnHRMCheckBreakTime(TIMEDIFF(In2,Shift_TimeInPeriod2), In2, TimeBreak2, 'TimeIn');
					SET checkLateDurationDeductIn2 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn2);
				END IF;
			END IF;

			IF Shift_TimeOutPeriod2 != "00:00:00" AND Shift_TimeOutPeriod2 > Out2 AND TIMEDIFF(Shift_TimeOutPeriod2, SEC_TO_TIME(Shift_TimeOut2LateAmt *60)) <= Out2 AND In2 <> '00:00:00' AND Out2 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out2%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod2, Out2), Out2, TimeBreak2, 'TimeOut') > LeaveDurationInOut2 THEN
						SET CheckLateOut2 = 1;
						SET CheckLateDurationOut2 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod2, Out2),LeaveDurationInOut2), Out2, TimeBreak2, 'TimeOut');
						SET checkLateDurationDeductOut2 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut2);
					END IF;
				ELSE
					SET CheckLateOut2 = 1;
					SET CheckLateDurationOut2 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod2, Out2), Out2, TimeBreak2, 'TimeOut');
					SET checkLateDurationDeductOut2 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut2);
				END IF;
			END IF;
			
			IF Shift_TimeInPeriod3 != "00:00:00" AND Shift_TimeInPeriod3 < In3 AND ADDTIME(Shift_TimeInPeriod3, SEC_TO_TIME(Shift_TimeIn3LateAmt *60)) >= In3 AND In3 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In3%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In3,Shift_TimeInPeriod3), In3, TimeBreak3, 'TimeIn') > LeaveDurationInOut3 THEN
						SET CheckLateIn3 = 1;
						SET CheckLateDurationIn3 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In3,Shift_TimeInPeriod3),LeaveDurationInOut3), In3, TimeBreak3, 'TimeIn');
						SET checkLateDurationDeductIn3 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn3);
					END IF;
				ELSE
					SET CheckLateIn3 = 1;
					SET CheckLateDurationIn3 = fnHRMCheckBreakTime(TIMEDIFF(In3,Shift_TimeInPeriod3), In3, TimeBreak3, 'TimeIn');
					SET checkLateDurationDeductIn3 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn3);
				END IF;
			END IF;
			
			IF Shift_TimeOutPeriod3 != "00:00:00" AND Shift_TimeOutPeriod3 > Out3 AND TIMEDIFF(Shift_TimeOutPeriod3, SEC_TO_TIME(Shift_TimeOut3LateAmt *60)) <= Out3 AND In3 <> '00:00:00' AND Out3 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out3%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod3, Out3), Out3, TimeBreak3, 'TimeOut') > LeaveDurationInOut3 THEN
						SET CheckLateOut3 = 1;
						SET CheckLateDurationOut3 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod3, Out3),LeaveDurationInOut3), Out3, TimeBreak3, 'TimeOut');
						SET checkLateDurationDeductOut3 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut3);
					END IF;
				ELSE
					SET CheckLateOut3 = 1;
					SET CheckLateDurationOut3 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod3, Out3), Out3, TimeBreak3, 'TimeOut');
					SET checkLateDurationDeductOut3 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut3);
				END IF;
			END IF;
			
			IF Shift_TimeInPeriod4 != "00:00:00" AND Shift_TimeInPeriod4 < In4 AND ADDTIME(Shift_TimeInPeriod4, SEC_TO_TIME(Shift_TimeIn4LateAmt *60)) >= In4 AND In4 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In4%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In4,Shift_TimeInPeriod4), In4, TimeBreak4, 'TimeIn') > LeaveDurationInOut4 THEN
						SET CheckLateIn4 = 1;
						SET CheckLateDurationIn4 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In4,Shift_TimeInPeriod4),LeaveDurationInOut4), In4, TimeBreak4, 'TimeIn');
						SET checkLateDurationDeductIn4 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn4);
					END IF;
				ELSE
					SET CheckLateIn4 = 1;
					SET CheckLateDurationIn4 = fnHRMCheckBreakTime(TIMEDIFF(In4,Shift_TimeInPeriod4), In4, TimeBreak4, 'TimeIn');
					SET checkLateDurationDeductIn4 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn4);
				END IF;
			END IF;
			
			IF Shift_TimeOutPeriod4 != "00:00:00" AND Shift_TimeOutPeriod4 > Out4 AND TIMEDIFF(Shift_TimeOutPeriod4, SEC_TO_TIME(Shift_TimeOut4LateAmt *60)) <= Out4 AND In4 <> '00:00:00' AND Out4 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out4%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod4, Out4), Out4, TimeBreak4, 'TimeOut') > LeaveDurationInOut4 THEN
						SET CheckLateOut4 = 1;
						SET CheckLateDurationOut4 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod4, Out4),LeaveDurationInOut4), Out4, TimeBreak4, 'TimeOut');
						SET checkLateDurationDeductOut4 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut4);
					END IF;
				ELSE
					SET CheckLateOut4 = 1;
					SET CheckLateDurationOut4 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod4, Out4), Out4, TimeBreak4, 'TimeOut');
					SET checkLateDurationDeductOut4 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut4);
				END IF;
			END IF;
			
			IF Shift_TimeInPeriod5 != "00:00:00" AND Shift_TimeInPeriod5 < In5 AND ADDTIME(Shift_TimeInPeriod5, SEC_TO_TIME(Shift_TimeIn5LateAmt *60)) >= In5 AND In5 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%In5%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(In5,Shift_TimeInPeriod5), In5, TimeBreak5, 'TimeIn') > LeaveDurationInOut5 THEN
						SET CheckLateIn5 = 1;
						SET CheckLateDurationIn5 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(In5,Shift_TimeInPeriod5),LeaveDurationInOut5), In5, TimeBreak5, 'TimeIn');
						SET checkLateDurationDeductIn5 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn5);
					END IF;
				ELSE
					SET CheckLateIn5 = 1;
					SET CheckLateDurationIn5 = fnHRMCheckBreakTime(TIMEDIFF(In5,Shift_TimeInPeriod5), In5, TimeBreak5, 'TimeIn');
					SET checkLateDurationDeductIn5 = fnHRMCheckLateDurationDeduction(CheckLateDurationIn5);
				END IF;
			END IF;
			
			IF Shift_TimeOutPeriod5 != "00:00:00" AND Shift_TimeOutPeriod5 > Out5 AND TIMEDIFF(Shift_TimeOutPeriod5, SEC_TO_TIME(Shift_TimeOut5LateAmt *60)) <= Out5 AND In5 <> '00:00:00' AND Out5 <> '00:00:00' THEN
				IF LeaveDurationStatus LIKE '%Out5%' THEN
					IF fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod5, Out5), Out5, TimeBreak5, 'TimeOut') > LeaveDurationInOut5 THEN
						SET CheckLateOut5 = 1;
						SET CheckLateDurationOut5 = fnHRMCheckBreakTime(TIMEDIFF(TIMEDIFF(Shift_TimeOutPeriod5, Out5),LeaveDurationInOut5), Out5, TimeBreak5, 'TimeOut');
						SET checkLateDurationDeductOut5 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut5);
					END IF;
				ELSE
					SET CheckLateOut5 = 1;
					SET CheckLateDurationOut5 = fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOutPeriod5, Out5), Out5, TimeBreak5, 'TimeOut');
					SET checkLateDurationDeductOut5 = fnHRMCheckLateDurationDeduction(CheckLateDurationOut5);	
				END IF;		
			END IF;

			IF S IS NULL THEN
				SET S = '';
			END IF;
			
			IF S <> 'HO' AND S <> 'B' THEN
				
				-- Check AB
				IF Shift_TimeIn1 <> '00:00:00' AND Shift_TimeOut1 <> '00:00:00' AND (In1 = '00:00:00' OR Out1 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct, fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut1,Shift_TimeIn1), '00:00:00', TimeBreak1, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn1 = '00:00:00' AND CheckLateDurationOut1 = '00:00:00' AND LeaveDurationInOut1 <> '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut1);
					END IF;

					SET CheckLateIn1 = 0;
					SET CheckLateDurationIn1 = '00:00:00';
					SET checkLateDurationDeductIn1 = '00:00:00';
					SET CheckLateOut1 = 0;
					SET CheckLateDurationOut1 = '00:00:00';
					SET checkLateDurationDeductOut1 = '00:00:00';
					
				END IF;
				IF Shift_TimeIn2 <> '00:00:00' AND Shift_TimeOut2 <> '00:00:00' AND (In2 = '00:00:00' OR Out2 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct, fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut2,Shift_TimeIn2), '00:00:00', TimeBreak2, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn2 = '00:00:00' AND CheckLateDurationOut2 = '00:00:00' AND LeaveDurationInOut2 <> '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut2);
					END IF;

					SET CheckLateIn2 = 0;
					SET CheckLateDurationIn2 = '00:00:00';
					SET checkLateDurationDeductIn2 = '00:00:00';
					SET CheckLateOut2 = 0;
					SET CheckLateDurationOut2 = '00:00:00';
					SET checkLateDurationDeductOut2 = '00:00:00';
				END IF;
				IF Shift_TimeIn3 <> '00:00:00' AND Shift_TimeOut3 <> '00:00:00' AND (In3 = '00:00:00' OR Out3 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct,fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut3,Shift_TimeIn3), '00:00:00', TimeBreak3, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn3 = '00:00:00' AND CheckLateDurationOut3 = '00:00:00' AND LeaveDurationInOut3 <> '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut3);
					END IF;

					SET CheckLateIn3 = 0;
					SET CheckLateDurationIn3 = '00:00:00';
					SET checkLateDurationDeductIn3 = '00:00:00';
					SET CheckLateOut3 = 0;
					SET CheckLateDurationOut3 = '00:00:00';
					SET checkLateDurationDeductOut3 = '00:00:00';
				END IF;
				IF Shift_TimeIn4 <> '00:00:00' AND Shift_TimeOut4 <> '00:00:00' AND (In4 = '00:00:00' OR Out4 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct,fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut4,Shift_TimeIn4), '00:00:00', TimeBreak4, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn4 = '00:00:00' AND CheckLateDurationOut4 = '00:00:00' AND LeaveDurationInOut4 = '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut4);
					END IF;

					SET CheckLateIn4 = 0;
					SET CheckLateDurationIn4 = '00:00:00';
					SET checkLateDurationDeductIn4 = '00:00:00';
					SET CheckLateOut4 = 0;
					SET CheckLateDurationOut4 = '00:00:00';
					SET checkLateDurationDeductOut4 = '00:00:00';
				END IF;
				IF Shift_TimeIn5 <> '00:00:00' AND Shift_TimeOut5 <> '00:00:00' AND (In5 = '00:00:00' OR Out5 = '00:00:00') THEN
					SET checkAbDurationDeduct = ADDTIME(checkAbDurationDeduct,fnHRMCheckBreakTime(TIMEDIFF(Shift_TimeOut5,Shift_TimeIn5), '00:00:00', TimeBreak5, 'AB'));
					SET CheckAb = CheckAb + 1;

					IF CheckLateDurationIn5 = '00:00:00' AND CheckLateDurationOut5 = '00:00:00' AND LeaveDurationInOut5 = '00:00:00' THEN
						SET checkAbDurationDeduct = TIMEDIFF(checkAbDurationDeduct, LeaveDurationInOut5);
					END IF;

					SET CheckLateIn5 = 0;
					SET CheckLateDurationIn5 = '00:00:00';
					SET checkLateDurationDeductIn5 = '00:00:00';
					SET CheckLateOut5 = 0;
					SET CheckLateDurationOut5 = '00:00:00';
					SET checkLateDurationDeductOut5 = '00:00:00';
				END IF;
		
				IF fnHRMTimeToFloat(checkAbDurationDeduct) > Shift_TotalWorkHour THEN
					SET checkAbDurationDeduct = CONCAT(FLOOR(Shift_TotalWorkHour),':',(Shift_TotalWorkHour -FLOOR(Shift_TotalWorkHour))*60, ':00');
				END IF;
				
				-- Check Leave
				IF CheckOutLeave <> "" THEN
					SET CheckL = CheckL + 1;
				ELSEIF In1 = '00:00:01' OR LeaveDurationInOut1 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out1 = '00:00:01' OR LeaveDurationInOut1 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;	
				ELSEIF In2 = '00:00:01' OR LeaveDurationInOut2 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out2 = '00:00:01' OR LeaveDurationInOut2 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF In3 = '00:00:01' OR LeaveDurationInOut3 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out3 = '00:00:01' OR LeaveDurationInOut3 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF In4 = '00:00:01' OR LeaveDurationInOut4 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out4 = '00:00:01' OR LeaveDurationInOut4 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF In5 = '00:00:01' OR LeaveDurationInOut5 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF Out5 = '00:00:01' OR LeaveDurationInOut5 <> '00:00:00' THEN
					SET CheckL = CheckL + 1;
				ELSEIF O1 = '00:00:01' THEN
					SET CheckL = CheckL + 1;
				ELSEIF O2 = '00:00:01' THEN
					SET CheckL = CheckL + 1; 
				END IF;

				-- Check Work Hour
				IF In1 <> '00:00:00' AND In1 <> '00:00:01' AND Out1 <> '00:00:00' AND Out1 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out1,IN1));
				END IF;
				IF In2 <> '00:00:00' AND In2 <> '00:00:01' AND Out2 <> '00:00:00' AND Out2 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out2,IN2));
				END IF;
				IF In3 <> '00:00:00' AND In3 <> '00:00:01' AND Out3 <> '00:00:00' AND Out3 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out3,IN3));
				END IF;
				IF In4 <> '00:00:00' AND In4 <> '00:00:01' AND Out4 <> '00:00:00' AND Out4 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out4,IN4));
				END IF;
				IF In5 <> '00:00:00' AND In5 <> '00:00:01' AND Out5 <> '00:00:00' AND Out5 <> '00:00:01' THEN
					SET WorkHour = WorkHour + HOUR(TIMEDIFF(Out5,IN5));
				END IF;
				IF WorkHour > Shift_TotalWorkHour THEN
					SET WorkHour = Shift_TotalWorkHour;
				END IF;

				SET TotalCheckLate = TotalCheckLate + CheckLateIn1 + CheckLateOut1 + CheckLateIn2 + CheckLateOut2 + CheckLateIn3 + CheckLateOut3 + CheckLateIn4 + CheckLateOut4 + CheckLateIn5 + CheckLateOut5;

				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn1);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut1);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn2);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut2);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn3);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut3);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn4);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut4);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationIn5);
				SET TotalCheckLateDuration = ADDTIME(TotalCheckLateDuration, CheckLateDurationOut5);

				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn1);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut1);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn2);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut2);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn3);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut3);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn4);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut4);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductIn5);
				SET TotalCheckLateDurationDeduct = ADDTIME(TotalCheckLateDurationDeduct, CheckLateDurationDeductOut5);

				-- Check Negative AB & Late
				IF checkAbDurationDeduct <= '00:00:00' THEN
					SET checkAbDurationDeduct = '00:00:00';
					SET CheckAb = 0;
				END IF;
				IF TotalCheckLateDuration <= '00:00:00' THEN
					SET TotalCheckLateDuration = '00:00:00';
					SET TotalCheckLateDurationDeduct = '00:00:00';
					SET TotalCheckLate = 0;
				END IF;
				


				IF TotalCheckLate >0 AND CheckAb >0 AND CheckL > 0 THEN
					SET S = 'LA/AB/LE';
				ELSEIF TotalCheckLate >0 AND CheckAb >0 AND CheckL <= 0 THEN
					SET S = 'LA/AB';
				ELSEIF TotalCheckLate >0 AND CheckAb <= 0 AND CheckL > 0 THEN
					SET S = 'LA/LE';
				ELSEIF TotalCheckLate <= 0 AND CheckAb >0 AND CheckL > 0 THEN
					SET S = 'AB/LE';
				ELSEIF TotalCheckLate >0 AND CheckAb <= 0 AND CheckL <= 0 THEN
					SET S = 'LA';
				ELSEIF TotalCheckLate <=0 AND CheckAb > 0 AND CheckL <= 0 THEN
					SET S = 'AB';
				ELSEIF TotalCheckLate <=0 AND CheckAb <= 0 AND CheckL > 0 THEN
					SET S = 'LE';
				ELSE 
					SET S = 'P';
				END IF;

				IF In1 = '00:00:00' AND Out1 = '00:00:00' AND In2 = '00:00:00' AND Out2 = '00:00:00' AND In3 = '00:00:00' AND Out3 = '00:00:00' AND In4 = '00:00:00' AND Out4 = '00:00:00' AND In5 = '00:00:00' AND Out5 = '00:00:00' AND S = 'P' THEN
					SET S = 'B';
				END IF;

			END IF;

			IF CheckExist	> 0 THEN
					UPDATE hrm_timesheet_attendance SET Att_LateAmount=TotalCheckLate,Att_ABAmount=CheckAb,Att_Status=S,Att_RStatus=S,Att_WorkHour=WorkHour, Att_LateDuration=TotalCheckLateDuration, Att_LateDurationDeduct = TotalcheckLateDurationDeduct, Att_ABDurationDeduct = checkAbDurationDeduct  WHERE Att_FPID=FP_ID AND Att_Date=FP_Date;
			END IF;			
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckAuthorisationGroupTemp`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckAuthorisationGroupTemp`(IN SUserID varchar(255), IN AuthGroupID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE done INT DEFAULT FALSE;
	DECLARE AuthID VARCHAR(255) DEFAULT('');
	DECLARE AuthType varchar(255) DEFAULT('');
	DECLARE cur1 CURSOR FOR SELECT DISTINCT(Auth_ID) FROM hrm_authorisation_approved WHERE Auth_GroupID = AuthGroupID;


	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	OPEN cur1;
	read_loop: LOOP
    FETCH cur1 INTO AuthID;
    IF done THEN
      LEAVE read_loop;
    END IF;
	BEGIN
			DECLARE C1 CURSOR FOR SELECT SQL_CALC_FOUND_ROWS COALESCE(auth_type, '') FROM hrm_authorisation WHERE Auth_ID = AuthID;
			OPEN C1;
					IF FOUND_ROWS() > 0 THEN FETCH C1 INTO AuthType; END IF;
			CLOSE C1;
	END;

		IF AuthType != "" THEN
		-- Dayoff
			CALL spHRMCheckAuthorisationGroupTemp_Dayoff(SUserID, AuthID, AuthType);

		-- Deduction
			CALL spHRMCheckAuthorisationGroupTemp_Deduction(SUserID, AuthID, AuthType);

		-- Overtime
			CALL spHRMCheckAuthorisationGroupTemp_Overtime(SUserID, AuthID, AuthType);

		-- Leave
			CALL spHRMCheckAuthorisationGroupTemp_Leave(SUserID, AuthID, AuthType);

			-- Customer
			CALL ameCheckAuthorisationGroupTemp_Customer(SUserID, AuthID, AuthType);

			-- Sale Order
			CALL ameCheckAuthorisationGroupTemp_SaleOrder(SUserID, AuthID, AuthType);

			-- Quote
			CALL ameCheckAuthorisationGroupTemp_Quote(SUserID, AuthID, AuthType);

			-- Over Due Date
			CALL ameCheckAuthorisationGroupTemp_OverDueDate(SUserID, AuthID, AuthType);

			--  TEMPORARY
			CALL ameCheckAuthorisationGroupTemp_TemporaryCredit(SUserID, AuthID, AuthType);

			-- General 
			CALL ameCheckAuthorisationGroupTemp_General(SUserID, AuthID, AuthType);

			-- Budget
			CALL ameCheckAuthorisationGroupTemp_Budget(SUserID, AuthID, AuthType);

			-- Material
			CALL ameCheckAuthorisationGroupTemp_Material(SUserID, AuthID, AuthType);

			-- Expense
			CALL ameCheckAuthorisationGroupTemp_Expense(SUserID, AuthID, AuthType);

			-- Logistic Material
			CALL ameCheckAuthorisationGroupTemp_LogisticMaterial(SUserID, AuthID, AuthType);

			-- Logistic Expense
			CALL ameCheckAuthorisationGroupTemp_LogisticExpense(SUserID, AuthID, AuthType);

		END IF;

	END LOOP;
	CLOSE cur1;


	-- ---------------------------------------

	DELETE FROM hrm_authorisation_approved WHERE Auth_ProcessID IN(SELECT DISTINCT(Auth_ProcessID) FROM hrm_authorisation_approved_temp WHERE UserID = SUserID);

	INSERT INTO hrm_authorisation_approved(Auth_ProcessID,Auth_ProcessName,Auth_ID, Auth_GroupID,Auth_EmpID,Auth_Status,Auth_Date) (SELECT Auth_ProcessID,Auth_ProcessName,Auth_ID, Auth_GroupID,Auth_EmpID,Auth_Status,Auth_Date FROM hrm_authorisation_approved_temp WHERE UserID = SUserID);

	BEGIN
			DECLARE D1 INTEGER DEFAULT 0;
			DECLARE SProID VARCHAR(100) DEFAULT '';
			DECLARE SProName VARCHAR(100) DEFAULT '';
			DECLARE SAuthID VARCHAR(100) DEFAULT '';
			DECLARE SAuthGID VARCHAR(100) DEFAULT '';
			DECLARE C1 CURSOR FOR SELECT DISTINCT(Auth_ProcessID), Auth_ProcessName, Auth_ID, Auth_GroupID FROM hrm_authorisation_approved_temp WHERE UserID = SUserID;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET D1 = 1;
			OPEN C1;
					L1: LOOP FETCH C1 INTO SProID, SProName, SAuthID, SAuthGID;
							IF D1 = 1 THEN LEAVE L1; END IF;
							CALL spHRMGetCheckAuthorisationTranApproved(SUserID, SProID, SProName, SAuthID, SAuthGID);
					END LOOP L1;
			CLOSE C1;
	END;

	DELETE FROM hrm_authorisation_approved_temp WHERE UserID = SUserID;

	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckAuthorisationGroupTemp_Dayoff`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckAuthorisationGroupTemp_Dayoff`(IN SUserID varchar(255), IN AuthID varchar(255), IN AuthType varchar(255))
    DETERMINISTIC
BEGIN

	-- Dayoff

	DELETE FROM hrm_authorisation_group_temp WHERE Auth_TranID IN(SELECT dayoff_id FROM hrm_timesheet_dayoff WHERE LOWER(dayoff_status) NOT IN('approved', 'rejected') AND dayoff_authid = AuthID);
	INSERT INTO hrm_authorisation_group_temp(Auth_TranID,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description) (SELECT dayoff_id,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description FROM hrm_authorisation_group INNER JOIN hrm_timesheet_dayoff ON(LOWER(dayoff_status) NOT IN('approved', 'rejected') AND dayoff_authid = AuthID) WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));

	DELETE FROM hrm_authorisation_group_detail_temp WHERE Auth_TranID IN(SELECT dayoff_id FROM hrm_timesheet_dayoff WHERE LOWER(dayoff_status) NOT IN('approved', 'rejected') AND dayoff_authid = AuthID);
	INSERT INTO hrm_authorisation_group_detail_temp(Auth_TranID,AuthGroup_ID,AuthGroup_EmpID) (SELECT dayoff_id,AuthGroup_ID,AuthGroup_EmpID FROM hrm_authorisation_group_detail INNER JOIN hrm_timesheet_dayoff ON(LOWER(dayoff_status) NOT IN('approved', 'rejected') AND dayoff_authid = AuthID) WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));

	IF LOWER(AuthType) = 'individual' THEN
		CALL spHRMAddIAuthorisationApprovedTemp(SUserID, AuthID, 'Dayoff');
	ELSE
		CALL spHRMAddGAuthorisationApprovedTemp(SUserID, AuthID, 'Dayoff');
	END IF;

	DELETE FROM hrm_authorisation_approved WHERE Auth_ProcessID IN(SELECT dayoff_id FROM hrm_timesheet_dayoff WHERE LOWER(dayoff_status) NOT IN('approved', 'rejected') AND dayoff_authid = AuthID);
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckAuthorisationGroupTemp_Deduction`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckAuthorisationGroupTemp_Deduction`(IN SUserID varchar(255), IN AuthID varchar(255), IN AuthType varchar(255))
    DETERMINISTIC
BEGIN

	-- Deduction

	DELETE FROM hrm_authorisation_group_temp WHERE Auth_TranID IN(SELECT deduction_id FROM hrm_payroll_deduction WHERE LOWER(deduction_status) NOT IN('approved', 'rejected') AND deduction_authid = AuthID);
	INSERT INTO hrm_authorisation_group_temp(Auth_TranID,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description) (SELECT deduction_id,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description FROM hrm_authorisation_group INNER JOIN hrm_payroll_deduction ON(LOWER(deduction_status) NOT IN('approved', 'rejected') AND deduction_authid = AuthID) WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));

	DELETE FROM hrm_authorisation_group_detail_temp WHERE Auth_TranID IN(SELECT deduction_id FROM hrm_payroll_deduction WHERE LOWER(deduction_status) NOT IN('approved', 'rejected') AND deduction_authid = AuthID);
	INSERT INTO hrm_authorisation_group_detail_temp(Auth_TranID,AuthGroup_ID,AuthGroup_EmpID) (SELECT deduction_id,AuthGroup_ID,AuthGroup_EmpID FROM hrm_authorisation_group_detail INNER JOIN hrm_payroll_deduction ON(LOWER(deduction_status) NOT IN('approved', 'rejected') AND deduction_authid = AuthID) WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));

	IF LOWER(AuthType) = 'individual' THEN
		CALL spHRMAddIAuthorisationApprovedTemp(SUserID, AuthID, 'Deduction');
	ELSE
		CALL spHRMAddGAuthorisationApprovedTemp(SUserID, AuthID, 'Deduction');
	END IF;

	DELETE FROM hrm_authorisation_approved WHERE Auth_ProcessID IN(SELECT deduction_id FROM hrm_payroll_deduction WHERE LOWER(deduction_status) NOT IN('approved', 'rejected') AND deduction_authid = AuthID);
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckAuthorisationGroupTemp_Leave`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckAuthorisationGroupTemp_Leave`(IN SUserID varchar(255), IN AuthID varchar(255), IN AuthType varchar(255))
    DETERMINISTIC
BEGIN

	-- Leave

	DELETE FROM hrm_authorisation_group_temp WHERE Auth_TranID IN(SELECT leave_id FROM hrm_timesheet_leave WHERE LOWER(leave_status) NOT IN('approved', 'rejected') AND leave_authid = AuthID);
	INSERT INTO hrm_authorisation_group_temp(Auth_TranID,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description) (SELECT leave_id,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description FROM hrm_authorisation_group INNER JOIN hrm_timesheet_leave ON(LOWER(leave_status) NOT IN('approved', 'rejected') AND leave_authid = AuthID) WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));

	DELETE FROM hrm_authorisation_group_detail_temp WHERE Auth_TranID IN(SELECT leave_id FROM hrm_timesheet_leave WHERE LOWER(leave_status) NOT IN('approved', 'rejected') AND leave_authid = AuthID);
	INSERT INTO hrm_authorisation_group_detail_temp(Auth_TranID,AuthGroup_ID,AuthGroup_EmpID) (SELECT leave_id,AuthGroup_ID,AuthGroup_EmpID FROM hrm_authorisation_group_detail INNER JOIN hrm_timesheet_leave ON(LOWER(leave_status) NOT IN('approved', 'rejected') AND leave_authid = AuthID) WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));

	IF LOWER(AuthType) = 'individual' THEN
		CALL spHRMAddIAuthorisationApprovedTemp(SUserID, AuthID, 'Leave');
	ELSE
		CALL spHRMAddGAuthorisationApprovedTemp(SUserID, AuthID, 'Leave');
	END IF;

	DELETE FROM hrm_authorisation_approved WHERE Auth_ProcessID IN(SELECT leave_id FROM hrm_timesheet_leave WHERE LOWER(leave_status) NOT IN('approved', 'rejected') AND leave_authid = AuthID);
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckAuthorisationGroupTemp_Overtime`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckAuthorisationGroupTemp_Overtime`(IN SUserID varchar(255), IN AuthID varchar(255), IN AuthType varchar(255))
    DETERMINISTIC
BEGIN

	-- Overtime

	DELETE FROM hrm_authorisation_group_temp WHERE Auth_TranID IN(SELECT overtime_id FROM hrm_payroll_overtime WHERE LOWER(overtime_status) NOT IN('approved', 'rejected') AND overtime_authid = AuthID);
	INSERT INTO hrm_authorisation_group_temp(Auth_TranID,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description) (SELECT overtime_id,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description FROM hrm_authorisation_group INNER JOIN hrm_payroll_overtime ON(LOWER(overtime_status) NOT IN('approved', 'rejected') AND overtime_authid = AuthID) WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));

	DELETE FROM hrm_authorisation_group_detail_temp WHERE Auth_TranID IN(SELECT overtime_id FROM hrm_payroll_overtime WHERE LOWER(overtime_status) NOT IN('approved', 'rejected') AND overtime_authid = AuthID);
	INSERT INTO hrm_authorisation_group_detail_temp(Auth_TranID,AuthGroup_ID,AuthGroup_EmpID) (SELECT overtime_id,AuthGroup_ID,AuthGroup_EmpID FROM hrm_authorisation_group_detail INNER JOIN hrm_payroll_overtime ON(LOWER(overtime_status) NOT IN('approved', 'rejected') AND overtime_authid = AuthID) WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));

	IF LOWER(AuthType) = 'individual' THEN
		CALL spHRMAddIAuthorisationApprovedTemp(SUserID, AuthID, 'Overtime');
	ELSE
		CALL spHRMAddGAuthorisationApprovedTemp(SUserID, AuthID, 'Overtime');
	END IF;

	DELETE FROM hrm_authorisation_approved WHERE Auth_ProcessID IN(SELECT overtime_id FROM hrm_payroll_overtime WHERE LOWER(overtime_status) NOT IN('approved', 'rejected') AND overtime_authid = AuthID);
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckAuthorisationTemp`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckAuthorisationTemp`(IN SUserID varchar(255), IN AuthID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE AuthType varchar(255);

	SELECT auth_type INTO AuthType FROM hrm_authorisation WHERE Auth_ID = AuthID;

	-- Dayoff
	CALL spHRMCheckAuthorisationTemp_Dayoff(SUserID, AuthID, AuthType);

	-- Deduction
	CALL spHRMCheckAuthorisationTemp_Deduction(SUserID, AuthID, AuthType);

	-- Overtime
	CALL spHRMCheckAuthorisationTemp_Overtime(SUserID, AuthID, AuthType);

	-- Leave
	CALL spHRMCheckAuthorisationTemp_Leave(SUserID, AuthID, AuthType);

	-- Customer
	-- CALL ameCheckAuthorisationTemp_Customer(SUserID, AuthID, AuthType);

	-- Sale Order
	-- CALL ameCheckAuthorisationTemp_SaleOrder(SUserID, AuthID, AuthType);

	-- Quote
	-- CALL ameCheckAuthorisationTemp_Quote(SUserID, AuthID, AuthType);

	-- Over Due Date
	-- CALL ameCheckAuthorisationTemp_OverDueDate(SUserID, AuthID, AuthType);

	--  TEMPORARY
	-- CALL ameCheckAuthorisationTemp_TemporaryCredit(SUserID, AuthID, AuthType);

	-- General 
	-- CALL ameCheckAuthorisationTemp_General(SUserID, AuthID, AuthType);

	-- Budget
	-- CALL ameCheckAuthorisationTemp_Budget(SUserID, AuthID, AuthType);

	-- Material
	-- CALL ameCheckAuthorisationTemp_Material(SUserID, AuthID, AuthType);

	-- Expense
	-- CALL ameCheckAuthorisationTemp_Expense(SUserID, AuthID, AuthType);

	-- Logistic Material
	-- CALL ameCheckAuthorisationTemp_LogisticMaterial(SUserID, AuthID, AuthType);

	-- Logistic Expense
	-- CALL ameCheckAuthorisationTemp_LogisticExpense(SUserID, AuthID, AuthType);
	-- --------------------------------------------------------

	DELETE FROM hrm_authorisation_approved WHERE Auth_ProcessID IN(SELECT DISTINCT(Auth_ProcessID) FROM hrm_authorisation_approved_temp WHERE UserID = SUserID);
	
	INSERT INTO hrm_authorisation_approved(Auth_ProcessID,Auth_ProcessName,Auth_ID, Auth_GroupID,Auth_EmpID,Auth_Status,Auth_Date) (SELECT Auth_ProcessID,Auth_ProcessName,Auth_ID, Auth_GroupID,Auth_EmpID,Auth_Status,Auth_Date FROM hrm_authorisation_approved_temp WHERE UserID = SUserID);

	BEGIN
			DECLARE D1 INTEGER DEFAULT 0;
			DECLARE SProID VARCHAR(100) DEFAULT '';
			DECLARE SProName VARCHAR(100) DEFAULT '';
			DECLARE SAuthID VARCHAR(100) DEFAULT '';
			DECLARE SAuthGID VARCHAR(100) DEFAULT '';
			DECLARE C1 CURSOR FOR SELECT DISTINCT(Auth_ProcessID), Auth_ProcessName, Auth_ID, Auth_GroupID FROM hrm_authorisation_approved_temp WHERE UserID = SUserID;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET D1 = 1;
			OPEN C1;
					L1: LOOP FETCH C1 INTO SProID, SProName, SAuthID, SAuthGID;
							IF D1 = 1 THEN LEAVE L1; END IF;
							CALL spHRMGetCheckAuthorisationTranApproved(SUserID, SProID, SProName, SAuthID, SAuthGID);
					END LOOP L1;
			CLOSE C1;
	END;

	DELETE FROM hrm_authorisation_approved_temp WHERE UserID = SUserID;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckAuthorisationTemp_Dayoff`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckAuthorisationTemp_Dayoff`(IN SUserID varchar(255), IN AuthID varchar(255), IN AuthType varchar(255))
    DETERMINISTIC
BEGIN

	-- Dayoff
	DELETE FROM hrm_authorisation_temp WHERE Auth_TranID  IN(SELECT dayoff_id FROM hrm_timesheet_dayoff WHERE LOWER(dayoff_status) NOT IN('approved', 'rejected') AND dayoff_authid = AuthID);
	INSERT INTO hrm_authorisation_temp(Auth_TranID,Auth_ID,Auth_Name,Auth_Type,Auth_AndOr,Auth_Amount) (SELECT dayoff_id,Auth_ID,Auth_Name,Auth_Type,Auth_AndOr,Auth_Amount FROM hrm_authorisation INNER JOIN hrm_timesheet_dayoff ON(LOWER(dayoff_status) NOT IN('approved', 'rejected') AND dayoff_authid = AuthID) WHERE Auth_ID = AuthID);

	DELETE FROM hrm_authorisation_detail_temp WHERE Auth_TranID IN(SELECT dayoff_id FROM hrm_timesheet_dayoff WHERE LOWER(dayoff_status) NOT IN('approved', 'rejected') AND dayoff_authid = AuthID);
	INSERT INTO hrm_authorisation_detail_temp(Auth_TranID,Auth_ID,Auth_EmpID,Auth_GroupID,Auth_GroupAndOr,Auth_GroupAmount) (SELECT dayoff_id,Auth_ID,Auth_EmpID,Auth_GroupID,Auth_GroupAndOr,Auth_GroupAmount FROM hrm_authorisation_detail INNER JOIN hrm_timesheet_dayoff ON(LOWER(dayoff_status) NOT IN('approved', 'rejected') AND dayoff_authid = AuthID) WHERE Auth_ID = AuthID);

	DELETE FROM hrm_authorisation_group_temp WHERE Auth_TranID IN(SELECT dayoff_id FROM hrm_timesheet_dayoff WHERE LOWER(dayoff_status) NOT IN('approved', 'rejected') AND dayoff_authid = AuthID);
	INSERT INTO hrm_authorisation_group_temp(Auth_TranID,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description) (SELECT dayoff_id,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description FROM hrm_authorisation_group INNER JOIN hrm_timesheet_dayoff ON(LOWER(dayoff_status) NOT IN('approved', 'rejected') AND dayoff_authid = AuthID) WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));

	DELETE FROM hrm_authorisation_group_detail_temp WHERE Auth_TranID IN(SELECT dayoff_id FROM hrm_timesheet_dayoff WHERE LOWER(dayoff_status) NOT IN('approved', 'rejected') AND dayoff_authid = AuthID);
	INSERT INTO hrm_authorisation_group_detail_temp(Auth_TranID,AuthGroup_ID,AuthGroup_EmpID) (SELECT dayoff_id,AuthGroup_ID,AuthGroup_EmpID FROM hrm_authorisation_group_detail INNER JOIN hrm_timesheet_dayoff ON(LOWER(dayoff_status) NOT IN('approved', 'rejected') AND dayoff_authid = AuthID) WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));

	IF LOWER(AuthType) = 'individual' THEN
		CALL spHRMAddIAuthorisationApprovedTemp(SUserID, AuthID, 'Dayoff');
	ELSE
		CALL spHRMAddGAuthorisationApprovedTemp(SUserID, AuthID, 'Dayoff');
	END IF;

	DELETE FROM hrm_authorisation_approved WHERE Auth_ProcessID IN(SELECT dayoff_id FROM hrm_timesheet_dayoff WHERE LOWER(dayoff_status) NOT IN('approved', 'rejected') AND dayoff_authid = AuthID);
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckAuthorisationTemp_Deduction`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckAuthorisationTemp_Deduction`(IN SUserID varchar(255), IN AuthID varchar(255), IN AuthType varchar(255))
    DETERMINISTIC
BEGIN

	-- Deduction
	DELETE FROM hrm_authorisation_temp WHERE Auth_TranID  IN(SELECT deduction_id FROM hrm_payroll_deduction WHERE LOWER(deduction_status) NOT IN('approved', 'rejected') AND deduction_authid = AuthID);
	INSERT INTO hrm_authorisation_temp(Auth_TranID,Auth_ID,Auth_Name,Auth_Type,Auth_AndOr,Auth_Amount) (SELECT deduction_id,Auth_ID,Auth_Name,Auth_Type,Auth_AndOr,Auth_Amount FROM hrm_authorisation INNER JOIN hrm_payroll_deduction ON(LOWER(deduction_status) NOT IN('approved', 'rejected') AND deduction_authid = AuthID) WHERE Auth_ID = AuthID);

	DELETE FROM hrm_authorisation_detail_temp WHERE Auth_TranID IN(SELECT deduction_id FROM hrm_payroll_deduction WHERE LOWER(deduction_status) NOT IN('approved', 'rejected') AND deduction_authid = AuthID);
	INSERT INTO hrm_authorisation_detail_temp(Auth_TranID,Auth_ID,Auth_EmpID,Auth_GroupID,Auth_GroupAndOr,Auth_GroupAmount) (SELECT deduction_id,Auth_ID,Auth_EmpID,Auth_GroupID,Auth_GroupAndOr,Auth_GroupAmount FROM hrm_authorisation_detail INNER JOIN hrm_payroll_deduction ON(LOWER(deduction_status) NOT IN('approved', 'rejected') AND deduction_authid = AuthID) WHERE Auth_ID = AuthID);

	DELETE FROM hrm_authorisation_group_temp WHERE Auth_TranID IN(SELECT deduction_id FROM hrm_payroll_deduction WHERE LOWER(deduction_status) NOT IN('approved', 'rejected') AND deduction_authid = AuthID);
	INSERT INTO hrm_authorisation_group_temp(Auth_TranID,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description) (SELECT deduction_id,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description FROM hrm_authorisation_group INNER JOIN hrm_payroll_deduction ON(LOWER(deduction_status) NOT IN('approved', 'rejected') AND deduction_authid = AuthID) WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));

	DELETE FROM hrm_authorisation_group_detail_temp WHERE Auth_TranID IN(SELECT deduction_id FROM hrm_payroll_deduction WHERE LOWER(deduction_status) NOT IN('approved', 'rejected') AND deduction_authid = AuthID);
	INSERT INTO hrm_authorisation_group_detail_temp(Auth_TranID,AuthGroup_ID,AuthGroup_EmpID) (SELECT deduction_id,AuthGroup_ID,AuthGroup_EmpID FROM hrm_authorisation_group_detail INNER JOIN hrm_payroll_deduction ON(LOWER(deduction_status) NOT IN('approved', 'rejected') AND deduction_authid = AuthID) WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));

	IF LOWER(AuthType) = 'individual' THEN
		CALL spHRMAddIAuthorisationApprovedTemp(SUserID, AuthID, 'Deduction');
	ELSE
		CALL spHRMAddGAuthorisationApprovedTemp(SUserID, AuthID, 'Deduction');
	END IF;

	DELETE FROM hrm_authorisation_approved WHERE Auth_ProcessID IN(SELECT deduction_id FROM hrm_payroll_deduction WHERE LOWER(deduction_status) NOT IN('approved', 'rejected') AND deduction_authid = AuthID);
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckAuthorisationTemp_Leave`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckAuthorisationTemp_Leave`(IN SUserID varchar(255), IN AuthID varchar(255), IN AuthType varchar(255))
    DETERMINISTIC
BEGIN

	-- Leave
	DELETE FROM hrm_authorisation_temp WHERE Auth_TranID  IN(SELECT leave_id FROM hrm_timesheet_leave WHERE LOWER(leave_status) NOT IN('approved', 'rejected') AND leave_authid = AuthID);
	INSERT INTO hrm_authorisation_temp(Auth_TranID,Auth_ID,Auth_Name,Auth_Type,Auth_AndOr,Auth_Amount) (SELECT leave_id,Auth_ID,Auth_Name,Auth_Type,Auth_AndOr,Auth_Amount FROM hrm_authorisation INNER JOIN hrm_timesheet_leave ON(LOWER(leave_status) NOT IN('approved', 'rejected') AND leave_authid = AuthID) WHERE Auth_ID = AuthID);

	DELETE FROM hrm_authorisation_detail_temp WHERE Auth_TranID IN(SELECT leave_id FROM hrm_timesheet_leave WHERE LOWER(leave_status) NOT IN('approved', 'rejected') AND leave_authid = AuthID);
	INSERT INTO hrm_authorisation_detail_temp(Auth_TranID,Auth_ID,Auth_EmpID,Auth_GroupID,Auth_GroupAndOr,Auth_GroupAmount) (SELECT leave_id,Auth_ID,Auth_EmpID,Auth_GroupID,Auth_GroupAndOr,Auth_GroupAmount FROM hrm_authorisation_detail INNER JOIN hrm_timesheet_leave ON(LOWER(leave_status) NOT IN('approved', 'rejected') AND leave_authid = AuthID) WHERE Auth_ID = AuthID);

	DELETE FROM hrm_authorisation_group_temp WHERE Auth_TranID IN(SELECT leave_id FROM hrm_timesheet_leave WHERE LOWER(leave_status) NOT IN('approved', 'rejected') AND leave_authid = AuthID);
	INSERT INTO hrm_authorisation_group_temp(Auth_TranID,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description) (SELECT leave_id,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description FROM hrm_authorisation_group INNER JOIN hrm_timesheet_leave ON(LOWER(leave_status) NOT IN('approved', 'rejected') AND leave_authid = AuthID) WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));

	DELETE FROM hrm_authorisation_group_detail_temp WHERE Auth_TranID IN(SELECT leave_id FROM hrm_timesheet_leave WHERE LOWER(leave_status) NOT IN('approved', 'rejected') AND leave_authid = AuthID);
	INSERT INTO hrm_authorisation_group_detail_temp(Auth_TranID,AuthGroup_ID,AuthGroup_EmpID) (SELECT leave_id,AuthGroup_ID,AuthGroup_EmpID FROM hrm_authorisation_group_detail INNER JOIN hrm_timesheet_leave ON(LOWER(leave_status) NOT IN('approved', 'rejected') AND leave_authid = AuthID) WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));

	IF LOWER(AuthType) = 'individual' THEN
		CALL spHRMAddIAuthorisationApprovedTemp(SUserID, AuthID, 'Leave');
	ELSE
		CALL spHRMAddGAuthorisationApprovedTemp(SUserID, AuthID, 'Leave');
	END IF;

	DELETE FROM hrm_authorisation_approved WHERE Auth_ProcessID IN(SELECT leave_id FROM hrm_timesheet_leave WHERE LOWER(leave_status) NOT IN('approved', 'rejected') AND leave_authid = AuthID);
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckAuthorisationTemp_Overtime`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckAuthorisationTemp_Overtime`(IN SUserID varchar(255), IN AuthID varchar(255), IN AuthType varchar(255))
    DETERMINISTIC
BEGIN

	-- Overtime
	DELETE FROM hrm_authorisation_temp WHERE Auth_TranID  IN(SELECT overtime_id FROM hrm_payroll_overtime WHERE LOWER(overtime_status) NOT IN('approved', 'rejected') AND overtime_authid = AuthID);
	INSERT INTO hrm_authorisation_temp(Auth_TranID,Auth_ID,Auth_Name,Auth_Type,Auth_AndOr,Auth_Amount) (SELECT overtime_id,Auth_ID,Auth_Name,Auth_Type,Auth_AndOr,Auth_Amount FROM hrm_authorisation INNER JOIN hrm_payroll_overtime ON(LOWER(overtime_status) NOT IN('approved', 'rejected') AND overtime_authid = AuthID) WHERE Auth_ID = AuthID);

	DELETE FROM hrm_authorisation_detail_temp WHERE Auth_TranID IN(SELECT overtime_id FROM hrm_payroll_overtime WHERE LOWER(overtime_status) NOT IN('approved', 'rejected') AND overtime_authid = AuthID);
	INSERT INTO hrm_authorisation_detail_temp(Auth_TranID,Auth_ID,Auth_EmpID,Auth_GroupID,Auth_GroupAndOr,Auth_GroupAmount) (SELECT overtime_id,Auth_ID,Auth_EmpID,Auth_GroupID,Auth_GroupAndOr,Auth_GroupAmount FROM hrm_authorisation_detail INNER JOIN hrm_payroll_overtime ON(LOWER(overtime_status) NOT IN('approved', 'rejected') AND overtime_authid = AuthID) WHERE Auth_ID = AuthID);

	DELETE FROM hrm_authorisation_group_temp WHERE Auth_TranID IN(SELECT overtime_id FROM hrm_payroll_overtime WHERE LOWER(overtime_status) NOT IN('approved', 'rejected') AND overtime_authid = AuthID);
	INSERT INTO hrm_authorisation_group_temp(Auth_TranID,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description) (SELECT overtime_id,AuthGroup_ID,AuthGroup_Name,AuthGroup_Description FROM hrm_authorisation_group INNER JOIN hrm_payroll_overtime ON(LOWER(overtime_status) NOT IN('approved', 'rejected') AND overtime_authid = AuthID) WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));

	DELETE FROM hrm_authorisation_group_detail_temp WHERE Auth_TranID IN(SELECT overtime_id FROM hrm_payroll_overtime WHERE LOWER(overtime_status) NOT IN('approved', 'rejected') AND overtime_authid = AuthID);
	INSERT INTO hrm_authorisation_group_detail_temp(Auth_TranID,AuthGroup_ID,AuthGroup_EmpID) (SELECT overtime_id,AuthGroup_ID,AuthGroup_EmpID FROM hrm_authorisation_group_detail INNER JOIN hrm_payroll_overtime ON(LOWER(overtime_status) NOT IN('approved', 'rejected') AND overtime_authid = AuthID) WHERE AuthGroup_ID IN(SELECT Auth_GroupID FROM hrm_authorisation_detail WHERE Auth_ID = AuthID));

	IF LOWER(AuthType) = 'individual' THEN
		CALL spHRMAddIAuthorisationApprovedTemp(SUserID, AuthID, 'Overtime');
	ELSE
		CALL spHRMAddGAuthorisationApprovedTemp(SUserID, AuthID, 'Overtime');
	END IF;

	DELETE FROM hrm_authorisation_approved WHERE Auth_ProcessID IN(SELECT overtime_id FROM hrm_payroll_overtime WHERE LOWER(overtime_status) NOT IN('approved', 'rejected') AND overtime_authid = AuthID);
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckAutoFPNormal`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckAutoFPNormal`(SShiftID varchar(255), SNow DATETIME, In1 INT, Out1 INT, In2 INT, Out2 INT, In3 INT, Out3 INT,In4 INT, Out4 INT, In5 INT, Out5 INT)
    DETERMINISTIC
BEGIN
	DECLARE SEmpID VARCHAR(255) DEFAULT('');
	DECLARE SFPID VARCHAR(255) DEFAULT('');
	DECLARE ShiftTimeIn1 TIME DEFAULT('00:00:00');
	DECLARE ShiftTimeOut1 TIME DEFAULT('00:00:00');
	DECLARE ShiftTimeIn2 TIME DEFAULT('00:00:00');
	DECLARE ShiftTimeOut2 TIME DEFAULT('00:00:00');
	DECLARE ShiftTimeIn3 TIME DEFAULT('00:00:00');
	DECLARE ShiftTimeOut3 TIME DEFAULT('00:00:00');
	DECLARE ShiftTimeIn4 TIME DEFAULT('00:00:00');
	DECLARE ShiftTimeOut4 TIME DEFAULT('00:00:00');
	DECLARE ShiftTimeIn5 TIME DEFAULT('00:00:00');
	DECLARE ShiftTimeOut5 TIME DEFAULT('00:00:00');

	DECLARE TimeIn1 TIME DEFAULT('00:00:00');
	DECLARE TimeOut1 TIME DEFAULT('00:00:00');
	DECLARE TimeIn2 TIME DEFAULT('00:00:00');
	DECLARE TimeOut2 TIME DEFAULT('00:00:00');
	DECLARE TimeIn3 TIME DEFAULT('00:00:00');
	DECLARE TimeOut3 TIME DEFAULT('00:00:00');
	DECLARE TimeIn4 TIME DEFAULT('00:00:00');
	DECLARE TimeOut4 TIME DEFAULT('00:00:00');
	DECLARE TimeIn5 TIME DEFAULT('00:00:00');
	DECLARE TimeOut5 TIME DEFAULT('00:00:00');
	
	DECLARE done INT DEFAULT FALSE;
  DECLARE cursor_i CURSOR FOR SELECT EmpID,Emp_FPID FROM tblemployee e WHERE e.Emp_ShiftID=SShiftID;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	SELECT Shift_TimeIn1,Shift_TimeOut1,Shift_TimeIn2,Shift_TimeOut2,Shift_TimeIn3,Shift_TimeOut3,Shift_TimeIn4,Shift_TimeOut4,Shift_TimeIn5,Shift_TimeOut5 INTO
	ShiftTimeIn1,ShiftTimeOut1,ShiftTimeIn2,ShiftTimeOut2,ShiftTimeIn3,ShiftTimeOut3,ShiftTimeIn4,ShiftTimeOut4,ShiftTimeIn5,ShiftTimeOut5
	FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID=SShiftID AND wd.Shift_Day=DAYNAME(SNow) LIMIT 1;

  OPEN cursor_i;
  read_loop: LOOP
    FETCH cursor_i INTO SEmpID, SFPID;
		IF done THEN
      LEAVE read_loop;
    END IF;

		SET @SQL1 = '';		
		BEGIN
			DECLARE C1 CURSOR FOR SELECT SQL_CALC_FOUND_ROWS Att_In1, Att_Out1, Att_In2, Att_Out2, Att_In3, Att_Out3, Att_In4, Att_Out4, Att_In5, Att_Out5 FROM hrm_timesheet_attendance WHERE Att_EmpID = SEmpID AND Att_FPID= SFPID AND Att_Date = DATE_FORMAT(SNow, "%Y-%m-%d") LIMIT 1;
			OPEN C1;
				 IF FOUND_ROWS() > 0 THEN	FETCH C1 INTO TimeIn1, TimeOut1, TimeIn2, TimeOut2, TimeIn3, TimeOut3, TimeIn4, TimeOut4, TimeIn5, TimeOut5; END IF;
			CLOSE C1;
		END;

		SET @SQL1 = "";
    IF In1 =1 AND ShiftTimeIn1 = DATE_FORMAT(SNow, "%H:%i:00") AND TimeIn1 = '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_In1='", ShiftTimeIn1 ,"',");
		END IF;
		IF Out1 =1 AND ShiftTimeOut1 = DATE_FORMAT(SNow, "%H:%i:00") AND TimeOut1 = '00:00:00' AND TimeIn1 <> '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_Out1='", ShiftTimeOut1 ,"',");
		END IF;
		IF In2 =1 AND ShiftTimeIn2 = DATE_FORMAT(SNow, "%H:%i:00") AND TimeIn2 = '00:00:00' AND TimeOut1 <> '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_In2='", ShiftTimeIn2 ,"',");
		END IF;
		IF Out2 =1 AND ShiftTimeOut2 = DATE_FORMAT(SNow, "%H:%i:00") AND TimeOut2 = '00:00:00' AND TimeIn2 <> '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_Out2='", ShiftTimeOut2 ,"',");
		END IF;
		IF In3 =1 AND ShiftTimeIn3 = DATE_FORMAT(SNow, "%H:%i:00") AND TimeIn3 = '00:00:00'  AND TimeOut2 <> '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_In3='", ShiftTimeIn3 ,"',");
		END IF;
		IF Out3 =1 AND ShiftTimeOut3 = DATE_FORMAT(SNow, "%H:%i:00") AND TimeOut3 = '00:00:00' AND TimeIn3 <> '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_Out3='", ShiftTimeOut3 ,"',");
		END IF;
		IF In4 =1 AND ShiftTimeIn4 = DATE_FORMAT(SNow, "%H:%i:00") AND TimeIn4 = '00:00:00' AND TimeOut3 <> '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_In4='", ShiftTimeIn4 ,"',");
		END IF;
		IF Out4 =1 AND ShiftTimeOut4 = DATE_FORMAT(SNow, "%H:%i:00") AND TimeOut4 = '00:00:00' AND TimeIn4 <> '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_Out4='", ShiftTimeOut4 ,"',");
		END IF;
		IF In5 =1 AND ShiftTimeIn5 = DATE_FORMAT(SNow, "%H:%i:00")  AND TimeIn5 = '00:00:00' AND TimeOut4 <> '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_In5='", ShiftTimeIn5 ,"',");
		END IF;
		IF Out5 =1 AND ShiftTimeOut5 = DATE_FORMAT(SNow, "%H:%i:00") AND TimeOut5 = '00:00:00' AND TimeIn5 <> '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_Out5='", ShiftTimeOut5 ,"',");
		END IF;

		IF @SQL1 != "" THEN
			SET @SQL1 = SUBSTRING(@SQL1, 1, CHAR_LENGTH(@SQL1) - 1);

			SET @SQL1 = CONCAT("UPDATE hrm_timesheet_attendance SET ",@SQL1," WHERE Att_EmpID='", SEmpID,"' AND Att_FPID='", SFPID,"' AND Att_Date='", DATE_FORMAT(SNow, "%Y-%m-%d"),"';");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			CALL spHRMCheckAttendanceNormal(SEmpID, SShiftID, SFPID, DATE_FORMAT(SNow, "%Y-%m-%d"));
		END IF;
	
  END LOOP;
  CLOSE cursor_i;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckAutoFPRoster`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckAutoFPRoster`(SShiftID varchar(255), SNow DATETIME, In1 INT, Out1 INT, In2 INT, Out2 INT, In3 INT, Out3 INT,In4 INT, Out4 INT, In5 INT, Out5 INT)
    DETERMINISTIC
BEGIN
	DECLARE SEmpID VARCHAR(255) DEFAULT('');
	DECLARE SFPID VARCHAR(255) DEFAULT('');
	DECLARE ShiftTimeIn1 TIME DEFAULT('00:00:00');
	DECLARE ShiftTimeOut1 TIME DEFAULT('00:00:00');
	DECLARE ShiftTimeIn2 TIME DEFAULT('00:00:00');
	DECLARE ShiftTimeOut2 TIME DEFAULT('00:00:00');
	DECLARE ShiftTimeIn3 TIME DEFAULT('00:00:00');
	DECLARE ShiftTimeOut3 TIME DEFAULT('00:00:00');
	DECLARE ShiftTimeIn4 TIME DEFAULT('00:00:00');
	DECLARE ShiftTimeOut4 TIME DEFAULT('00:00:00');
	DECLARE ShiftTimeIn5 TIME DEFAULT('00:00:00');
	DECLARE ShiftTimeOut5 TIME DEFAULT('00:00:00');

	DECLARE TimeIn1 TIME DEFAULT('00:00:00');
	DECLARE TimeOut1 TIME DEFAULT('00:00:00');
	DECLARE TimeIn2 TIME DEFAULT('00:00:00');
	DECLARE TimeOut2 TIME DEFAULT('00:00:00');
	DECLARE TimeIn3 TIME DEFAULT('00:00:00');
	DECLARE TimeOut3 TIME DEFAULT('00:00:00');
	DECLARE TimeIn4 TIME DEFAULT('00:00:00');
	DECLARE TimeOut4 TIME DEFAULT('00:00:00');
	DECLARE TimeIn5 TIME DEFAULT('00:00:00');
	DECLARE TimeOut5 TIME DEFAULT('00:00:00');

	DECLARE done INT DEFAULT FALSE;
  DECLARE cursor_i CURSOR FOR SELECT Roster_EmpID,Emp_FPID FROM hrm_timesheet_roster r INNER JOIN tblemployee e ON(r.Roster_EmpID=e.EmpID) WHERE r.Roster_ShiftID=SShiftID AND r.Roster_Date = DATE_FORMAT(SNow, "%Y-%m-%d");
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	SELECT Shift_TimeIn1,Shift_TimeOut1,Shift_TimeIn2,Shift_TimeOut2,Shift_TimeIn3,Shift_TimeOut3,Shift_TimeIn4,Shift_TimeOut4,Shift_TimeIn5,Shift_TimeOut5 INTO
	ShiftTimeIn1,ShiftTimeOut1,ShiftTimeIn2,ShiftTimeOut2,ShiftTimeIn3,ShiftTimeOut3,ShiftTimeIn4,ShiftTimeOut4,ShiftTimeIn5,ShiftTimeOut5
	FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID=SShiftID LIMIT 1;

  OPEN cursor_i;
  read_loop: LOOP
    FETCH cursor_i INTO SEmpID, SFPID;
		IF done THEN
      LEAVE read_loop;
    END IF;

		SET @SQL1 = '';		
		BEGIN
			DECLARE C1 CURSOR FOR SELECT SQL_CALC_FOUND_ROWS Att_In1, Att_Out1, Att_In2, Att_Out2, Att_In3, Att_Out3, Att_In4, Att_Out4, Att_In5, Att_Out5 FROM hrm_timesheet_attendance WHERE Att_EmpID = SEmpID AND Att_FPID= SFPID AND Att_Date = DATE_FORMAT(SNow, "%Y-%m-%d") LIMIT 1;
			OPEN C1;
				 IF FOUND_ROWS() > 0 THEN	FETCH C1 INTO TimeIn1, TimeOut1, TimeIn2, TimeOut2, TimeIn3, TimeOut3, TimeIn4, TimeOut4, TimeIn5, TimeOut5; END IF;
			CLOSE C1;
		END;

		SET @SQL1 = "";
    IF In1 =1 AND ShiftTimeIn1 = DATE_FORMAT(SNow, "%H:%i:00") AND TimeIn1 = '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_In1='", ShiftTimeIn1 ,"',");
		END IF;
		IF Out1 =1 AND ShiftTimeOut1 = DATE_FORMAT(SNow, "%H:%i:00") AND TimeOut1 = '00:00:00' AND TimeIn1 <> '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_Out1='", ShiftTimeOut1 ,"',");
		END IF;
		IF In2 =1 AND ShiftTimeIn2 = DATE_FORMAT(SNow, "%H:%i:00") AND TimeIn2 = '00:00:00' AND TimeOut1 <> '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_In2='", ShiftTimeIn2 ,"',");
		END IF;
		IF Out2 =1 AND ShiftTimeOut2 = DATE_FORMAT(SNow, "%H:%i:00") AND TimeOut2 = '00:00:00' AND TimeIn2 <> '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_Out2='", ShiftTimeOut2 ,"',");
		END IF;
		IF In3 =1 AND ShiftTimeIn3 = DATE_FORMAT(SNow, "%H:%i:00") AND TimeIn3 = '00:00:00'  AND TimeOut2 <> '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_In3='", ShiftTimeIn3 ,"',");
		END IF;
		IF Out3 =1 AND ShiftTimeOut3 = DATE_FORMAT(SNow, "%H:%i:00") AND TimeOut3 = '00:00:00' AND TimeIn3 <> '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_Out3='", ShiftTimeOut3 ,"',");
		END IF;
		IF In4 =1 AND ShiftTimeIn4 = DATE_FORMAT(SNow, "%H:%i:00") AND TimeIn4 = '00:00:00' AND TimeOut3 <> '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_In4='", ShiftTimeIn4 ,"',");
		END IF;
		IF Out4 =1 AND ShiftTimeOut4 = DATE_FORMAT(SNow, "%H:%i:00") AND TimeOut4 = '00:00:00' AND TimeIn4 <> '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_Out4='", ShiftTimeOut4 ,"',");
		END IF;
		IF In5 =1 AND ShiftTimeIn5 = DATE_FORMAT(SNow, "%H:%i:00")  AND TimeIn5 = '00:00:00' AND TimeOut4 <> '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_In5='", ShiftTimeIn5 ,"',");
		END IF;
		IF Out5 =1 AND ShiftTimeOut5 = DATE_FORMAT(SNow, "%H:%i:00") AND TimeOut5 = '00:00:00' AND TimeIn5 <> '00:00:00' THEN
			SET @SQL1 = CONCAT(@SQL1,"Att_Out5='", ShiftTimeOut5 ,"',");
		END IF;

		IF @SQL1 != "" THEN
			SET @SQL1 = SUBSTRING(@SQL1, 1, CHAR_LENGTH(@SQL1) - 1);

			SET @SQL1 = CONCAT("UPDATE hrm_timesheet_attendance SET ",@SQL1," WHERE Att_EmpID='", SEmpID,"' AND Att_FPID='", SFPID,"' AND Att_Date='", DATE_FORMAT(SNow, "%Y-%m-%d"),"';");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			CALL spHRMCheckAttendanceRoster(SEmpID, SShiftID, SFPID, DATE_FORMAT(SNow, "%Y-%m-%d"));
		END IF;

  END LOOP;
  CLOSE cursor_i;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckDateSalary`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckDateSalary`(IN PayrollType varchar(255), IN StartDate Date, IN TargetDate Date, OUT ResultDate Date)
    DETERMINISTIC
BEGIN
	DECLARE StartD DATE;
	DECLARE TargetD DATE;
	DECLARE ResultD DATE;
	DECLARE i INT DEFAULT 1;
	DECLARE n INT DEFAULT 0;
	DECLARE SNow DATE;
	DECLARE tz VARCHAR(20) DEFAULT('');

	SET StartD = StartDate;
	SET TargetD = TargetDate;
	SET ResultD = StartDate;

	SELECT Setting_Value INTO tz FROM hrm_setting WHERE Setting_Type = 'TimeZone' AND Setting_Name = 'TimeZone';
	SET SNow = convert_tz(now(), @@session.time_zone, tz);

	IF PayrollType = "Monthly" THEN
		IF MONTH(TargetD) <> MONTH(ResultD) OR YEAR(TargetD) <> YEAR(ResultD) THEN
			WHILE (MONTH(TargetD) <> MONTH(ResultD) OR YEAR(TargetD) <> YEAR(ResultD))
			DO 
				SET ResultD  = DATE_ADD(StartD, INTERVAL i MONTH);
				SET i = i + 1;
			END WHILE;
		ELSE
			WHILE (ResultD < SNow)
			DO 
				SET ResultD  = DATE_ADD(StartD, INTERVAL i MONTH);
				SET i = i + 1;
			END WHILE;
		END IF;
			
	ELSEIF PayrollType = "Biweekly" THEN
		SET n = 14;
		IF MONTH(TargetD) <> MONTH(ResultD) OR YEAR(TargetD) <> YEAR(ResultD) THEN
			WHILE (MONTH(TargetD) <> MONTH(ResultD) OR YEAR(TargetD) <> YEAR(ResultD))
			DO 
				SET ResultD  = DATE_ADD(StartD, INTERVAL n*i DAY);
				SET i = i + 1;
			END WHILE;
		ELSE
			WHILE (ResultD < SNow)
			DO 
				SET ResultD  = DATE_ADD(StartD, INTERVAL n*i DAY);
				SET i = i + 1;
			END WHILE;
		END IF;
				
	ELSEIF PayrollType = "Weekly" THEN
		SET n = 7;
		IF MONTH(TargetD) <> MONTH(ResultD) OR YEAR(TargetD) <> YEAR(ResultD) THEN
			WHILE (MONTH(TargetD) <> MONTH(ResultD) OR YEAR(TargetD) <> YEAR(ResultD))
			DO 
				SET ResultD  = DATE_ADD(StartD, INTERVAL n*i DAY);
				SET i = i + 1;
			END WHILE;
		ELSE	
			WHILE (ResultD < SNow)
			DO 
				SET ResultD  = DATE_ADD(StartD, INTERVAL n*i DAY);
				SET i = i + 1;
			END WHILE;
		END IF;
		
	ELSEIF PayrollType = "Daily" THEN
		SET ResultD  = CONCAT(YEAR(TargetD),"-", MONTH(TargetD), "-", DAY(StartD));
		WHILE (ResultD < SNow)
		DO 
			SET ResultD  = DATE_ADD(ResultD, INTERVAL 1 DAY);
		END WHILE;
	END IF;
	
	SET ResultDate = ResultD;

	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckDeleteAttendanceLeave`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckDeleteAttendanceLeave`(SID varchar(255), SEmpID varchar(255))
    DETERMINISTIC
BEGIN
		DECLARE v_finished INTEGER DEFAULT 0;
		DECLARE SDuration varchar(255) DEFAULT("");
		DECLARE SDate DATE;
		DECLARE SFrom TIME;
		DECLARE STo TIME;
		DECLARE TempA VARCHAR(255);
		DECLARE TempB VARCHAR(255);

		DEClARE CustID_Cursor CURSOR FOR SELECT LeaveD_Duration,LeaveD_Date,LeaveD_TimeFrom,LeaveD_TimeTo FROM hrm_timesheet_leave_detail WHERE LeaveD_ID  = SID;
		DECLARE CONTINUE HANDLER
		FOR NOT FOUND SET v_finished = 1;
		OPEN CustID_Cursor;
			GetCustID: LOOP
				FETCH CustID_Cursor INTO SDuration,SDate,SFrom,STo;
				IF v_finished = 1 THEN
					LEAVE GetCustID;
				END IF;

				IF LOWER(SDuration) = 'full day' THEN
					Set TempA = CONCAT(SDate, ' 00:00:00');
					Set TempB = CONCAT(SDate, ' 00:00:00');
					CALL spHRMAttendanceLeaveDeleteFullDay(SEmpID, TempA, TempB);
				ELSE
					Set TempA = CONCAT(SDate, ' ', SFrom);
					Set TempB = CONCAT(SDate, ' ', STo);
					CALL spHRMAttendanceLeaveDeleteHourly(SEmpID, TempA, TempB);
				END IF;

			END LOOP GetCustID;
		CLOSE CustID_Cursor;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckDeleteSync`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckDeleteSync`(IN GTblName text, IN GF1 text, IN GV1 Text, IN GF2 text, IN GV2 Text, IN GF3 text, IN GV3 Text)
    DETERMINISTIC
BEGIN
	SET @i = 0;
	SET @u = 0;
	SET @d = 0;
	IF GF3 is NOT NULL AND GV3 IS NOT NULL THEN
		SELECT COUNT(*) INTO @i FROM hrm_synchronize s WHERE s.tblName = GTblName AND s.F1 = GF1 AND s.V1 = GV1 AND s.F2 = GF2 AND s.V2 = GV2 AND s.F3 = GF3 AND s.V3 = GV3 AND s.Action_Status = 'insert' AND s.IsSynced = 0;
		SELECT COUNT(*) INTO @u FROM hrm_synchronize s WHERE s.tblName = GTblName AND s.F1 = GF1 AND s.V1 = GV1 AND s.F2 = GF2 AND s.V2 = GV2 AND s.F3 = GF3 AND s.V3 = GV3 AND s.Action_Status = 'update' AND s.IsSynced = 0;
		SELECT COUNT(*) INTO @d FROM hrm_synchronize s WHERE s.tblName = GTblName AND s.F1 = GF1 AND s.V1 = GV1 AND s.F2 = GF2 AND s.V2 = GV2 AND s.F3 = GF3 AND s.V3 = GV3 AND s.Action_Status = 'delete' AND s.IsSynced = 0;
		IF @i > 0 OR @u > 0 OR @d > 0 THEN
			DELETE FROM hrm_synchronize WHERE tblName = GTblName AND F1 = GF1 AND V1 = GV1 AND F2 = GF2 AND V2 = GV2 AND F3 = GF3 AND V3 = GV3 AND IsSynced = 0;
		END IF;
	ELSEIF GF2 is NOT NULL AND GV2 IS NOT NULL THEN
		SELECT COUNT(*) INTO @i FROM hrm_synchronize s WHERE s.tblName = GTblName AND s.F1 = GF1 AND s.V1 = GV1 AND s.F2 = GF2 AND s.V2 = GV2 AND s.Action_Status = 'insert' AND s.IsSynced = 0;
		SELECT COUNT(*) INTO @u FROM hrm_synchronize s WHERE s.tblName = GTblName AND s.F1 = GF1 AND s.V1 = GV1 AND s.F2 = GF2 AND s.V2 = GV2 AND s.Action_Status = 'update' AND s.IsSynced = 0;
		SELECT COUNT(*) INTO @d FROM hrm_synchronize s WHERE s.tblName = GTblName AND s.F1 = GF1 AND s.V1 = GV1 AND s.F2 = GF2 AND s.V2 = GV2 AND s.Action_Status = 'delete' AND s.IsSynced = 0;
		IF @i > 0 OR @u > 0 OR @d > 0 THEN
			DELETE FROM hrm_synchronize WHERE tblName = GTblName AND F1 = GF1 AND V1 = GV1 AND F2 = GF2 AND V2 = GV2 AND IsSynced = 0;
		END IF;
	ELSE
		SELECT COUNT(*) INTO @i FROM hrm_synchronize s WHERE s.tblName = GTblName AND s.F1 = GF1 AND s.V1 = GV1 AND s.Action_Status = 'insert' AND s.IsSynced = 0;
		SELECT COUNT(*) INTO @u FROM hrm_synchronize s WHERE s.tblName = GTblName AND s.F1 = GF1 AND s.V1 = GV1 AND s.Action_Status = 'update' AND s.IsSynced = 0;
		SELECT COUNT(*) INTO @d FROM hrm_synchronize s WHERE s.tblName = GTblName AND s.F1 = GF1 AND s.V1 = GV1 AND s.Action_Status = 'delete' AND s.IsSynced = 0;
		IF @i > 0 OR @u > 0 OR @d > 0 THEN
			DELETE FROM hrm_synchronize WHERE tblName = GTblName AND F1 = GF1 AND V1 = GV1 AND IsSynced = 0;
		END IF;
	END IF;
	IF GF3 is NOT NULL AND GV3 IS NOT NULL THEN
			INSERT INTO hrm_synchronize(tblname,F1,V1,Action_Status,IsSynced,Action_Date,F2,V2,F3,V3) VALUES (GTblName,GF1,GV1,'delete',0,NOW(),GF2,GV2,GF3,GV3);
	ELSEIF GF2 is NOT NULL AND GV2 IS NOT NULL THEN
			INSERT INTO hrm_synchronize(tblname,F1,V1,Action_Status,IsSynced,Action_Date,F2,V2) VALUES (GTblName,GF1,GV1,'delete',0,NOW(),GF2,GV2);
	ELSE
			INSERT INTO hrm_synchronize(tblname,F1,V1,Action_Status,IsSynced,Action_Date) VALUES (GTblName,GF1,GV1,'delete',0,NOW());
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckFingerPrint`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckFingerPrint`(SValue text)
    DETERMINISTIC
BEGIN
	DECLARE Exist INT DEFAULT(0);
	DECLARE Punch1 TIME DEFAULT('00:00:00');
	DECLARE Punch2 TIME DEFAULT('00:00:00');
	DECLARE Punch3 TIME DEFAULT('00:00:00');
	DECLARE Punch4 TIME DEFAULT('00:00:00');
	DECLARE Punch5 TIME DEFAULT('00:00:00');
	DECLARE Punch6 TIME DEFAULT('00:00:00');
	DECLARE Punch7 TIME DEFAULT('00:00:00');
	DECLARE Punch8 TIME DEFAULT('00:00:00');
	DECLARE Punch9 TIME DEFAULT('00:00:00');
	DECLARE Punch10 TIME DEFAULT('00:00:00');
	DECLARE TempSql VARCHAR(255) DEFAULT('');

	WHILE (LOCATE('*', SValue) > 0)
		DO
			SET @value = LEFT(SValue, LOCATE('*',SValue) - 1);    
      SET SValue = SUBSTRING(SValue, LOCATE('*',SValue) + 1);
			IF @value != "" THEN
					SELECT COUNT(*) INTO Exist FROM hrm_timesheet_fingerprint WHERE FP_ID = fnHRMSplit(@value, '!@#$%', 1) AND FP_Date = fnHRMSplit(@value, '!@#$%', 2);
					IF Exist > 0 THEN
						SELECT FP_Punch1,FP_Punch2,FP_Punch3,FP_Punch4,FP_Punch5,FP_Punch6,FP_Punch7,FP_Punch8,FP_Punch9,FP_Punch10 INTO Punch1,Punch2,Punch3,Punch4,Punch5,Punch6,Punch7,Punch8,Punch9,Punch10 FROM hrm_timesheet_fingerprint WHERE FP_ID = fnHRMSplit(@value, '!@#$%', 1) AND FP_Date = fnHRMSplit(@value, '!@#$%', 2);
						IF punch1 = '00:00:00' THEN
							SET TempSql = CONCAT("SET FP_Punch1='", fnHRMSplit(@value, '!@#$%', 3), "'");
						ELSEIF punch2 = '00:00:00' THEN
							SET TempSql = CONCAT("SET FP_Punch2='", fnHRMSplit(@value, '!@#$%', 3), "'");
						ELSEIF punch3 = '00:00:00' THEN
							SET TempSql = CONCAT("SET FP_Punch3='", fnHRMSplit(@value, '!@#$%', 3), "'");
						ELSEIF punch4 = '00:00:00' THEN
							SET TempSql = CONCAT("SET FP_Punch4='", fnHRMSplit(@value, '!@#$%', 3), "'");
						ELSEIF punch5 = '00:00:00' THEN
							SET TempSql = CONCAT("SET FP_Punch5='", fnHRMSplit(@value, '!@#$%', 3), "'");
						ELSEIF punch6 = '00:00:00' THEN
							SET TempSql = CONCAT("SET FP_Punch6='", fnHRMSplit(@value, '!@#$%', 3), "'");
						ELSEIF punch7 = '00:00:00' THEN
							SET TempSql = CONCAT("SET FP_Punch7='", fnHRMSplit(@value, '!@#$%', 3), "'");
						ELSEIF punch8 = '00:00:00' THEN
							SET TempSql = CONCAT("SET FP_Punch8='", fnHRMSplit(@value, '!@#$%', 3), "'");
						ELSEIF punch9 = '00:00:00' THEN
							SET TempSql = CONCAT("SET FP_Punch9='", fnHRMSplit(@value, '!@#$%', 3), "'");
						ELSEIF punch10 = '00:00:00' THEN
							SET TempSql = CONCAT("SET FP_Punch10='", fnHRMSplit(@value, '!@#$%', 3), "'");
						END IF;
						IF TempSql != "" THEN
							SET @SQL1 = CONCAT("UPDATE hrm_timesheet_fingerprint ", TempSql," WHERE FP_ID = '", fnHRMSplit(@value, '!@#$%', 1), "' AND FP_Date = '", fnHRMSplit(@value, '!@#$%', 2), "';");
							PREPARE St FROM @SQL1;
							EXECUTE St;
							DEALLOCATE PREPARE St;
						END IF;
					ELSE
						SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_fingerprint(FP_ID,FP_Date,FP_Punch1) VALUES('", fnHRMSplit(@value, '!@#$%', 1), "', '", fnHRMSplit(@value, '!@#$%', 2) , "', '", fnHRMSplit(@value, '!@#$%', 3), "')");
						SELECT @SQL1;
						PREPARE St FROM @SQL1;
						EXECUTE St;
						DEALLOCATE PREPARE St;
					END IF;
			END IF;
			SET Punch1 = '00:00:00';
			SET Punch2 = '00:00:00';
			SET Punch3 = '00:00:00';
			SET Punch4 = '00:00:00';
			SET Punch5 = '00:00:00';
			SET Punch6 = '00:00:00';
			SET Punch7 = '00:00:00';
			SET Punch8 = '00:00:00';
			SET Punch9 = '00:00:00';
			SET Punch10= '00:00:00';
			SET TempSql = '';
	END WHILE;
	
	

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckGroupAuthorisationApprove`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckGroupAuthorisationApprove`(IN SProID varchar(255),IN SAuthID varchar(255),OUT SStatus varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE PStatus VARCHAR(255) DEFAULT('');
	DECLARE PAuthGroupID VARCHAR(255) DEFAULT('');
	DECLARE PAuthGroupAndOr VARCHAR(255) DEFAULT('');
	DECLARE PAuthGroupAmount VARCHAR(255) DEFAULT('');
	DECLARE done INT DEFAULT FALSE;
	DECLARE cur1 CURSOR FOR SELECT ad.Auth_GroupID,ad.Auth_GroupAndOr,ad.Auth_GroupAmount FROM hrm_authorisation_detail ad WHERE ad.Auth_ID = SAuthID; 
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	SELECT IF(COUNT(*)>0,'rejected', '') INTO PStatus FROM hrm_authorisation_approved ap WHERE ap.Auth_ProcessID = SProID AND ap.Auth_ID = SAuthID AND ap.Auth_Status = 'rejected';
	IF PStatus != 'rejected' THEN 
		OPEN cur1;
		read_loop: LOOP
    FETCH cur1 INTO PAuthGroupID,PAuthGroupAndOr,PAuthGroupAmount;
    IF done THEN
      LEAVE read_loop;
    END IF;
			SELECT IF(PAuthGroupAndOr='Or' AND COUNT(*)>0, 'approved', IF(PAuthGroupAndOr='And' AND COUNT(*)>=PAuthGroupAmount, 'approved', '')) INTO PStatus FROM hrm_authorisation_approved ap WHERE ap.Auth_ProcessID = SProID AND ap.Auth_ID = SAuthID AND ap.Auth_Status = 'approved' AND ap.Auth_GroupID = PAuthGroupID;
			IF PStatus != 'approved' THEN
				LEAVE read_loop;
			END IF;
		END LOOP;
		CLOSE cur1;
	END IF;
	SET SStatus = PStatus;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckInsertSync`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckInsertSync`(IN TblName text, IN F1 text, IN V1 Text, IN F2 text, IN V2 Text, IN F3 text, IN V3 Text)
    DETERMINISTIC
BEGIN
	SET @i = 0;
	IF F3 is NOT NULL AND V3 IS NOT NULL THEN
			SELECT COUNT(*) INTO @i FROM hrm_synchronize s WHERE s.tblName = TblName AND s.F1 = F1 AND s.V1 = V1 AND s.F2 = F2 AND s.V2 = V2 AND s.F3 = F3 AND s.V3 = V3 AND s.Action_Status = 'insert' AND s.IsSynced = 0;
			IF @i <= 0 THEN
				INSERT INTO hrm_synchronize(tblname,F1,V1,Action_Status,IsSynced,Action_Date,F2,V2,F3,V3) VALUES (TblName,F1,V1,'insert',0,NOW(),F2,V2,F3,V3);
			END IF;
	ELSEIF F2 is NOT NULL AND V2 IS NOT NULL THEN
			SELECT COUNT(*) INTO @i FROM hrm_synchronize s WHERE s.tblName = TblName AND s.F1 = F1 AND s.V1 = V1 AND s.F2 = F2 AND s.V2 = V2 AND s.Action_Status = 'insert' AND s.IsSynced = 0;
			IF @i <= 0 THEN
				INSERT INTO hrm_synchronize(tblname,F1,V1,Action_Status,IsSynced,Action_Date,F2,V2) VALUES (TblName,F1,V1,'insert',0,NOW(),F2,V2);
			END IF;
	ELSE
			SELECT COUNT(*) INTO @i FROM hrm_synchronize s WHERE s.tblName = TblName AND s.F1 = F1 AND s.V1 = V1 AND s.Action_Status = 'insert' AND s.IsSynced = 0;
			IF @i <= 0 THEN
				INSERT INTO hrm_synchronize(tblname,F1,V1,Action_Status,IsSynced,Action_Date) VALUES (TblName,F1,V1,'insert',0,NOW());
			END IF;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckLeaveBalance`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckLeaveBalance`(IN SEmpID varchar(255),IN SYear int,IN STypeID varchar(255),IN SDuration varchar(255), IN STotal varchar(255))
    DETERMINISTIC
BEGIN

	/*SELECT lt.LeaveType_AmountAllowed-SUM(l.Leave_Amount) INTO SBalance
	FROM hrm_timesheet_leave l
	INNER JOIN hrm_timesheet_leave_type lt ON lt.LeaveType_ID = l.Leave_TypeID AND lt.LeaveType_Year = SYear 
	WHERE l.Leave_EmpID = SEmpID AND l.Leave_TypeID = STypeID;*/
	DECLARE Deduct_Leave_Balance_Hourly VARCHAR(255);
	DECLARE WorkHour FLOAT DEFAULT(0);
	DECLARE Tempfullday FLOAT DEFAULT(0);
	DECLARE Temphourly FLOAT DEFAULT(0);
	DECLARE SBalance FLOAT DEFAULT(0);
	DECLARE CheckLeavePayType VARCHAR(255) DEFAULT('');
	DECLARE LeaveTypeBaseBalance VARCHAR(255) DEFAULT('');

	SELECT LeaveType_PayStatus, LeaveType_BaseBalance INTO CheckLeavePayType, LeaveTypeBaseBalance FROM hrm_timesheet_leave_type WHERE LeaveType_ID = STypeID;

	IF LOWER(CheckLeavePayType) = 'paid' THEN

		SELECT Setting_Value INTO Deduct_Leave_Balance_Hourly FROM hrm_setting WHERE Setting_Type = 'Leave' AND Setting_Name = 'Deduct_Leave_Balance_Hourly';
		
		SELECT Payroll_AmtWorkingHourPerDay INTO WorkHour FROM hrm_payroll_salary
		LEFT JOIN hrm_payroll ON(Payroll_ID = Salary_PayrollID)
		WHERE Salary_EmpID = SEmpID AND LOWER(Salary_Status) = 'active';

		IF Deduct_Leave_Balance_Hourly = 'Half of Day' THEN
			SELECT COALESCE(fnHRMCheckLeaveBaanceRate(SEmpID, LeaveTypeBaseBalance, lt.LeaveType_AmountAllowed), 0)-COALESCE((SELECT SUM(ld.Leave_Amount) FROM hrm_timesheet_leave l LEFT JOIN hrm_timesheet_leave_detail ld ON(l.Leave_ID = ld.LeaveD_ID AND l.Leave_EmpID = SEmpID AND ld.LeaveD_TypeID = STypeID) WHERE l.Leave_EmpID = SEmpID AND LOWER(l.Leave_Status) <> 'rejected'), 0) INTO SBalance
			FROM hrm_timesheet_leave_type lt
			LEFT JOIN hrm_timesheet_leave_type_employee e ON(e.Leave_TypeID = lt.LeaveType_ID)
			WHERE e.Leave_EmpID = SEmpID AND lt.LeaveType_ID = STypeID AND lt.LeaveType_Year = SYear;

		ELSEIF Deduct_Leave_Balance_Hourly = 'Hourly' THEN
			IF LOWER(SDuration) = 'full day' AND WorkHour > 0 THEN

				SELECT COALESCE(SUM(if(LOWER(ld.LeaveD_Duration) = 'full day', ld.Leave_Total, 0)), 0) INTO Tempfullday 
				FROM hrm_timesheet_leave l 
				LEFT JOIN hrm_timesheet_leave_detail ld ON(l.Leave_ID = ld.LeaveD_ID AND l.Leave_EmpID = SEmpID AND ld.LeaveD_TypeID = STypeID)
				WHERE l.Leave_EmpID = SEmpID AND ld.LeaveD_TypeID = STypeID AND LOWER(l.Leave_Status) <> 'rejected';
			
				SELECT COALESCE(SUM(if(LOWER(ld.LeaveD_Duration) = 'hourly', ld.Leave_Total, 0)), 0) INTO Temphourly 
				FROM hrm_timesheet_leave l 
				LEFT JOIN hrm_timesheet_leave_detail ld ON(l.Leave_ID = ld.LeaveD_ID AND l.Leave_EmpID = SEmpID AND ld.LeaveD_TypeID = STypeID)
				WHERE l.Leave_EmpID = SEmpID AND ld.LeaveD_TypeID = STypeID AND LOWER(l.Leave_Status) <> 'rejected';
				
				SELECT COALESCE(fnHRMCheckLeaveBaanceRate(SEmpID, LeaveTypeBaseBalance, lt.LeaveType_AmountAllowed), 0) - COALESCE((Tempfullday + COALESCE(FLOOR(Temphourly/WorkHour))),0) - COALESCE(if(MOD(Temphourly,WorkHour) > 0, 1, 0), 0) INTO SBalance
				FROM hrm_timesheet_leave_type lt
				LEFT JOIN hrm_timesheet_leave_type_employee e ON(e.Leave_TypeID = lt.LeaveType_ID)
				WHERE e.Leave_EmpID = SEmpID AND lt.LeaveType_ID = STypeID AND lt.LeaveType_Year = SYear;

			ELSEIF LOWER(SDuration) = 'hourly' AND WorkHour > 0 THEN

				SELECT COALESCE(SUM(if(LOWER(ld.LeaveD_Duration) = 'full day', ld.Leave_Total, 0)), 0) INTO Tempfullday 
				FROM hrm_timesheet_leave l 
				LEFT JOIN hrm_timesheet_leave_detail ld ON(l.Leave_ID = ld.LeaveD_ID AND l.Leave_EmpID = SEmpID AND ld.LeaveD_TypeID = STypeID)
				WHERE l.Leave_EmpID = SEmpID AND ld.LeaveD_TypeID = STypeID AND LOWER(l.Leave_Status) <> 'rejected';
			
				SELECT COALESCE(SUM(if(LOWER(ld.LeaveD_Duration) = 'hourly', ld.Leave_Total, 0)), 0) INTO Temphourly 
				FROM hrm_timesheet_leave l 
				LEFT JOIN hrm_timesheet_leave_detail ld ON(l.Leave_ID = ld.LeaveD_ID AND l.Leave_EmpID = SEmpID AND ld.LeaveD_TypeID = STypeID)
				WHERE l.Leave_EmpID = SEmpID AND ld.LeaveD_TypeID = STypeID AND LOWER(l.Leave_Status) <> 'rejected';
				
				SELECT COALESCE(fnHRMCheckLeaveBaanceRate(SEmpID, LeaveTypeBaseBalance, lt.LeaveType_AmountAllowed) * WorkHour, 0) - COALESCE((Tempfullday * WorkHour + COALESCE(Temphourly)),0) INTO SBalance
				FROM hrm_timesheet_leave_type lt
				LEFT JOIN hrm_timesheet_leave_type_employee e ON(e.Leave_TypeID = lt.LeaveType_ID)
				WHERE e.Leave_EmpID = SEmpID AND lt.LeaveType_ID = STypeID AND lt.LeaveType_Year = SYear;

			END IF;
		END IF;
	ELSE
			SET SBalance = 10000;
	END IF;
	SELECT SBalance;
	CALL hrm_message_param3('1101606', 'Leave', 'notallowed', STypeID, STotal, '');
	
	/*SELECT COALESCE((al.LeaveType_AmountAllowed - (al.Leave_Taken + al.Leave_Pending)), 0) INTO SBalance FROM (
				SELECT b.LeaveType_ID,b.LeaveType_AmountAllowed, 
				SUM(IF(l.Leave_Duration = 'Full Day' AND l.Leave_Status = 'approved', l.Leave_Total, IF(Emp_ShiftType = 'Normal' AND l.Leave_Status = 'approved', IF(COALESCE(wd.Shift_TotalWorkHour, 0)=0,0,IF(l.Leave_Total <= (COALESCE(wd.Shift_TotalWorkHour, 0)/2),0.5,1)), IF(Emp_ShiftType = 'Roster' AND l.Leave_Status = 'approved', IF(COALESCE(wdd.Shift_TotalWorkHour, 0)=0,0,IF(l.Leave_Total <= (COALESCE(wdd.Shift_TotalWorkHour, 0)/2),0.5,1)) , 0)))) AS 'Leave_Taken',

				SUM(IF(l.Leave_Duration = 'Full Day' AND l.Leave_Status = 'requested', l.Leave_Total, IF(Emp_ShiftType = 'Normal' AND l.Leave_Status = 'requested', IF(COALESCE(wd.Shift_TotalWorkHour, 0)=0,0,IF(l.Leave_Total <= (COALESCE(wd.Shift_TotalWorkHour, 0)/2),0.5,1)), IF(Emp_ShiftType = 'Roster' AND l.Leave_Status = 'requested', IF(COALESCE(wdd.Shift_TotalWorkHour, 0)=0,0,IF(l.Leave_Total <= (COALESCE(wdd.Shift_TotalWorkHour, 0)/2),0.5,1)) , 0)))) AS 'Leave_Pending'

				FROM hrm_timesheet_leave_type b INNER JOIN hrm_timesheet_leave_type_employee e on(b.LeaveType_ID = e.Leave_TypeID)
				INNER JOIN tblemployee emp ON emp.EmpID = e.Leave_EmpID
				LEFT JOIN hrm_timesheet_leave l ON b.LeaveType_ID = l.Leave_TypeID
				LEFT JOIN hrm_timesheet_worksheet_detail wd ON wd.Shift_ID = emp.Emp_ShiftID AND wd.Shift_Day = DAYNAME(l.Leave_From)
				LEFT JOIN hrm_timesheet_roster r ON r.Roster_EmpID = emp.EmpID AND r.Roster_Date = DATE(l.Leave_From)
				LEFT JOIN hrm_timesheet_worksheet_detail wdd ON r.Roster_ShiftID = wdd.Shift_ID AND r.Roster_EmpID = emp.EmpID AND r.Roster_Date = DATE(l.Leave_From)
				WHERE (b.LeaveType_Year = SYear OR b.LeaveType_Year = 0) AND e.Leave_EmpID = SEmpID AND b.LeaveType_PayStatus = "Unpay" AND b.LeaveType_ID = STypeID
				GROUP BY b.LeaveType_ID 
			
	) al ORDER BY al.LeaveType_ID;*/

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckLeaveBalanceUpdate`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckLeaveBalanceUpdate`(IN SEmpID varchar(255),IN SYear int,IN STypeID varchar(255),IN SDuration varchar(255), IN STotal varchar(255), IN SID varchar(255))
    DETERMINISTIC
BEGIN

	/*SELECT lt.LeaveType_AmountAllowed-SUM(l.Leave_Amount) INTO SBalance
	FROM hrm_timesheet_leave l
	INNER JOIN hrm_timesheet_leave_type lt ON lt.LeaveType_ID = l.Leave_TypeID AND lt.LeaveType_Year = SYear 
	WHERE l.Leave_EmpID = SEmpID AND l.Leave_TypeID = STypeID;*/
	DECLARE Deduct_Leave_Balance_Hourly VARCHAR(255);
	DECLARE WorkHour FLOAT DEFAULT(0);
	DECLARE Tempfullday FLOAT DEFAULT(0);
	DECLARE Temphourly FLOAT DEFAULT(0);
	DECLARE SBalance FLOAT DEFAULT(0);
	DECLARE CheckLeavePayType VARCHAR(255) DEFAULT('');
	DECLARE LeaveTypeBaseBalance VARCHAR(255) DEFAULT('');

	SELECT LeaveType_PayStatus, LeaveType_BaseBalance INTO CheckLeavePayType, LeaveTypeBaseBalance FROM hrm_timesheet_leave_type WHERE LeaveType_ID = STypeID;

	IF LOWER(CheckLeavePayType) = 'paid' THEN

		SELECT Setting_Value INTO Deduct_Leave_Balance_Hourly FROM hrm_setting WHERE Setting_Type = 'Leave' AND Setting_Name = 'Deduct_Leave_Balance_Hourly';
		
		SELECT Payroll_AmtWorkingHourPerDay INTO WorkHour FROM hrm_payroll_salary
		LEFT JOIN hrm_payroll ON(Payroll_ID = Salary_PayrollID)
		WHERE Salary_EmpID = SEmpID AND LOWER(Salary_Status) = 'active';

		IF Deduct_Leave_Balance_Hourly = 'Half of Day' THEN
			SELECT COALESCE(fnHRMCheckLeaveBaanceRate(SEmpID, LeaveTypeBaseBalance, lt.LeaveType_AmountAllowed), 0)-COALESCE((SELECT SUM(ld.Leave_Amount) FROM hrm_timesheet_leave l LEFT JOIN hrm_timesheet_leave_detail ld ON(l.Leave_ID = ld.LeaveD_ID AND ld.LeaveD_TypeID = STypeID) WHERE l.Leave_EmpID = SEmpID AND l.Leave_ID != SID AND LOWER(l.Leave_Status) <> 'rejected'), 0) INTO SBalance
			FROM hrm_timesheet_leave_type lt
			LEFT JOIN hrm_timesheet_leave_type_employee e ON(e.Leave_TypeID = lt.LeaveType_ID)
			WHERE e.Leave_EmpID = SEmpID AND lt.LeaveType_ID = STypeID AND lt.LeaveType_Year = SYear;

		ELSEIF Deduct_Leave_Balance_Hourly = 'Hourly' THEN
			IF LOWER(SDuration) = 'full day' AND WorkHour > 0  THEN

				SELECT COALESCE(SUM(if(LOWER(ld.LeaveD_Duration) = 'full day', ld.Leave_Total, 0)), 0) INTO Tempfullday 
				FROM hrm_timesheet_leave l 
				LEFT JOIN hrm_timesheet_leave_detail ld ON(l.Leave_ID = ld.LeaveD_ID AND ld.LeaveD_TypeID = STypeID)
				WHERE l.Leave_EmpID = SEmpID AND ld.LeaveD_TypeID = STypeID AND l.Leave_ID != SID AND LOWER(l.Leave_Status) <> 'rejected';
			
				SELECT COALESCE(SUM(if(LOWER(ld.LeaveD_Duration) = 'hourly', ld.Leave_Total, 0)), 0) INTO Temphourly 
				FROM hrm_timesheet_leave l 
				LEFT JOIN hrm_timesheet_leave_detail ld ON(l.Leave_ID = ld.LeaveD_ID AND ld.LeaveD_TypeID = STypeID)
				WHERE l.Leave_EmpID = SEmpID AND ld.LeaveD_TypeID = STypeID  AND l.Leave_ID != SID AND LOWER(l.Leave_Status) <> 'rejected';
				
				SELECT COALESCE(fnHRMCheckLeaveBaanceRate(SEmpID, LeaveTypeBaseBalance, lt.LeaveType_AmountAllowed), 0) - COALESCE((Tempfullday + COALESCE(FLOOR(Temphourly/WorkHour))),0) - COALESCE(if(MOD(Temphourly,WorkHour) > 0, 1, 0), 0) INTO SBalance
				FROM hrm_timesheet_leave_type lt
				LEFT JOIN hrm_timesheet_leave_type_employee e ON(e.Leave_TypeID = lt.LeaveType_ID)
				WHERE e.Leave_EmpID = SEmpID AND lt.LeaveType_ID = STypeID AND lt.LeaveType_Year = SYear;

			ELSEIF LOWER(SDuration) = 'hourly' AND WorkHour > 0  THEN

				SELECT COALESCE(SUM(if(LOWER(ld.LeaveD_Duration) = 'full day', ld.Leave_Total, 0)), 0) INTO Tempfullday 
				FROM hrm_timesheet_leave l 
				LEFT JOIN hrm_timesheet_leave_detail ld ON(l.Leave_ID = ld.LeaveD_ID AND ld.LeaveD_TypeID = STypeID)
				WHERE l.Leave_EmpID = SEmpID AND ld.LeaveD_TypeID = STypeID AND l.Leave_ID != SID AND LOWER(l.Leave_Status) <> 'rejected';
			
				SELECT COALESCE(SUM(if(LOWER(ld.LeaveD_Duration) = 'hourly', ld.Leave_Total, 0)), 0) INTO Temphourly 
				FROM hrm_timesheet_leave l 
				LEFT JOIN hrm_timesheet_leave_detail ld ON(l.Leave_ID = ld.LeaveD_ID AND ld.LeaveD_TypeID = STypeID)
				WHERE l.Leave_EmpID = SEmpID AND ld.LeaveD_TypeID = STypeID AND l.Leave_ID != SID AND LOWER(l.Leave_Status) <> 'rejected';
				
				SELECT COALESCE(fnHRMCheckLeaveBaanceRate(SEmpID, LeaveTypeBaseBalance, lt.LeaveType_AmountAllowed) * WorkHour, 0) - COALESCE((Tempfullday * WorkHour + COALESCE(Temphourly)),0) INTO SBalance
				FROM hrm_timesheet_leave_type lt
				LEFT JOIN hrm_timesheet_leave_type_employee e ON(e.Leave_TypeID = lt.LeaveType_ID)
				WHERE e.Leave_EmpID = SEmpID AND lt.LeaveType_ID = STypeID AND lt.LeaveType_Year = SYear;

			END IF;
		END IF;
	ELSE
			SET SBalance = 10000;
	END IF;
	SELECT SBalance;
	CALL hrm_message_param3('1101606', 'Leave', 'notallowed', STypeID, STotal, '');
	
	/*SELECT COALESCE((al.LeaveType_AmountAllowed - (al.Leave_Taken + al.Leave_Pending)), 0) INTO SBalance FROM (
				SELECT b.LeaveType_ID,b.LeaveType_AmountAllowed, 
				SUM(IF(l.Leave_Duration = 'Full Day' AND l.Leave_Status = 'approved', l.Leave_Total, IF(Emp_ShiftType = 'Normal' AND l.Leave_Status = 'approved', IF(COALESCE(wd.Shift_TotalWorkHour, 0)=0,0,IF(l.Leave_Total <= (COALESCE(wd.Shift_TotalWorkHour, 0)/2),0.5,1)), IF(Emp_ShiftType = 'Roster' AND l.Leave_Status = 'approved', IF(COALESCE(wdd.Shift_TotalWorkHour, 0)=0,0,IF(l.Leave_Total <= (COALESCE(wdd.Shift_TotalWorkHour, 0)/2),0.5,1)) , 0)))) AS 'Leave_Taken',

				SUM(IF(l.Leave_Duration = 'Full Day' AND l.Leave_Status = 'requested', l.Leave_Total, IF(Emp_ShiftType = 'Normal' AND l.Leave_Status = 'requested', IF(COALESCE(wd.Shift_TotalWorkHour, 0)=0,0,IF(l.Leave_Total <= (COALESCE(wd.Shift_TotalWorkHour, 0)/2),0.5,1)), IF(Emp_ShiftType = 'Roster' AND l.Leave_Status = 'requested', IF(COALESCE(wdd.Shift_TotalWorkHour, 0)=0,0,IF(l.Leave_Total <= (COALESCE(wdd.Shift_TotalWorkHour, 0)/2),0.5,1)) , 0)))) AS 'Leave_Pending'

				FROM hrm_timesheet_leave_type b INNER JOIN hrm_timesheet_leave_type_employee e on(b.LeaveType_ID = e.Leave_TypeID)
				INNER JOIN tblemployee emp ON emp.EmpID = e.Leave_EmpID
				LEFT JOIN hrm_timesheet_leave l ON b.LeaveType_ID = l.Leave_TypeID
				LEFT JOIN hrm_timesheet_worksheet_detail wd ON wd.Shift_ID = emp.Emp_ShiftID AND wd.Shift_Day = DAYNAME(l.Leave_From)
				LEFT JOIN hrm_timesheet_roster r ON r.Roster_EmpID = emp.EmpID AND r.Roster_Date = DATE(l.Leave_From)
				LEFT JOIN hrm_timesheet_worksheet_detail wdd ON r.Roster_ShiftID = wdd.Shift_ID AND r.Roster_EmpID = emp.EmpID AND r.Roster_Date = DATE(l.Leave_From)
				WHERE (b.LeaveType_Year = SYear OR b.LeaveType_Year = 0) AND e.Leave_EmpID = SEmpID AND b.LeaveType_PayStatus = "Unpay" AND b.LeaveType_ID = STypeID
				GROUP BY b.LeaveType_ID 
			
	) al ORDER BY al.LeaveType_ID;*/

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckLeaveTo`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckLeaveTo`(SEmpID varchar(255), SDate DateTime)
    DETERMINISTIC
BEGIN
	DECLARE ShiftType VARCHAR(255) DEFAULT('');	
	DECLARE ShiftID VARCHAR(255) DEFAULT('');	
	SELECT e.Emp_ShiftType,e.Emp_ShiftID INTO ShiftType,ShiftID FROM tblemployee e WHERE e.EmpID = SEmpID;

	IF LOWER(ShiftType) = 'normal' THEN
			SELECT wd.Shift_ID,wd.Shift_Day,wd.Shift_TotalWorkHour,wd.Shift_TotalWorkOvertime,wd.Shift_TimeIn1,wd.Shift_TimeInPeriod1,wd.Shift_TimeOut1,wd.Shift_TimeOutPeriod1,wd.Shift_TimeIn2,wd.Shift_TimeInPeriod2,wd.Shift_TimeOut2,wd.Shift_TimeOutPeriod2,wd.Shift_TimeIn3,wd.Shift_TimeInPeriod3,wd.Shift_TimeOut3,wd.Shift_TimeOutPeriod3,wd.Shift_TimeIn4,wd.Shift_TimeInPeriod4,wd.Shift_TimeOut4,wd.Shift_TimeOutPeriod4,wd.Shift_TimeIn5,wd.Shift_TimeInPeriod5,wd.Shift_TimeOut5,wd.Shift_TimeOutPeriod5,wd.Shift_TimeInOvertime,wd.Shift_TimeOutOvertime,Shift_TimeBreak1,Shift_TimeBreak2,Shift_TimeBreak3,Shift_TimeBreak4,Shift_TimeBreak5 FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID = ShiftID AND LOWER(wd.Shift_Day) = LOWER(DAYNAME(SDate));
	ELSE
			SELECT wd.Shift_ID,wd.Shift_Day,wd.Shift_TotalWorkHour,wd.Shift_TotalWorkOvertime,wd.Shift_TimeIn1,wd.Shift_TimeInPeriod1,wd.Shift_TimeOut1,wd.Shift_TimeOutPeriod1,wd.Shift_TimeIn2,wd.Shift_TimeInPeriod2,wd.Shift_TimeOut2,wd.Shift_TimeOutPeriod2,wd.Shift_TimeIn3,wd.Shift_TimeInPeriod3,wd.Shift_TimeOut3,wd.Shift_TimeOutPeriod3,wd.Shift_TimeIn4,wd.Shift_TimeInPeriod4,wd.Shift_TimeOut4,wd.Shift_TimeOutPeriod4,wd.Shift_TimeIn5,wd.Shift_TimeInPeriod5,wd.Shift_TimeOut5,wd.Shift_TimeOutPeriod5,wd.Shift_TimeInOvertime,wd.Shift_TimeOutOvertime,Shift_TimeBreak1,Shift_TimeBreak2,Shift_TimeBreak3,Shift_TimeBreak4,Shift_TimeBreak5 FROM hrm_timesheet_workshift_detail wd WHERE wd.Shift_ID = (SELECT Roster_ShiftID FROM hrm_timesheet_roster WHERE Roster_Date = SDate AND Roster_EmpID = SEmpID);
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckTask`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckTask`(SNow Date)
    DETERMINISTIC
BEGIN

	/*DECLARE SNow DATE;
	DECLARE tz VARCHAR(20) DEFAULT('');
	
	SELECT Setting_Value INTO tz FROM hrm_setting WHERE Setting_Type = 'TimeZone' AND Setting_Name = 'TimeZone';
	SET SNow = convert_tz(now(), @@session.time_zone, tz);*/

	-- Currency
	INSERT INTO hrm_payroll_currency_history(Currency_ID,Currency_Name,Currency_Date,Currency_Rate) 
	SELECT Currency_ID,Currency_Name,SNow,Currency_Rate FROM hrm_payroll_currency;

	-- Payroll
	CALL spHRMCheckTaskPayroll(SNow);

	-- Attendance Normal
	CALL spHRMCheckTaskAttendance(SNow);

	-- Break Attandence Normal
	-- UPDATE hrm_timesheet_attendance SET Att_Status='B', Att_RStatus='B' WHERE Att_Date=SNow AND Att_Status='P' AND Att_In1='00:00:00' AND Att_Out1='00:00:00' AND Att_In2='00:00:00' AND Att_Out2='00:00:00' AND Att_In3='00:00:00' AND Att_Out3='00:00:00' AND Att_In4='00:00:00' AND Att_Out4='00:00:00' AND Att_In5='00:00:00' AND Att_Out5='00:00:00';

	-- Auto FP
	#CALL spHRMCheckTaskAutoFP(SNow);
	

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckTaskAttendance`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckTaskAttendance`(SNow Date)
    DETERMINISTIC
BEGIN
	DECLARE SEmpID VARCHAR(255) DEFAULT('');
	DECLARE SShiftID VARCHAR(255) DEFAULT('');
	DECLARE SFPID VARCHAR(255) DEFAULT('');
	DECLARE done INT DEFAULT FALSE;
  DECLARE cursor_i CURSOR FOR SELECT e.EmpID,e.Emp_ShiftID,e.Emp_FPID FROM tblemployee e WHERE e.Emp_FPID <> '' OR e.Emp_FPID <> NULL;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
  OPEN cursor_i;
  read_loop: LOOP
    FETCH cursor_i INTO SEmpID, SShiftID, SFPID;
    IF done THEN
      LEAVE read_loop;
    END IF;
		 CALL spHRMAddAttendanceNormal(SEmpID,SShiftID,SFPID,SNow, '00:00:00', '00:00:00', '00:00:00', '00:00:00', '00:00:00', '00:00:00', '00:00:00', '00:00:00', '00:00:00', '00:00:00');   
  END LOOP;
  CLOSE cursor_i;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckTaskAutoFP`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckTaskAutoFP`()
    DETERMINISTIC
BEGIN
	/*DECLARE AutoFPID VARCHAR(255) DEFAULT('');
	DECLARE AutoFPDay VARCHAR(255) DEFAULT('');
	DECLARE AutoFPShiftID VARCHAR(255) DEFAULT('');
	DECLARE AutoFP_In1 INT DEFAULT(0);
	DECLARE AutoFP_Out1 INT DEFAULT(0);
	DECLARE AutoFP_In2 INT DEFAULT(0);
	DECLARE AutoFP_Out2 INT DEFAULT(0);
	DECLARE AutoFP_In3 INT DEFAULT(0);
	DECLARE AutoFP_Out3 INT DEFAULT(0);
	DECLARE AutoFP_In4 INT DEFAULT(0);
	DECLARE AutoFP_Out4 INT DEFAULT(0);
	DECLARE AutoFP_In5 INT DEFAULT(0);
	DECLARE AutoFP_Out5 INT DEFAULT(0);


	DECLARE done INT DEFAULT FALSE;
  DECLARE cursor_i CURSOR FOR SELECT f.AutoFP_ID,f.AutoFP_ShiftID,fd.AutoFP_Day,fd.AutoFP_In1,fd.AutoFP_Out1,fd.AutoFP_In2,fd.AutoFP_Out2,fd.AutoFP_In3,fd.AutoFP_Out3,fd.AutoFP_In4,fd.AutoFP_Out4,fd.AutoFP_In5,fd.AutoFP_Out5 FROM hrm_timesheet_auto_fingerprint f INNER JOIN hrm_timesheet_auto_finger_detail fd ON(f.AutoFP_ID=fd.AutoFP_ID AND (LOWER(fd.AutoFP_Day)=LOWER(DAYNAME(SNow)) OR fd.AutoFP_Day=''));
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
  OPEN cursor_i;
  read_loop: LOOP
    FETCH cursor_i INTO AutoFPID, AutoFPShiftID, AutoFPDay, AutoFP_In1, AutoFP_Out1, AutoFP_In2, AutoFP_Out2, AutoFP_In3, AutoFP_Out3, AutoFP_In4, AutoFP_Out4, AutoFP_In5, AutoFP_Out5;
    IF done THEN
      LEAVE read_loop;
    END IF;

		IF AutoFPDay != '' THEN
			CALL spHRMCheckAutoFPNormal(AutoFPShiftID, SNow, AutoFP_In1, AutoFP_Out1, AutoFP_In2, AutoFP_Out2, AutoFP_In3, AutoFP_Out3, AutoFP_In4, AutoFP_Out4, AutoFP_In5, AutoFP_Out5);
		ELSE
			CALL spHRMCheckAutoFPRoster(AutoFPShiftID, SNow, AutoFP_In1, AutoFP_Out1, AutoFP_In2, AutoFP_Out2, AutoFP_In3, AutoFP_Out3, AutoFP_In4, AutoFP_Out4, AutoFP_In5, AutoFP_Out5);
		END IF;
		
  END LOOP;
  CLOSE cursor_i;*/

	DECLARE SNow DATETIME;
	DECLARE tz VARCHAR(20) DEFAULT('');
	
	SELECT Setting_Value INTO tz FROM hrm_setting WHERE Setting_Type = 'TimeZone' AND Setting_Name = 'TimeZone';
	SET SNow = convert_tz(now(), @@session.time_zone, tz);

	SELECT f.AutoFP_ID, SNow, f.AutoFP_ShiftID,fd.AutoFP_Day,fd.AutoFP_In1,fd.AutoFP_Out1,fd.AutoFP_In2,fd.AutoFP_Out2,fd.AutoFP_In3,fd.AutoFP_Out3,fd.AutoFP_In4,fd.AutoFP_Out4,fd.AutoFP_In5,fd.AutoFP_Out5 FROM hrm_timesheet_auto_fingerprint f INNER JOIN hrm_timesheet_auto_finger_detail fd ON(f.AutoFP_ID=fd.AutoFP_ID AND (LOWER(fd.AutoFP_Day)=LOWER(DAYNAME(SNow)) OR fd.AutoFP_Day=''));
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckTaskPayroll`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckTaskPayroll`(SNow DATE)
    DETERMINISTIC
BEGIN
	DECLARE PayrollID VARCHAR(255) DEFAULT('');
	DECLARE PayrollName VARCHAR(255) DEFAULT('');
	DECLARE PayrollType VARCHAR(255) DEFAULT('');
	DECLARE PayrollStartDate DATE;
	DECLARE PayrollLastSubmitDate DATE;
	DECLARE PayrollSubmitDate DATE;
	DECLARE PayrollSalaryStartDate DATE;
	DECLARE PayrollLastSalaryDate DATE;
	DECLARE PayrollSalaryDate DATE;
	DECLARE D DATE;
	DECLARE SD DATE;
	DECLARE ID VARCHAR(255) DEFAULT('');
	DECLARE done INT DEFAULT FALSE;
	DECLARE cur1 CURSOR FOR SELECT Payroll_ID,Payroll_Name,Payroll_Type,Payroll_StartDate,Payroll_LastSubmitDate,Payroll_SubmitDate,Payroll_SalaryStartDate,Payroll_LastSalaryDate,Payroll_SalaryDate FROM hrm_payroll WHERE Payroll_SubmitDate = SNow; 
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	OPEN cur1;
	read_loop: LOOP
  FETCH cur1 INTO PayrollID,PayrollName,PayrollType,PayrollStartDate,PayrollLastSubmitDate,PayrollSubmitDate,PayrollSalaryStartDate,PayrollLastSalaryDate,PayrollSalaryDate;
  IF done THEN
    LEAVE read_loop;
  END IF;
	IF PayrollType = "Monthly" THEN
		SET D = DATE_ADD(PayrollSubmitDate, INTERVAL 1 MONTH);
		SET SD = DATE_ADD(PayrollSalaryDate, INTERVAL 1 MONTH);
		CALL spHRMGetNumberPrefix("SubmitPayroll", ID);
		INSERT INTO hrm_payroll_submit_payroll(SubmitPayroll_ID,SubmitPayroll_PayrollID,SubmitPayroll_Date,SubmitPayroll_StartDate,SubmitPayroll_EndDate,SubmitPayroll_SalaryDate,SubmitPayroll_SalaryStartDate,SubmitPayroll_SalaryEndDate) VALUES(ID, PayrollID, PayrollSubmitDate, PayrollLastSubmitDate, DATE_SUB(PayrollSubmitDate, INTERVAL 1 DAY), PayrollSalaryDate, PayrollLastSalaryDate, DATE_SUB(PayrollSalaryDate, INTERVAL 1 DAY));
		CALL spHRMUpdateNumberPrefix("SubmitPayroll");
		UPDATE hrm_payroll SET Payroll_LastSubmitDate=PayrollSubmitDate, Payroll_SubmitDate=D,Payroll_LastSalaryDate=PayrollSalaryDate,Payroll_SalaryDate=SD WHERE Payroll_ID=PayrollID;
	ELSEIF PayrollType = "Biweekly" THEN
		SET D = DATE_ADD(PayrollSubmitDate, INTERVAL 14 DAY);
		SET SD = DATE_ADD(PayrollSalaryDate, INTERVAL 14 DAY);
		CALL spHRMGetNumberPrefix("SubmitPayroll", ID);
		INSERT INTO hrm_payroll_submit_payroll(SubmitPayroll_ID,SubmitPayroll_PayrollID,SubmitPayroll_Date,SubmitPayroll_StartDate,SubmitPayroll_EndDate,SubmitPayroll_SalaryDate,SubmitPayroll_SalaryStartDate,SubmitPayroll_SalaryEndDate) VALUES(ID, PayrollID, PayrollSubmitDate, PayrollLastSubmitDate, DATE_SUB(PayrollSubmitDate, INTERVAL 1 DAY), PayrollSalaryDate, PayrollLastSalaryDate, DATE_SUB(PayrollSalaryDate, INTERVAL 1 DAY));
		CALL spHRMUpdateNumberPrefix("SubmitPayroll");
		UPDATE hrm_payroll SET Payroll_LastSubmitDate=PayrollSubmitDate, Payroll_SubmitDate=D,Payroll_LastSalaryDate=PayrollSalaryDate,Payroll_SalaryDate=SD WHERE Payroll_ID=PayrollID;				
	ELSEIF PayrollType = "Weekly" THEN
		SET D = DATE_ADD(PayrollSubmitDate, INTERVAL 7 DAY);
		SET SD = DATE_ADD(PayrollSalaryDate, INTERVAL 7 DAY);
		CALL spHRMGetNumberPrefix("SubmitPayroll", ID);
		INSERT INTO hrm_payroll_submit_payroll(SubmitPayroll_ID,SubmitPayroll_PayrollID,SubmitPayroll_Date,SubmitPayroll_StartDate,SubmitPayroll_EndDate,SubmitPayroll_SalaryDate,SubmitPayroll_SalaryStartDate,SubmitPayroll_SalaryEndDate) VALUES(ID, PayrollID, PayrollSubmitDate, PayrollLastSubmitDate, DATE_SUB(PayrollSubmitDate, INTERVAL 1 DAY), PayrollSalaryDate, PayrollLastSalaryDate, DATE_SUB(PayrollSalaryDate, INTERVAL 1 DAY));
		CALL spHRMUpdateNumberPrefix("SubmitPayroll");
		UPDATE hrm_payroll SET Payroll_LastSubmitDate=PayrollSubmitDate, Payroll_SubmitDate=D,Payroll_LastSalaryDate=PayrollSalaryDate,Payroll_SalaryDate=SD WHERE Payroll_ID=PayrollID;		
	ELSEIF PayrollType = "Daily" THEN
		SET D = DATE_ADD(PayrollSubmitDate, INTERVAL 1 DAY);
		SET SD = DATE_ADD(PayrollSalaryDate, INTERVAL 1 DAY);
		CALL spHRMGetNumberPrefix("SubmitPayroll", ID);
		INSERT INTO hrm_payroll_submit_payroll(SubmitPayroll_ID,SubmitPayroll_PayrollID,SubmitPayroll_Date,SubmitPayroll_StartDate,SubmitPayroll_EndDate,SubmitPayroll_SalaryDate,SubmitPayroll_SalaryStartDate,SubmitPayroll_SalaryEndDate) VALUES(ID, PayrollID, PayrollSubmitDate, PayrollLastSubmitDate, DATE_SUB(PayrollSubmitDate, INTERVAL 1 DAY), PayrollSalaryDate, PayrollLastSalaryDate, DATE_SUB(PayrollSalaryDate, INTERVAL 1 DAY));
		CALL spHRMUpdateNumberPrefix("SubmitPayroll");
		UPDATE hrm_payroll SET Payroll_LastSubmitDate=PayrollSubmitDate, Payroll_SubmitDate=D,Payroll_LastSalaryDate=PayrollSalaryDate,Payroll_SalaryDate=SD WHERE Payroll_ID=PayrollID;		
	END IF;
			
	END LOOP;
	CLOSE cur1;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCheckUpdateSync`;
DELIMITER |
CREATE PROCEDURE `spHRMCheckUpdateSync`(IN TblName text, IN F1 text, IN V1 Text, IN F2 text, IN V2 Text, IN F3 text, IN V3 Text)
    DETERMINISTIC
BEGIN
	SET @i = 0;
	SET @u = 0;
	IF F3 is NOT NULL AND V3 IS NOT NULL THEN
		SELECT COUNT(*) INTO @i FROM hrm_synchronize s WHERE s.tblName = TblName AND s.F1 = F1 AND s.V1 = V1 AND s.F2 = F2 AND s.V2 = V2 AND s.F3 = F3 AND s.V3 = V3 AND s.Action_Status = 'insert' AND s.IsSynced = 0;
		SELECT COUNT(*) INTO @u FROM hrm_synchronize s WHERE s.tblName = TblName AND s.F1 = F1 AND s.V1 = V1 AND s.F2 = F2 AND s.V2 = V2 AND s.F3 = F3 AND s.V3 = V3 AND s.Action_Status = 'update' AND s.IsSynced = 0;
		IF @i = 0 AND @u = 0 THEN
			INSERT INTO hrm_synchronize(tblname,F1,V1,Action_Status,IsSynced,Action_Date,F2,V2,F3,V3) VALUES (TblName,F1,V1,'update',0,NOW(),F2,V2,F3,V3);
		END IF;
	ELSEIF F2 is NOT NULL AND V2 IS NOT NULL THEN
		SELECT COUNT(*) INTO @i FROM hrm_synchronize s WHERE s.tblName = TblName AND s.F1 = F1 AND s.V1 = V1 AND s.F2 = F2 AND s.V2 = V2 AND s.Action_Status = 'insert' AND s.IsSynced = 0;
		SELECT COUNT(*) INTO @u FROM hrm_synchronize s WHERE s.tblName = TblName AND s.F1 = F1 AND s.V1 = V1 AND s.F2 = F2 AND s.V2 = V2 AND s.Action_Status = 'update' AND s.IsSynced = 0;
		IF @i = 0 AND @u = 0 THEN
			INSERT INTO hrm_synchronize(tblname,F1,V1,Action_Status,IsSynced,Action_Date,F2,V2) VALUES (TblName,F1,V1,'update',0,NOW(),F2,V2);
		END IF;
	ELSE
		SELECT COUNT(*) INTO @i FROM hrm_synchronize s WHERE s.tblName = TblName AND s.F1 = F1 AND s.V1 = V1 AND s.Action_Status = 'insert' AND s.IsSynced = 0;
		SELECT COUNT(*) INTO @u FROM hrm_synchronize s WHERE s.tblName = TblName AND s.F1 = F1 AND s.V1 = V1 AND s.Action_Status = 'update' AND s.IsSynced = 0;
		IF @i = 0 AND @u = 0 THEN
			INSERT INTO hrm_synchronize(tblname,F1,V1,Action_Status,IsSynced,Action_Date) VALUES (TblName,F1,V1,'update',0,NOW());
		END IF;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMCurrency`;
DELIMITER |
CREATE PROCEDURE `spHRMCurrency`(def tinyint, statuss varchar(20), curName varchar(255), cur text)
    DETERMINISTIC
BEGIN
	IF def = 0 THEN
		IF statuss = "add" THEN
			SET @SQL1 = CONCAT("INSERT INTO hrm_currency(CurName,CurPlace,CurDesc,CurRate) VALUES(", cur, "); ");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
			CALL spHRMCheckInsertSync('hrm_currency', 'CurName', curName, NULL, NULL, NULL, NULL);
		ELSEIF statuss = "update" THEN
			SET @SQL1 = CONCAT("UPDATE hrm_currency SET ", cur, " WHERE CurName = '", curName ,"'; ");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
			CALL spHRMCheckUpdateSync('hrm_currency', 'CurName', curName, NULL, NULL, NULL, NULL);
		ELSEIF statuss = "delete" THEN
			SET @SQL1 = CONCAT("DELETE FROM hrm_currency WHERE CurName = '", curName ,"'; ");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
			CALL spHRMCheckDeleteSync('hrm_currency', 'CurName', curName, NULL, NULL, NULL, NULL);
		END IF;
	ELSEIF def = 1 THEN
			SELECT CurName INTO @c from hrm_currency WHERE CurDefault = 1;
			SET @SQL1 = "UPDATE hrm_currency SET CurDefault = 0 WHERE CurDefault = 1;";
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
			CALL spHRMCheckUpdateSync('hrm_currency', 'CurName', @c, NULL, NULL, NULL, NULL);

			SET @SQL1 = CONCAT("UPDATE hrm_currency SET CurDefault = 1 WHERE CurName = '", curName ,"'; ");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
			CALL spHRMCheckUpdateSync('hrm_currency', 'CurName', curName, NULL, NULL, NULL, NULL);
	END IF;
	

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteAllowance`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteAllowance`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	SELECT Count(Allowance_ID) INTO CheckExist FROM hrm_payroll_allowance_employee WHERE Allowance_ID = ID;

	IF CheckExist <= 0 THEN

		DELETE FROM hrm_payroll_allowance WHERE Allowance_ID = ID;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Allowance', ID);
	
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1100103', 'Allowance', 'delete', ID);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1100105', 'Allowance', 'used', ID);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteAuthorisation`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteAuthorisation`(UserID varchar(255),AuthID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	SELECT Count(Auth_ID) INTO CheckExist FROM hrm_authorisation_employee WHERE Auth_ID = AuthID;
	IF CheckExist <= 0 THEN
		DELETE FROM hrm_authorisation WHERE Auth_ID = AuthID;

		DELETE FROM hrm_authorisation_detail WHERE Auth_ID  = AuthID;

		CALL spHRMAddLog(userid, "delete", "Authorisation", AuthID);

		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1101403', 'Auth', 'delete', AuthID);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1101405', 'Auth', 'used', AuthID);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteAuthorisationGroup`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteAuthorisationGroup`(UserID varchar(255),AuthGroupID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckUsed INT DEFAULT(0);
	SELECT Count(Auth_GroupID) INTO CheckUsed FROM hrm_authorisation_detail WHERE Auth_GroupID = AuthGroupID;
	IF CheckUsed <= 0 THEN
		SELECT COUNT(*) INTO CheckUsed FROM hrm_authorisation_approved ap WHERE ap.Auth_GroupID = AuthGroupID;
	END IF;
	IF CheckUsed <= 0 THEN
		DELETE FROM hrm_authorisation_group WHERE AuthGroup_ID = AuthGroupID;

		DELETE FROM hrm_authorisation_group_detail WHERE AuthGroup_ID  = AuthGroupID;

		CALL spHRMAddLog(userid, "delete", "AuthorisationGroup", AuthGroupID);

		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1101503', 'AuthGroup', 'delete', AuthGroupID);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1101505', 'AuthGroup', 'used', AuthGroupID);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteAutoFP`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteAutoFP`(UserID varchar(255),SID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);
	DECLARE CheckUsed INT DEFAULT(0);

		IF CheckUsed <= 0 THEN

			DELETE FROM hrm_timesheet_auto_fingerprint WHERE AutoFP_ID = SID;

			DELETE FROM hrm_timesheet_auto_finger_detail WHERE AutoFP_ID = SID;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'AutoFP', SID);
	
			SET Message = "success";
			SELECT Message;
			CALL hrm_message('1102203', 'AutoFP', 'delete', SID);
		ELSE
			SET Message = "used";
			SELECT Message;
			CALL hrm_message('1102205', 'AutoFP', 'used', SID);
		END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteBonus`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteBonus`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);
	DECLARE CheckUsed INT DEFAULT(0);

		SELECT COUNT(*) INTO CheckUsed FROM hrm_payroll_bonus_detail WHERE Bonus_ID = ID AND Bonus_PayStatus <> 'Open';
		IF CheckUsed <= 0 THEN

			DELETE FROM hrm_payroll_bonus WHERE Bonus_ID = ID;

			DELETE FROM hrm_payroll_bonus_detail WHERE Bonus_ID = ID;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Bonus', ID);
	
			SET Message = "success";
			SELECT Message;
			CALL hrm_message('1100203', 'Bonus', 'delete', ID);
		ELSE
			SET Message = "used";
			SELECT Message;
			CALL hrm_message('1100205', 'Bonus', 'used', ID);
		END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteCurrency`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteCurrency`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	SELECT Currency_Default INTO CheckExist FROM hrm_payroll_currency WHERE Currency_ID = ID;

	IF CheckExist = 0 THEN

		DELETE FROM hrm_payroll_currency WHERE Currency_ID = ID;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Currency', ID);
	
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1100003', 'Currency', 'delete', ID);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1100005', 'Currency', 'used', ID);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteDayoff`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteDayoff`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE CheckAuth VARCHAR(1) DEFAULT("1");
	DECLARE OldDate DATE;
	DECLARE SEmpID VARCHAR(255);

	SELECT Setting_Value INTO CheckAuth FROM hrm_setting WHERE Setting_Type = "Authorisation" AND Setting_Name = "Authorisation_Dayoff";
	IF CheckAuth ="1" THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_authorisation_approved WHERE Auth_ProcessID = ID AND Auth_ProcessName = "Dayoff" AND (Auth_Status = "approved" OR Auth_Status = "rejected");
		IF CheckExist <= 0 THEN
				SELECT COUNT(*) INTO CheckExist FROM hrm_timesheet_dayoff WHERE Dayoff_ID = ID AND (Dayoff_Status = "approved" OR Dayoff_Status = "rejected");
		END IF;
		IF CheckExist <= 0 THEN

			DELETE FROM hrm_timesheet_dayoff WHERE Dayoff_ID = ID;

			DELETE FROM hrm_authorisation_approved WHERE  Auth_ProcessID = ID AND Auth_ProcessName = "Dayoff";

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Dayoff', ID);
	
			SET Message = "success";
			SELECT Message;
			CALL hrm_message('1101703', 'Dayoff', 'delete', ID);
		ELSE
			SET Message = "used";
			SELECT Message;
			CALL hrm_message('1101705', 'Dayoff', 'used', ID);
		END IF;
	ELSE
		-- check Attendance
		SELECT Dayoff_Date, Dayoff_EmpID INTO OldDate, SEmpID FROM hrm_timesheet_dayoff WHERE Dayoff_ID = ID;

		DELETE FROM hrm_timesheet_dayoff WHERE Dayoff_ID = ID;

		-- check Attendance
		CALL spHRMAttendanceLeaveDeleteFullDay(SEmpID, OldDate, OldDate);

		DELETE FROM hrm_authorisation_approved WHERE  Auth_ProcessID = ID AND Auth_ProcessName = "Dayoff";

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Dayoff', ID);
	
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1101703', 'Dayoff', 'delete', ID);
	END IF;

	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteDeduction`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteDeduction`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE CheckAuth VARCHAR(1) DEFAULT("1");

	SELECT Setting_Value INTO CheckAuth FROM hrm_setting WHERE Setting_Type = "Authorisation" AND Setting_Name = "Authorisation_Deduction";
	IF CheckAuth ="1" THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_authorisation_approved WHERE Auth_ProcessID = ID AND Auth_ProcessName = "Deduction" AND (Auth_Status = "approved" OR Auth_Status = "rejected"  OR Auth_Status = "approved & deducted");
		IF CheckExist <= 0 THEN
				SELECT COUNT(*) INTO CheckExist FROM hrm_payroll_deduction WHERE Deduction_ID = ID AND (Deduction_Status = "approved" OR Deduction_Status = "rejected" OR Deduction_Status = "approved & deducted");
			END IF;
		IF CheckExist <= 0 THEN

			DELETE FROM hrm_payroll_deduction WHERE Deduction_ID = ID;

			DELETE FROM hrm_authorisation_approved WHERE  Auth_ProcessID = ID AND Auth_ProcessName = "Deduction";

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Deduction', ID);
	
			SET Message = "success";
			SELECT Message;
			CALL hrm_message('1100303', 'Deduction', 'delete', ID);
		ELSE
			SET Message = "used";
			SELECT Message;
			CALL hrm_message('1100305', 'Deduction', 'used', ID);
		END IF;
	ELSE
		DELETE FROM hrm_payroll_deduction WHERE Deduction_ID = ID;

		DELETE FROM hrm_authorisation_approved WHERE  Auth_ProcessID = ID AND Auth_ProcessName = "Deduction";

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Deduction', ID);
	
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1100303', 'Deduction', 'delete', ID);
			
	END IF;

	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployee`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployee`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE SUID VARCHAR(255);
	SELECT Count(e.var_id) INTO CheckExist FROM ame_mt_emp e WHERE e.var_hrm_supervisor = ID;

	SELECT COALESCE(e.var_img, '') AS EmpImg FROM ame_mt_emp e WHERE e.var_id = ID;

	SELECT Att_FilePath FROM hrm_employee_attachment WHERE Emp_ID = ID;
	
	IF CheckExist <= 0 THEN

		DELETE FROM ame_mt_emp WHERE var_id = ID;
	
		DELETE FROM hrm_employee_social_communication WHERE Emp_ID = ID;

		DELETE FROM hrm_employee_skill WHERE Emp_ID = ID;

		DELETE FROM hrm_employee_language WHERE Emp_ID = ID;

		DELETE FROM hrm_employee_education WHERE Emp_ID = ID;

		DELETE FROM hrm_employee_experience WHERE Emp_ID = ID;

		DELETE FROM hrm_employee_family WHERE Emp_ID = ID; 
	
		DELETE FROM hrm_employee_contract WHERE Emp_ID = ID; 
	
		DELETE FROM hrm_employee_training WHERE Emp_ID = ID;

		DELETE FROM hrm_employee_attachment WHERE Emp_ID = ID;

		DELETE FROM hrm_employee_membership WHERE Emp_ID = ID;

		DELETE FROM hrm_employee_insurance WHERE Emp_ID = ID;

		SELECT COALESCE(var_id, '') AS UID INTO SUID FROM ame_user WHERE var_empid = ID;

		DELETE FROM ame_user WHERE var_id = SUID;
		DELETE FROM ame_user_app WHERE var_id = SUID;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Employee', ID);

		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1104503', 'Employee', 'delete', ID);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1104505', 'Employee', 'used', ID);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeAllowance`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeAllowance`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);

	DELETE FROM hrm_payroll_allowance_employee WHERE Allowance_EmpID = ID;

	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Employee Allowance', ID);
	
	SET Message = "success";
	SELECT Message;
	
	CALL hrm_message('1100402', 'EmpAllowance', 'delete', ID);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeAllowanceID`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeAllowanceID`(UserID varchar(255),ID varchar(255), AllowanceID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);

	DELETE FROM hrm_payroll_allowance_employee WHERE Allowance_EmpID = ID AND Allowance_ID = AllowanceID;

	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Employee Allowance', CONCAT(ID, ', ',AllowanceID));
	
	SET Message = "success";
	SELECT Message;
	
	CALL hrm_message('1100403', 'EmpAllowance', 'delete', ID);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeAuthorisation`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeAuthorisation`(UserID varchar(255),EmpID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	IF EmpID != '' THEN
		DELETE FROM hrm_authorisation_employee WHERE Emp_ID = EmpID;

		CALL spHRMAddLog(userid, "delete", "EmployeeAuthorisation", EmpID);

		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1102403', 'EmpAuth', 'delete', EmpID);
	ELSE
		SET Message = "fail";
		SELECT Message;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeAuthorisationID`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeAuthorisationID`(UserID varchar(255),EmpID varchar(255), SAuthProcess varchar(255), SAuthID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	IF EmpID != '' THEN
		DELETE FROM hrm_authorisation_employee WHERE Emp_ID = EmpID AND Auth_Process = SAuthProcess AND Auth_ID = SAuthID;

		CALL spHRMAddLog(userid, "delete", "Employee Authorisation", CONCAT(EmpID, ', ', SAuthProcess, ', ', SAuthID));

		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1102403', 'EmpAuth', 'delete', SAuthID);
	ELSE
		SET Message = "fail";
		SELECT Message;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeBank`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeBank`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	SELECT Count(var_hrm_bank_id) INTO CheckExist FROM ame_mt_emp WHERE var_hrm_bank_id = ID;

	IF CheckExist <= 0 THEN
		DELETE FROM hrm_emp_bank WHERE Bank_ID = ID;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'EmployeeBank', ID);

		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1102503', 'Bank', 'delete', ID);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1102505', 'Bank', 'used', ID);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeBranch`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeBranch`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	SELECT Count(e.var_hrm_branch_id) INTO CheckExist FROM ame_mt_emp e WHERE e.var_hrm_branch_id = ID;

	IF CheckExist <= 0 THEN

		DELETE FROM hrm_emp_branch WHERE Branch_ID = ID;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'EmployeeBranch', ID);
	
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1102603', 'Branch', 'delete', ID);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1102605', 'Branch', 'uesed', ID);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeCategory`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeCategory`(UserID varchar(255),CategoryName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	SELECT Count(var_hrm_category) INTO CheckExist FROM ame_mt_emp WHERE var_hrm_category = CategoryName;
	IF CheckExist <= 0 THEN
		DELETE FROM hrm_emp_category WHERE Category_Name = CategoryName;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'EmployeeCategory', CategoryName);
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1102703', 'Category', 'delete', CategoryName);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1102705', 'Category', 'used', CategoryName);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeContractType`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeContractType`(UserID varchar(255),ContractTypeName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);

	SELECT Count(Con_Type) INTO CheckExist FROM hrm_employee_contract WHERE Con_Type = ContractTypeName;

	IF CheckExist <= 0 THEN
		
		DELETE FROM hrm_emp_contract_type WHERE ContractType_Name = ContractTypeName;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'EmployeexContractType', ContractTypeName);
		SET Message = "success";
		CALL hrm_message('1102803', 'ContractType', 'delete', contractTypeName);
		SELECT Message;
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1102805', 'ContractType', 'used', contractTypeName);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeCountry`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeCountry`(UserID varchar(255),CountryName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	SELECT Count(var_addr7) INTO CheckExist FROM ame_mt_emp WHERE var_addr7 = CountryName;
	IF CheckExist <= 0 THEN
		SELECT Count(var_hrm_permanent_country) INTO CheckExist FROM ame_mt_emp WHERE var_hrm_permanent_country = CountryName;
	END IF;
	IF CheckExist <= 0 THEN
		DELETE FROM hrm_location_country WHERE Country_Name = CountryName;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Country', CountryName);
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1104203', 'Country', 'delete', CountryName);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1104205', 'Country', 'used', CountryName);
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeDepartment`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeDepartment`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	SELECT Count(var_hrm_department_id) INTO CheckExist FROM ame_mt_emp e WHERE e.var_hrm_department_id = ID;

	IF CheckExist <= 0 THEN

		DELETE FROM hrm_emp_department WHERE Department_ID = ID;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'EmployeeDepartment', ID);

		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1103203', 'Department', 'delete', ID);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1103205', 'Department', 'used', ID);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeGrade`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeGrade`(UserID varchar(255),SName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);

	SELECT Count(var_hrm_grade) INTO CheckExist FROM ame_mt_emp WHERE var_hrm_grade = SName;

	IF CheckExist <= 0 THEN

		DELETE FROM hrm_emp_grade WHERE Grade_Name = SName;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'EmployeeGrade', SName);

		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1104603', 'Grade', 'delete', SName);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1104605', 'Grade', 'used', SName);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeInsurance`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeInsurance`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	SELECT Count(Ins_InsuranceID) INTO CheckExist FROM hrm_employee_insurance WHERE Ins_InsuranceID = ID;

	IF CheckExist <= 0 THEN

		DELETE FROM hrm_emp_insurance WHERE Insurance_ID = ID;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'EmployeeInsurance', ID);

		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1103603', 'Insurance', 'delete', ID);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1103605', 'Insurance', 'used', ID);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeInsuranceType`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeInsuranceType`(UserID varchar(255),InsuranceTypeName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	SELECT Count(Insurance_Type) INTO CheckExist FROM hrm_emp_insurance WHERE Insurance_Type = InsuranceTypeName;
	IF CheckExist <= 0 THEN
		DELETE FROM hrm_emp_insurance_type WHERE InsuranceType_Name = InsuranceTypeName;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'EmployeeInsuranceType', InsuranceTypeName);
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1103703', 'InsuranceType', 'delete', InsuranceTypeName);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1103705', 'InsuranceType', 'used', InsuranceTypeName);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeLanguage`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeLanguage`(UserID varchar(255),LanguageName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	SELECT Count(l.`Language`) INTO CheckExist FROM hrm_employee_language l WHERE l.`Language` = LanguageName;

	IF CheckExist <= 0 THEN
		DELETE FROM hrm_emp_language WHERE Language_Name = LanguageName;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'EmployeeLanguage', LanguageName);
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1103403', 'Language', 'delete', LanguageName);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1103405', 'Language', 'used', LanguageName);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeLeaveType`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeLeaveType`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);

	DELETE FROM hrm_timesheet_leave_type_employee WHERE Leave_EmpID = ID;

	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Employee Leave Type', ID);
	
	SET Message = "success";
	SELECT Message;
	CALL hrm_message('1101102', 'EmpLeaveType', 'delete', ID);
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeLeaveTypeID`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeLeaveTypeID`(UserID varchar(255),SID varchar(255), STypeID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);

	DELETE FROM hrm_timesheet_leave_type_employee WHERE Leave_EmpID = SID AND Leave_TypeID = STypeID;

	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Employee Leave Type', SID);
	
	SET Message = "success";
	SELECT Message;
	CALL hrm_message('1101103', 'EmpLeaveType', 'delete', STypeID);
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeLevel`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeLevel`(UserID varchar(255),LevelName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	SELECT Count(Language_ReadLevel) INTO CheckExist FROM hrm_employee_language WHERE Language_ReadLevel = LevelName;
	IF CheckExist <=0 THEN
		SELECT Count(Language_WriteLevel) INTO CheckExist FROM hrm_employee_language WHERE Language_WriteLevel = LevelName;
	END IF;
	IF CheckExist <=0 THEN
		SELECT Count(Language_SpeakLevel) INTO CheckExist FROM hrm_employee_language WHERE Language_SpeakLevel = LevelName;
	END IF;
	IF CheckExist <=0 THEN
		SELECT Count(Language_UnderstandLevel) INTO CheckExist FROM hrm_employee_language WHERE Language_UnderstandLevel = LevelName;
	END IF;
	IF CheckExist <= 0 THEN
		DELETE FROM hrm_emp_level WHERE Level_Name = LevelName;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'EmployeeLevel', LevelName);
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1103503', 'Level', 'delete', LevelName);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1103551', 'Level', 'used', LevelName);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeMembershipType`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeMembershipType`(UserID varchar(255),MembershipTypeName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	SELECT Count(Mem_Type) INTO CheckExist FROM hrm_employee_membership WHERE Mem_Type = MembershipTypeName;
	IF CheckExist <= 0 THEN
		DELETE FROM hrm_emp_membership_type WHERE MembershipType_Name = MembershipTypeName;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'EmployeeMembershipType', MembershipTypeName);
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1103303', 'MemberShipType', 'delete', MembershipTypeName);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1103305', 'MemberShipType', 'used', MembershipTypeName);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeNationality`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeNationality`(UserID varchar(255),NationalityName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	SELECT Count(var_hrm_nationality) INTO CheckExist FROM ame_mt_emp WHERE var_hrm_nationality = NationalityName;
	IF CheckExist <= 0 THEN
		DELETE FROM hrm_emp_nationality WHERE Nationnality_Name = NationalityName;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'EmployeeNationality', NationalityName);
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1103903', 'Nationality', 'delete', NationalityName);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1103905', 'Nationality', 'used', NationalityName);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeNationals`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeNationals`(UserID varchar(255),NationalsName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	SELECT Count(var_hrm_nationals) INTO CheckExist FROM ame_mt_emp WHERE var_hrm_nationals = NationalsName;
	IF CheckExist <= 0 THEN
		DELETE FROM hrm_emp_nationals WHERE Nationals_Name = NationalsName;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'EmployeeNationals', NationalsName);
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1104003', 'National', 'delete', NationalsName);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1104005', 'National', 'used', NationalsName);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeePosition`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeePosition`(UserID varchar(255), PositionID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	SELECT Count(*) INTO CheckExist FROM ame_mt_emp WHERE var_posid = PositionId;

	IF CheckExist <= 0 THEN

		DELETE FROM ame_mt_pos WHERE var_id = PositionID;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'EmployeePosition', PositionID);

		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1102903', 'Position', 'delete', PositionID);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1102905', 'Position', 'used', PositionID);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeSchool`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeSchool`(UserID varchar(255),SchoolName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	SELECT Count(Edu_School) INTO CheckExist FROM hrm_employee_education WHERE Edu_School = SchoolName;
	IF CheckExist <= 0 THEN
		DELETE FROM hrm_emp_school WHERE School_Name = SchoolName;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'EmployeeSchool', SchoolName);
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1104103', 'School', 'delete', SchoolName);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1104105', 'School', 'used', SchoolName);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeSocialCommunication`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeSocialCommunication`(UserID varchar(255),SCName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	SELECT Count(SocialCommunication) INTO CheckExist FROM hrm_employee_social_communication WHERE SocialCommunication = SCName;
	IF CheckExist <= 0 THEN
		DELETE FROM hrm_emp_social_communication WHERE SocialCommunication_Name = SCName;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'EmployeeSocialCommunication', SCName);
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1103803', 'SocialCommunication', 'delete', SCName);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1103805', 'SocialCommunication', 'used', SCName);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeStatus`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeStatus`(UserID varchar(255),StatusName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	SELECT Count(dat_hrm_date_status) INTO CheckExist FROM ame_mt_emp WHERE dat_hrm_date_status = StatusName;
	IF StatusName = 'Death' OR StatusName = 'Recruited' OR StatusName = 'Reinstated' OR StatusName = 'Resigned' OR StatusName = 'Retired' OR StatusName = 'Terminated' THEN
		SET CheckExist = 1;
	END IF;
	IF CheckExist <= 0 THEN
		DELETE FROM hrm_emp_status WHERE Status_Name = StatusName;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'EmployeeStatus', StatusName);
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1103003', 'Status', 'delete', StatusName);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1103005', 'Status', 'used', StatusName);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeSubAttachment`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeSubAttachment`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE EmpID VARCHAR(255);
	DECLARE AttFileName VARCHAR(255);
	DECLARE AttFilePath VARCHAR(255);

	SELECT Emp_ID,Att_FileName,Att_FilePath INTO EmpID, AttFileName, AttFilePath  FROM hrm_employee_attachment WHERE MainID = ID;

	DELETE FROM hrm_employee_attachment WHERE MainID = ID;

	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Employee Training', CONCAT(EmpID,", ",AttFileName, ", ", AttFilePath));

	SET Message = "success";
	SELECT Message;
	CALL hrm_message('1104514', 'Employee', 'delete', EmpID);
	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeSubContact`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeSubContact`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE EmpID VARCHAR(255);
	DECLARE ConName VARCHAR(255);
	DECLARE ConType VARCHAR(255);

	SELECT Emp_ID,Con_Name,Con_Type INTO EmpID, ConName, ConType  FROM hrm_employee_contract WHERE Con_AutoID = ID;

	DELETE FROM hrm_employee_contract WHERE Con_AutoID = ID;

	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Employee Contract', CONCAT(EmpID,", ",ConName, ", ", ConType));

	SET Message = "success";
	SELECT Message;
	CALL hrm_message('1104512', 'Employee', 'delete', EmpID);
	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeSubEducation`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeSubEducation`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE EmpID VARCHAR(255);
	DECLARE EducationName VARCHAR(255);

	SELECT e.Emp_ID, e.Edu_Name INTO EmpID, EducationName  FROM hrm_employee_education e WHERE e.Edu_AutoID = ID;

	DELETE FROM hrm_employee_education WHERE Edu_AutoID = ID;

	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Employee Education', CONCAT(EmpID,", ",EducationName));

	SET Message = "success";
	SELECT Message;
	CALL hrm_message('1104509', 'Employee', 'delete', EmpID);
	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeSubExperience`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeSubExperience`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE EmpID VARCHAR(255);
	DECLARE position VARCHAR(255);
	DECLARE company VARCHAR(255);

	SELECT Emp_ID,Ex_Position,Ex_Company INTO EmpID, position, company  FROM hrm_employee_experience WHERE Ex_AutoID = ID;

	DELETE FROM hrm_employee_experience WHERE Ex_AutoID = ID;

	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Employee Experience', CONCAT(EmpID,", ",position, ", ", company));

	SET Message = "success";
	SELECT Message;
	CALL hrm_message('1104510', 'Employee', 'delete', EmpID);
	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeSubFamily`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeSubFamily`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE EmpID VARCHAR(255);
	DECLARE FamName VARCHAR(255);

	SELECT Emp_ID,Fam_Name INTO EmpID, FamName  FROM hrm_employee_family WHERE l.Fam_AutoID = ID;

	DELETE FROM hrm_employee_family WHERE Fam_AutoID = ID;

	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Employee Family', CONCAT(EmpID,", ",FamName));

	SET Message = "success";
	SELECT Message;
	CALL hrm_message('1104511', 'Employee', 'delete', EmpID);
	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeSubInsurance`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeSubInsurance`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE EmpID VARCHAR(255);
	DECLARE InsInsuranceID VARCHAR(255);

	SELECT Emp_ID,Ins_InsuranceID INTO EmpID, InsInsuranceID  FROM hrm_employee_insurance WHERE Ins_AutoID = ID;

	DELETE FROM hrm_employee_insurance WHERE Ins_AutoID = ID;

	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Employee Insurance', CONCAT(EmpID,", ",InsInsuranceID));

	SET Message = "success";
	SELECT Message;
	CALL hrm_message('1104516', 'Employee', 'delete', EmpID);
	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeSubLanguage`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeSubLanguage`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE EmpID VARCHAR(255);
	DECLARE LanguageName VARCHAR(255);

	SELECT l.Emp_ID,l.Language INTO EmpID, LanguageName  FROM hrm_employee_language l WHERE l.Language_AutoID = ID;

	DELETE FROM hrm_employee_language WHERE Language_AutoID = ID;

	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Employee Language', CONCAT(EmpID,", ",LanguageName));

	SET Message = "success";
	SELECT Message;
	CALL hrm_message('1104508', 'Employee', 'delete', EmpID);
	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeSubMembership`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeSubMembership`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE EmpID VARCHAR(255);
	DECLARE MemName VARCHAR(255);
	DECLARE MemInstitute VARCHAR(255);

	SELECT Emp_ID,Mem_Name,Mem_Institute INTO EmpID, MemName, MemInstitute  FROM hrm_employee_membership WHERE Mem_AutoID = ID;

	DELETE FROM hrm_employee_membership WHERE Mem_AutoID = ID;

	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Employee Membership', CONCAT(EmpID,", ",MemName, ", ", MemInstitute));

	SET Message = "success";
	SELECT Message;
	CALL hrm_message('1104515', 'Employee', 'delete', EmpID);
	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeSubProfile`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeSubProfile`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255) DEFAULT('');

	UPDATE ame_mt_emp SET var_img = '' WHERE EmpID = ID;

	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Employee Profile', ID);

	SET Message = "success";
	SELECT Message;
	CALL hrm_message('1104517', 'Employee', 'update', ID);
	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeSubSkill`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeSubSkill`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE EmpID VARCHAR(255);
	DECLARE Sk_Name VARCHAR(255);
	DECLARE Sk_Level VARCHAR(255);

	SELECT Emp_ID,Skill_Name,Skill_Level INTO EmpID, Sk_Name, Sk_Level  FROM hrm_employee_skill WHERE Skill_AutoID = ID;

	DELETE FROM hrm_employee_skill WHERE Skill_AutoID = ID;

	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Employee Skill', CONCAT(EmpID,", ",Sk_Name, ", ", Sk_Level));

	SET Message = "success";
	SELECT Message;
	CALL hrm_message('1104507', 'Employee', 'delete', EmpID);
	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeSubSocialCommunication`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeSubSocialCommunication`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE EmpID VARCHAR(255);
	DECLARE Sc VARCHAR(255);
	DECLARE ScValue VARCHAR(255);

	SELECT Emp_ID,SocialCommunication,SocialCommunication_Value INTO EmpID, Sc, ScValue  FROM hrm_employee_social_communication WHERE SocailCommunication_AutoID = ID;

	DELETE FROM hrm_employee_social_communication WHERE SocailCommunication_AutoID = ID;

	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Employee Social Communication', CONCAT(EmpID,", ",Sc, ", ", ScValue));

	SET Message = "success";
	SELECT Message;
	CALL hrm_message('1104506', 'Employee', 'delete', EmpID);
	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeSubTrain`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeSubTrain`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE EmpID VARCHAR(255);
	DECLARE TrainInstituteName VARCHAR(255);
	DECLARE TrainCertificate VARCHAR(255);

	SELECT Emp_ID,Train_Certificate,Train_Certificate INTO EmpID, TrainInstituteName, TrainCertificate  FROM hrm_employee_training WHERE Train_AutoID = ID;

	DELETE FROM hrm_employee_training WHERE Train_AutoID = ID;

	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Employee Training', CONCAT(EmpID,", ",TrainInstituteName, ", ", TrainCertificate));

	SET Message = "success";
	SELECT Message;
	CALL hrm_message('1104513', 'Employee', 'delete', EmpID);
	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteEmployeeType`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteEmployeeType`(UserID varchar(255),TypeName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);

	SELECT Count(var_hrm_type) INTO CheckExist FROM ame_mt_emp WHERE var_hrm_type = TypeName;

	IF CheckExist <= 0 THEN

		DELETE FROM hrm_emp_type WHERE Type_Name = TypeName;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'EmployeeType', TypeName);
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1103103', 'Type', 'delete', TypeName);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1103105', 'Type', 'used', TypeName);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteFile`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteFile`(IN fileName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Path text;

	SELECT Setting_Value INTO Path FROM hrm_setting WHERE Setting_Type='Path' AND Setting_Name = 'File_Path'; 
	SET Path = CONCAT(Path , "/", fileName);

	INSERT INTO hrm_delete_file_temp(File_Name) VALUES(Path);

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteFiles`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteFiles`(IN fileName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Path text;

	SELECT Setting_Value INTO Path FROM hrm_setting WHERE Setting_Type='Path' AND Setting_Name = 'File_Path';  
	
	WHILE (LOCATE('/', filename) > 0) DO
        SET @value = LEFT(filename, LOCATE('/',filename) - 1);    
        SET filename = SUBSTRING(filename, LOCATE(',',filename) + 1);
				IF @value != "" THEN
					SET @value = CONCAT(Path , "/", @value);
					INSERT INTO hrm_delete_file_temp(File_Name) VALUES(@value);
				END IF;
	END WHILE;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteHoliday`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteHoliday`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);
	DECLARE CheckUsed INT DEFAULT(0);
	DECLARE SNow DATE;
	DECLARE tz VARCHAR(20) DEFAULT('');
	DECLARE SBranch VARCHAR(255);
	DECLARE SStart Date;
	DECLARE SEnd Date;

	SELECT Setting_Value INTO tz FROM hrm_setting WHERE Setting_Type = 'TimeZone' AND Setting_Name = 'TimeZone';
	SET SNow = convert_tz(now(), @@session.time_zone, tz);

	SELECT IF(Holiday_StartDate < SNow, 1, 0)INTO CheckUsed FROM hrm_timesheet_holiday WHERE Holiday_ID = ID;
	
	IF CheckUsed <= 0 THEN
		
		-- SELECT Holiday_BranchID,Holiday_StartDate,Holiday_EndDate INTO SBranch,SStart,SEnd FROM hrm_timesheet_holiday WHERE Holiday_ID = ID;

		DELETE FROM hrm_timesheet_holiday WHERE Holiday_ID = ID;

		DELETE FROM hrm_timesheet_holiday_detail WHERE HolidayD_ID = ID;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Holiday', ID);

		/*IF SBranch = 'all' THEN
				CALL spHRMAttendanceHolidayDeleteAll(SStart, SEnd);
		ELSE
			CALL spHRMAttendanceHolidayDelete(SBranch, SStart, SEnd);
		END IF;*/
	
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1101803', 'Holiday', 'delete', ID);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1101805', 'Holiday', 'used', ID);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteLateDuration`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteLateDuration`(UserID varchar(255),SFrom int, STo int, SDeduct int)
    DETERMINISTIC
BEGIN
	DECLARE Message VARCHAR(255);

	DELETE FROM hrm_timesheet_late_duration WHERE LD_From = SFrom AND LD_To = STo AND LD_Deduction = SDeduct;

	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Late Duration', CONCAT(SFrom,', ',STo, ', ', SDeduct));
	SET Message = "success";
	SELECT Message;
	CALL hrm_message_param3('1104703', 'LateDuration', 'delete', SFrom, STo, SDeduct);
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteLeave`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteLeave`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE CheckAuth VARCHAR(1) DEFAULT("1");
	DECLARE File VARCHAR(255);

	DECLARE ShiftType VARCHAR(255);
  DECLARE ShiftID VARCHAR(255);
  DECLARE SEmpID VARCHAR(255);

	SELECT Setting_Value INTO CheckAuth FROM hrm_setting WHERE Setting_Type = "Authorisation" AND Setting_Name = "Authorisation_Leave";
	IF CheckAuth ="1" THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_authorisation_approved WHERE Auth_ProcessID = ID AND Auth_ProcessName = "Leave" AND (Auth_Status = "approved" OR Auth_Status = "rejected" OR Auth_Status = "approved & deducted");
		IF CheckExist <= 0 THEN
				SELECT COUNT(*) INTO CheckExist FROM hrm_timesheet_leave WHERE Leave_ID = ID AND (Leave_Status = "approved" OR Leave_Status = "rejected");
			END IF;
		IF CheckExist <= 0 THEN
			SELECT Leave_EmpID INTO SEmpID FROM hrm_timesheet_leave WHERE Leave_ID = ID;
		
			SELECT Leave_AttachmentPath INTO File FROM hrm_timesheet_leave WHERE Leave_ID = ID;

			DELETE FROM hrm_timesheet_leave WHERE Leave_ID = ID;
		
			DELETE FROM hrm_timesheet_leave_detail WHERE LeaveD_ID = ID;

			DELETE FROM hrm_authorisation_approved WHERE  Auth_ProcessID = ID AND Auth_ProcessName = "Leave";

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Leave', ID);
	
			SET Message = "success";
			SELECT Message;
			CALL hrm_message('1101603', 'Leave', 'delete', ID);
			SELECT File;
		ELSE
			SET Message = "used";
			SELECT Message;
			CALL hrm_message('1101605', 'Leave', 'used', ID);
		END IF;
	ELSE

		SELECT Leave_EmpID INTO SEmpID FROM hrm_timesheet_leave WHERE Leave_ID = ID;

		CALL spHRMCheckDeleteAttendanceLeave(ID, SEmpID); 

		DELETE FROM hrm_timesheet_leave_detail WHERE LeaveD_ID = ID;
		
		SELECT Leave_AttachmentPath INTO File FROM hrm_timesheet_leave WHERE Leave_ID = ID;

		DELETE FROM hrm_timesheet_leave WHERE Leave_ID = ID;

		DELETE FROM hrm_authorisation_approved WHERE  Auth_ProcessID = ID AND Auth_ProcessName = "Leave";

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Leave', ID);
	
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1101603', 'Leave', 'delete', ID);
		SELECT File;
	END IF;

	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteOvertime`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteOvertime`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE CheckAuth VARCHAR(1) DEFAULT("1");

	SELECT Setting_Value INTO CheckAuth FROM hrm_setting WHERE Setting_Type = "Authorisation" AND Setting_Name = "Authorisation_Overtime";
	IF CheckAuth ="1" THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_authorisation_approved WHERE Auth_ProcessID = ID AND Auth_ProcessName = "Overtime" AND (Auth_Status = "approved" OR Auth_Status = "rejected");
		IF CheckExist <= 0 THEN
			SELECT COUNT(*) INTO CheckExist FROM hrm_payroll_overtime WHERE Overtime_ID = ID AND (Overtime_Status = "approved" OR Overtime_Status = "rejected");
		END IF;
		IF CheckExist <= 0 THEN

			DELETE FROM hrm_payroll_overtime WHERE Overtime_ID = ID;

			DELETE FROM hrm_payroll_overtime_detail WHERE od_id = ID;
		
			DELETE FROM hrm_payroll_overtime_detail_employee WHERE od_id = ID;

			DELETE FROM hrm_authorisation_approved WHERE  Auth_ProcessID = ID AND Auth_ProcessName = "Overtime";

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Overtime', ID);
	
			SET Message = "success";
			SELECT Message;
			CALL hrm_message('1100703', 'Overtime', 'delete', ID);
		ELSE
			SET Message = "used";
			SELECT Message;
			CALL hrm_message('1100705', 'Overtime', 'used', ID);
		END IF;
	ELSE
		DELETE FROM hrm_payroll_overtime WHERE Overtime_ID = ID;

		DELETE FROM hrm_authorisation_approved WHERE  Auth_ProcessID = ID AND Auth_ProcessName = "Overtime";

		DELETE FROM hrm_payroll_overtime_detail WHERE od_id = ID;
		
		DELETE FROM hrm_payroll_overtime_detail_employee WHERE od_id = ID;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Overtime', ID);
	
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1100703', 'Overtime', 'delete', ID);
			
	END IF;

	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeletePayroll`;
DELIMITER |
CREATE PROCEDURE `spHRMDeletePayroll`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);

	SELECT Count(Salary_EmpID) INTO CheckExist FROM hrm_payroll_salary WHERE  Salary_PayrollID= ID;

	IF CheckExist <= 0 THEN

		DELETE FROM hrm_payroll WHERE Payroll_ID = ID;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Payroll', ID);
	
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1100803', 'Payroll', 'delete', ID);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1100805', 'Payroll', 'used', ID);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteRole`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteRole`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);
	DECLARE CheckUsed INT DEFAULT(0);

		SELECT COUNT(*) INTO CheckUsed FROM ame_user WHERE var_hrm_role= ID;

		IF CheckUsed <= 0 AND ID <> 'ADMIN' AND ID <> 'ESS' THEN

			DELETE FROM hrm_role WHERE RM_ID = ID;

			DELETE FROM hrm_role_detail WHERE RM_RoleID = ID;

			DELETE FROM hrm_role_rpt_detail WHERE RMR_RoleID = ID;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Role', ID);
	
			SET Message = "success";
			SELECT Message;
			CALL hrm_message('1104303', 'Role', 'delete', ID);
		ELSE
			SET Message = "used";
			SELECT Message;
			CALL hrm_message('1104305', 'Role', 'used', ID);
		END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteRoster`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteRoster`(UserID varchar(255), SDate Date, SEmpID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE SNow DATE;
	DECLARE tz VARCHAR(20) DEFAULT('');

	SELECT Setting_Value INTO tz FROM hrm_setting WHERE Setting_Type = 'TimeZone' AND Setting_Name = 'TimeZone';
	SET SNow = convert_tz(now(), @@session.time_zone, tz);

	IF SNow < SDate THEN
			-- SELECT COUNT(*) INTO CheckExist FROM hrm_timesheet_roster WHERE Roster_Date = SDate AND LOWER(Roster_EmpID) = SEmpID;
			IF CheckExist <= 0 THEN
					DELETE FROM hrm_timesheet_roster WHERE Roster_Date = SDate AND Roster_EmpID = SEmpID;

					INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Roster', CONCAT(SDate,", ",SEmpID));
						
					SET Message = "success";
					SELECT Message;
					CALL hrm_message_param3('1102003', 'Roster', 'delete', SDate, SEmpID, "");
			ELSE
				SET Message = "exist";
				SELECT Message;
				CALL hrm_message_param3('1102004', 'Roster', 'exist', SDate, SEmpID, "");
			END IF;
	ELSE
		SET Message = "not allowed";
		SELECT Message;
		CALL hrm_message('1102006', 'Roster', 'notallowed', DATE_FORMAT(SDate, '%d-%m-%Y'));
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteSalaryAdjustment`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteSalaryAdjustment`(UserID varchar(255),SID varchar(255), SEmpID varchar(255), SSalary Double)
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);

	DELETE FROM hrm_payroll_salary_adjustment WHERE adj_submitpayrollID = SID AND adj_empid = SEmpID AND adj_salary = SSalary;

	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Salary Adjustment', CONCAT(SID, ", ", SEmpID, ", ", SSalary));

	SET Message = "success";
	SELECT Message;
	CALL hrm_message_param3('1104803', 'SalaryAdjustment', 'delete', SID, SEmpID, '');
			

	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteTimesheetLeaveType`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteTimesheetLeaveType`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);
	DECLARE CheckExist INT DEFAULT(0);

	SELECT COUNT(Leave_TypeID) INTO CheckExist FROM hrm_timesheet_leave_type_employee WHERE Leave_TypeID = ID;

	IF CheckExist <=0 THEN
		SELECT Count(LeaveD_TypeID) INTO CheckExist FROM hrm_timesheet_leave_detail WHERE LeaveD_TypeID = ID;
	END IF;
	
	IF CheckExist <= 0 THEN

		DELETE FROM hrm_timesheet_leave_type WHERE LeaveType_ID = ID;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'Leave Type', ID);
	
		SET Message = "success";
		SELECT Message;
		CALL hrm_message('1101203', 'LeaveType', 'delete', ID);
	ELSE
		SET Message = "used";
		SELECT Message;
		CALL hrm_message('1101205', 'LeaveType', 'used', ID);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMDeleteUser`;
DELIMITER |
CREATE PROCEDURE `spHRMDeleteUser`(UserID varchar(255),ID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE Message VARCHAR(255);

	DELETE FROM ame_user WHERE var_id = ID AND var_id <> 'ADMIN';
	DELETE FROM ame_user_app WHERE var_id = ID;
	INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(UserID, 'delete', 'User', ID);
	
	SET Message = "success";
	SELECT Message;
	CALL hrm_message('1104403', 'User', 'delete', ID);
	
END |
