DELIMITER ;

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

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

		SELECT COUNT(*) INTO CheckUsed FROM ame_mt_emp e WHERE e.var_hrm_shift_id= SID;
		IF CheckUsed <= 0 THEN

			DELETE FROM hrm_timesheet_workshift WHERE Shift_ID = SID;

			DELETE FROM hrm_timesheet_workshift_detail WHERE Shift_ID = SID;

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

DROP PROCEDURE IF EXISTS `spHRMEfficiency`;
DELIMITER |
CREATE PROCEDURE `spHRMEfficiency`(IN ItemID Varchar(255))
    DETERMINISTIC
BEGIN
		SELECT e.EfficiencyName, e.EfficiencyInKhmer
		FROM hrm_efficiency e
		WHERE e.EfficiencyName LIKE ItemID OR e.EfficiencyInKhmer LIKE ItemID
		ORDER BY e.EfficiencyName;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMEfficiencyCount`;
DELIMITER |
CREATE PROCEDURE `spHRMEfficiencyCount`(Filter Varchar(255),IN ItemID Varchar(255))
    DETERMINISTIC
BEGIN
IF Filter = "Efficiency" THEN
	SELECT COUNT(e.EfficiencyName)
	FROM hrm_efficiency e
	WHERE e.EfficiencyName LIKE ItemID OR e.EfficiencyName LIKE ItemID;
ELSE
	SELECT COUNT(e.EfficiencyName)
	FROM hrm_efficiency e;
END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMEfficiencyOffset`;
DELIMITER |
CREATE PROCEDURE `spHRMEfficiencyOffset`(IN ID varchar(255))
    DETERMINISTIC
BEGIN
SET @RowIndex = -1;
SELECT RowIndex
FROM (SELECT @RowIndex:=@RowIndex + 1 As RowIndex,EfficiencyName FROM hrm_efficiency) AS tbl
WHERE  EfficiencyName = ID ;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMEfficiencySearch`;
DELIMITER |
CREATE PROCEDURE `spHRMEfficiencySearch`(Filter Varchar(255),ItemID Varchar(255), Limited INT(11),Offseted INT(11))
    DETERMINISTIC
BEGIN
	IF Filter = "Efficiency" THEN
		SELECT e.EfficiencyName, e.EfficiencyInKhmer
		FROM hrm_efficiency e
		WHERE e.EfficiencyName LIKE ItemID OR e.EfficiencyInKhmer LIKE ItemID
		LIMIT Limited OFFSET Offseted;
	ELSE
		SELECT e.EfficiencyName, e.EfficiencyInKhmer
		FROM hrm_efficiency e
		LIMIT Limited OFFSET Offseted;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMEmployeeHistory`;
DELIMITER |
CREATE PROCEDURE `spHRMEmployeeHistory`(EmpID varchar(255), Employee text, Statuss varchar(20), employeehistory text, OldType varchar(255), OldCreateDate varchar(20))
    DETERMINISTIC
BEGIN
	SET @SQL1 = CONCAT("UPDATE tblemployee SET ", Employee, " WHERE EmpID='", EmpID ,"'; ");
		PREPARE St FROM @SQL1;
		EXECUTE St;
		DEALLOCATE PREPARE St;
	CALL spHRMCheckUpdateSync('tblemployee', 'EmpID', EmpID, NULL, NULL, NULL, NULL); 
	IF Statuss = "add" THEN
		SET @SQL1 = CONCAT("INSERT INTO tblemployeehistory(EmpID,HistoryType,Type,CreateDate) VALUES(", employeehistory, "); ");
		PREPARE St FROM @SQL1;
		EXECUTE St;
		DEALLOCATE PREPARE St;
	ELSEIF Statuss = "update" THEN
		SET @SQL1 = CONCAT("UPDATE tblemployeehistory SET ", employeehistory, " WHERE EmpID = '", EmpID ,"' AND CreateDate = '", OldCreateDate ,"' AND HistoryType = 'Status' AND Type = '", OldType ,"'; ");
		PREPARE St FROM @SQL1;
		EXECUTE St;
		DEALLOCATE PREPARE St;
	END IF;
	CALL spHRMCheckInsertSync('tblemployeehistory', 'EmpID', EmpID, 'HistoryType', 'Status', NULL, NULL);
END |
DELIMITER ;

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

	SELECT a.Allowance_EmpID,a.Allowance_ID
	,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
	,al.Allowance_ID,al.Allowance_Name,al.Allowance_PayType,al.Allowance_PayAmount 
	FROM hrm_payroll_allowance_employee a
	INNER JOIN ame_mt_emp e ON a.Allowance_EmpID = e.var_id
	INNER JOIN hrm_payroll_allowance al ON a.Allowance_ID = al.Allowance_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.Allowance_EmpID = ID;

END |
DELIMITER ;

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

	SELECT Allowance_ID,Allowance_Name,Allowance_PayType,Allowance_PayAmount FROM hrm_payroll_allowance WHERE Allowance_ID = ID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetAttendance`;
DELIMITER |
CREATE PROCEDURE `spHRMGetAttendance`(UserID varchar(255), SDate Date, SEmpID varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 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_LateDuration,Att_LateDurationDeduct,Att_ABDurationDeduct, Att_Des
	,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_internal_id, '') AS Emp_InternalID
	FROM hrm_timesheet_attendance att
	INNER JOIN ame_mt_emp e ON att.Att_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 MONTH(att.Att_Date) = MONTH(SDate) AND YEAR(att.Att_Date) = YEAR(SDate) AND att.Att_EmpID = SEmpID ORDER BY att.Att_Date;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetAttendanceByDate`;
DELIMITER |
CREATE PROCEDURE `spHRMGetAttendanceByDate`(UserID varchar(255), SDate Date, SEmpID varchar(255))
    DETERMINISTIC
BEGIN
	SELECT 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_LateDuration,Att_LateDurationDeduct,Att_ABDurationDeduct, Att_Des
	,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_internal_id, '') AS Emp_InternalID
	FROM hrm_timesheet_attendance att
	INNER JOIN ame_mt_emp e ON att.Att_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 att.Att_Date = SDate AND att.Att_EmpID = SEmpID ORDER BY att.Att_Date;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetAttendanceSub`;
DELIMITER |
CREATE PROCEDURE `spHRMGetAttendanceSub`(Userid varchar(255))
    DETERMINISTIC
BEGIN
	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_id, '') AS 'PositionID', 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)
	ORDER BY e.var_id;

	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetAuthorisationApproveEmpID`;
DELIMITER |
CREATE PROCEDURE `spHRMGetAuthorisationApproveEmpID`(IN UserID varchar(255), IN SStatus varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE SID VARCHAR(255) DEFAULT('');
	SELECT u.var_empid INTO SID FROM ame_user u WHERE u.var_id = UserID;

	SELECT 
		al.Auth_ProcessID,
    al.Auth_ProcessName,
    al.Auth_ID, 
    al.Auth_GroupID,
    al.Auth_EmpID, 
    al.Auth_Status, 
    al.Auth_Edit,
    al.Auth_Date,
    al.EmpID,
    al.EmpName,
    al.EmpEmail,
    al.Emp_CompanyEmail, 
    al.Position, 
    al.PositionKhmer, 
    al.Position_Level, 
    al.UName,
    al.Auth_ProcessEmpID,
    CONCAT('',e.var_name) AS 'Auth_ProcessEmpName', al.Auth_TranStatus,
    fnHRMCheckAuthorisationApproved(al.Auth_ProcessID, al.Auth_ProcessName, al.Auth_ID) AS 'Auth_AmountApproved',
    fnHRMCheckAuthorisationApprove(al.Auth_ProcessID, al.Auth_ProcessName, al.Auth_ID) AS 'Auth_AmountApprove',
	  auth.Auth_ID,
    auth.Auth_Name,
    auth.Auth_Type,
    auth.Auth_AndOr,
    auth.Auth_Amount 

	FROM(

	SELECT Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_GroupID,Auth_EmpID,Auth_Status, 1 AS 'Auth_Edit', Auth_Date
	,IF(Auth_ProcessName='Deduction', d.Deduction_EmpID, IF(Auth_ProcessName='Leave', l.Leave_EmpID, IF(Auth_ProcessName='Overtime', o.Overtime_RequestBy, IF(Auth_ProcessName='Dayoff', df.Dayoff_EmpID, '')))) AS 'Auth_ProcessEmpID'
	,IF(Auth_ProcessName='Deduction', d.Deduction_Status, IF(Auth_ProcessName='Leave', l.Leave_Status, IF(Auth_ProcessName='Overtime', o.Overtime_Status, IF(Auth_ProcessName='Dayoff', df.Dayoff_Status, '')))) AS 'Auth_TranStatus',
	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_internal_id, '') AS Emp_InternalID
	FROM hrm_authorisation_approved ap 
	INNER JOIN hrm_authorisation_module m ON(LOWER(m.AM_ID) = LOWER(ap.Auth_ProcessName) AND LOWER(m.AM_APP) = 'hrm')
	LEFT JOIN hrm_payroll_deduction d ON ap.Auth_ProcessID = d.Deduction_ID
	LEFT JOIN hrm_timesheet_leave l ON ap.Auth_ProcessID = l.Leave_ID
	LEFT JOIN hrm_payroll_overtime o ON ap.Auth_ProcessID = o.Overtime_ID
	LEFT JOIN hrm_timesheet_dayoff df ON ap.Auth_ProcessID = df.Dayoff_ID
	INNER JOIN ame_mt_emp e ON ap.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 Auth_EmpID = SID
	) al

	INNER JOIN ame_mt_emp e ON e.var_id = al.Auth_ProcessEmpID
	-- 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_authorisation auth ON (auth.Auth_ID = al.Auth_ID)
	WHERE IF(LOWER(SStatus) = 'all',TRUE, IF(LOWER(SStatus) = 'requested', al.Auth_Status = 'requested' AND al.Auth_TranStatus = 'requested', IF(LOWER(SStatus) = 'approved', al.Auth_TranStatus = 'approved' OR al.Auth_Status = 'approved', al.Auth_Status = SStatus)))
	ORDER BY Auth_ProcessName, al.Auth_Date desc, al.Auth_Edit DESC, FIELD(al.Auth_Status, 'requested', 'approved', 'rejected', '');

-- IF(ap.Auth_ProcessName='Bonus' AND b.Bonus_Status='requested',1,expr3)

	
END |
DELIMITER ;

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

	DECLARE CheckUsed INT DEFAULT(0);

	SELECT Count(Auth_GroupID) INTO CheckUsed FROM hrm_authorisation_detail WHERE Auth_GroupID = ID;
	IF CheckUsed <= 0 THEN
		SELECT COUNT(*) INTO CheckUsed FROM hrm_authorisation_approved ap WHERE ap.Auth_GroupID = ID;
	END IF;

	SELECT a.AuthGroup_ID,a.AuthGroup_Name,a.AuthGroup_Description,IF(CheckUsed > 0, 1, 0) AS 'AuthGroup_Used' FROM hrm_authorisation_group a WHERE a.AuthGroup_ID = ID;

	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_id, '') AS 'PositionID', 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_authorisation_group_detail a 
	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)
	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 a.AuthGroup_ID = 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_id, '') AS 'PositionID', 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
	,gd.AuthGroup_EmpID
	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)
	LEFT JOIN hrm_authorisation_group_detail gd ON gd.AuthGroup_EmpID = e.var_id AND gd.AuthGroup_ID = ID
	GROUP BY e.var_id 
	ORDER BY e.var_id;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetAuthorisationGroupOffset`;
DELIMITER |
CREATE PROCEDURE `spHRMGetAuthorisationGroupOffset`(AuthOffset int)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);

	SELECT a.AuthGroup_ID INTO ID FROM hrm_authorisation_group a ORDER BY a.AuthGroup_ID LIMIT 1 OFFSET AuthOffset; 

	SELECT a.AuthGroup_ID,a.AuthGroup_Name,a.AuthGroup_Description FROM hrm_authorisation_group a WHERE a.AuthGroup_ID = ID;

	SELECT a.AuthGroup_ID,a.AuthGroup_EmpID FROM hrm_authorisation_group_detail a WHERE a.AuthGroup_ID = 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_internal_id, '') AS Emp_InternalID
	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)
	ORDER BY e.var_id;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetAuthorisationGroupSub`;
DELIMITER |
CREATE PROCEDURE `spHRMGetAuthorisationGroupSub`()
    DETERMINISTIC
BEGIN
	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_id, '') AS 'PositionID', 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)
	ORDER BY e.var_id;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetAuthorisationID`;
DELIMITER |
CREATE PROCEDURE `spHRMGetAuthorisationID`(ID varchar(255))
    DETERMINISTIC
BEGIN
	SELECT a.Auth_ID,a.Auth_Name,a.Auth_Type,a.Auth_AndOr,a.Auth_Amount,(SELECT IF(COUNT(*) > 0, 1, 0) FROM hrm_authorisation_approved ap WHERE ap.Auth_ID = a.Auth_ID) AS 'Auth_Used' FROM hrm_authorisation a WHERE a.Auth_ID = ID;

	SELECT a.Auth_ID,a.Auth_EmpID,a.Auth_GroupID,a.Auth_GroupAndOr,a.Auth_GroupAmount FROM hrm_authorisation_detail a WHERE a.Auth_ID = 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_id, '') AS 'PositionID', 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)
	ORDER BY e.var_id;

	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 "Auth_GroupAmount",(SELECT COUNT(ds.AuthGroup_ID) FROM hrm_authorisation_group_detail ds WHERE ds.AuthGroup_ID = a.AuthGroup_ID) as 'Count'
	FROM hrm_authorisation_group a
	LEFT JOIN hrm_authorisation_detail d ON(d.Auth_GroupID = a.AuthGroup_ID AND d.Auth_ID = ID)
	ORDER BY a.AuthGroup_ID DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetAuthorisationOffset`;
DELIMITER |
CREATE PROCEDURE `spHRMGetAuthorisationOffset`(AuthOffset int)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);

	SELECT a.Auth_ID INTO ID FROM hrm_authorisation a ORDER BY a.Auth_ID LIMIT 1 OFFSET AuthOffset; 

	SELECT a.Auth_ID,a.Auth_Name,a.Auth_Type,a.Auth_AndOr,a.Auth_Amount FROM hrm_authorisation a WHERE a.Auth_ID = ID;

	SELECT a.Auth_ID,a.Auth_EmpID,a.Auth_GroupID,a.Auth_GroupAndOr,a.Auth_GroupAmount FROM hrm_authorisation_detail a WHERE a.Auth_ID = 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_internal_id, '') AS Emp_InternalID 
	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);

	SELECT a.AuthGroup_ID,a.AuthGroup_Name,a.AuthGroup_Description FROM hrm_authorisation_group a ORDER BY a.AuthGroup_ID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetAuthorisationProcess`;
DELIMITER |
CREATE PROCEDURE `spHRMGetAuthorisationProcess`()
    DETERMINISTIC
BEGIN
		
	SELECT d.Setting_Name FROM hrm_setting d WHERE d.Setting_Type = "Authorisation" AND d.Setting_Value != "1" AND d.Setting_Value != "0";

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetAuthorisationSub`;
DELIMITER |
CREATE PROCEDURE `spHRMGetAuthorisationSub`()
    DETERMINISTIC
BEGIN
	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_id, '') AS 'PositionID', 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)
	ORDER BY e.var_id;

	SELECT a.AuthGroup_ID,a.AuthGroup_Name,a.AuthGroup_Description,(SELECT COUNT(d.AuthGroup_ID) FROM hrm_authorisation_group_detail d WHERE d.AuthGroup_ID = a.AuthGroup_ID) as 'Count' FROM hrm_authorisation_group a ORDER BY a.AuthGroup_ID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetAutoFP`;
DELIMITER |
CREATE PROCEDURE `spHRMGetAutoFP`(ID varchar(255))
    DETERMINISTIC
BEGIN
	SELECT AutoFP_ID,AutoFP_ShiftID FROM hrm_timesheet_auto_fingerprint WHERE AutoFP_ID = ID;
	
	SELECT AutoFP_ID,AutoFP_Day,AutoFP_In1,AutoFP_Out1,AutoFP_In2,AutoFP_Out2,AutoFP_In3,AutoFP_Out3,AutoFP_In4,AutoFP_Out4,AutoFP_In5,AutoFP_Out5
  FROM hrm_timesheet_auto_finger_detail WHERE AutoFP_ID = ID ORDER BY FIELD(AutoFP_Day, 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', '');

	SELECT Shift_ID,Shift_Name,Shift_Type,Shift_Description FROM hrm_timesheet_workshift b ORDER BY b.Shift_ID;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetAutoFPSub`;
DELIMITER |
CREATE PROCEDURE `spHRMGetAutoFPSub`(Userid varchar(255))
    DETERMINISTIC
BEGIN

	SELECT Shift_ID,Shift_Name,Shift_Type,Shift_Description	FROM hrm_timesheet_workshift b 
	ORDER BY b.Shift_ID;
END |
DELIMITER ;

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

	SELECT Bonus_ID,Bonus_Date,Bonus_Reason,Bonus_Description FROM hrm_payroll_bonus WHERE Bonus_ID = ID;

	SELECT Bonus_ID,Bonus_EmpID,Bonus_PayType,Bonus_PayAmount,Bonus_PayStatus
	,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_id, '') AS 'PositionID', 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_internal_id, '') AS Emp_InternalID
	FROM hrm_payroll_bonus_detail bd
	INNER JOIN ame_mt_emp e ON (bd.Bonus_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 Bonus_ID = ID
	ORDER BY e.var_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_id, '') AS 'PositionID', 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 Bonus_EmpID FROM hrm_payroll_bonus_detail WHERE Bonus_ID = ID)
	ORDER BY e.var_id;

	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_id, '') AS PositionID, 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 `spHRMGetBonusSub`;
DELIMITER |
CREATE PROCEDURE `spHRMGetBonusSub`()
    DETERMINISTIC
BEGIN
	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_id, '') AS 'PositionID', 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)
	ORDER BY e.var_id;

	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_id, '') AS PositionID, 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 `spHRMGetCheckAuthorisationApprove`;
DELIMITER |
CREATE PROCEDURE `spHRMGetCheckAuthorisationApprove`(IN UserID varchar(255), authProcessID varchar(255), authProcessName varchar(255), authID varchar(255), authGroupID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE SID VARCHAR(255) DEFAULT('');
	SELECT u.var_empid INTO SID FROM ame_user u WHERE u.var_id = UserID;

  SELECT al.Auth_ProcessID, al.Auth_ProcessName, al.Auth_ID, al.Auth_GroupID, al.Auth_EmpID, al.Auth_Status, al.Auth_Edit, al.Auth_Date, al.EmpID, al.EmpName, al.EmpEmail, al.Emp_CompanyEmail, al.Position, al.PositionKhmer, al.Position_Level, al.UName, al.Auth_ProcessEmpID, CONCAT('',e.var_name) AS 'Auth_ProcessEmpName', al.Auth_TranStatus, fnHRMCheckAuthorisationApproved(al.Auth_ProcessID, al.Auth_ProcessName, al.Auth_ID) AS 'Auth_AmountApproved', fnHRMCheckAuthorisationApprove(al.Auth_ProcessID, al.Auth_ProcessName, al.Auth_ID) AS 'Auth_AmountApprove',
	auth.Auth_ID,auth.Auth_Name,auth.Auth_Type,auth.Auth_AndOr,auth.Auth_Amount

 FROM(

	SELECT Auth_ProcessID,Auth_ProcessName,Auth_ID,Auth_GroupID,Auth_EmpID,Auth_Status, 1 AS 'Auth_Edit', Auth_Date
	,IF(Auth_ProcessName='Deduction', d.Deduction_EmpID, IF(Auth_ProcessName='Leave', l.Leave_EmpID, IF(Auth_ProcessName='Overtime', o.Overtime_RequestBy, IF(Auth_ProcessName='Dayoff', df.Dayoff_EmpID, '')))) AS 'Auth_ProcessEmpID'
	,IF(Auth_ProcessName='Deduction', d.Deduction_Status, IF(Auth_ProcessName='Leave', l.Leave_Status, IF(Auth_ProcessName='Overtime', o.Overtime_Status, IF(Auth_ProcessName='Dayoff', df.Dayoff_Status, '')))) AS 'Auth_TranStatus'
	,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_internal_id, '') AS Emp_InternalID
	FROM hrm_authorisation_approved ap 
	INNER JOIN hrm_authorisation_module m ON(LOWER(m.AM_ID) = LOWER(ap.Auth_ProcessName) AND LOWER(m.AM_APP) = 'hrm')
	LEFT JOIN hrm_payroll_deduction d ON ap.Auth_ProcessID = d.Deduction_ID
	LEFT JOIN hrm_timesheet_leave l ON ap.Auth_ProcessID = l.Leave_ID
	LEFT JOIN hrm_payroll_overtime o ON ap.Auth_ProcessID = o.Overtime_ID
	LEFT JOIN hrm_timesheet_dayoff df ON ap.Auth_ProcessID = df.Dayoff_ID
	INNER JOIN ame_mt_emp e ON ap.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 Auth_EmpID = SID AND ap.Auth_ProcessID = authProcessID AND ap.Auth_ProcessName = authProcessName 
	AND ap.Auth_ID = authID AND ap.Auth_GroupID = authGroupID

	) al
	INNER JOIN ame_mt_emp e ON e.var_id = al.Auth_ProcessEmpID
	LEFT JOIN hrm_authorisation auth ON (auth.Auth_ID = al.Auth_ID)
	ORDER BY al.Auth_Edit DESC, FIELD(al.Auth_Status, 'requested', 'approved', 'rejected', '');

-- IF(ap.Auth_ProcessName='Bonus' AND b.Bonus_Status='requested',1,expr3)

	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetCheckAuthorisationTranApproved`;
DELIMITER |
CREATE PROCEDURE `spHRMGetCheckAuthorisationTranApproved`(IN UserID varchar(255), SProID varchar(255), SProName varchar(255), SAuthID varchar(255), SAuthGroupID varchar(255))
    DETERMINISTIC
BEGIN
DECLARE PStatus VARCHAR(255);
DECLARE SEmpID VARCHAR(255);

IF SAuthGroupID = '' THEN
	SELECT (IF((SELECT COUNT(*) FROM hrm_authorisation_approved ap WHERE ap.Auth_ProcessID=SProID AND ap.Auth_Status = 'rejected')>0, 'rejected', 
	(SELECT IF(auth.Auth_AndOr='Or' AND COUNT(*)>0, 'approved', IF(auth.Auth_AndOr='And' AND COUNT(*)>=auth.Auth_Amount, 'approved', '')) FROM hrm_authorisation_approved ap WHERE ap.Auth_ProcessID=SProID AND ap.Auth_Status = 'approved'))) INTO PStatus 
	FROM hrm_authorisation auth WHERE auth.Auth_ID = SAuthID;
ELSE
	CALL spHRMCheckGroupAuthorisationApprove(SProID,SAuthID,PStatus);
END IF;

IF PStatus = 'approved' OR PStatus = 'rejected' THEN
	IF SProName = 'Overtime' THEN
		UPDATE hrm_payroll_overtime SET Overtime_Status = PStatus WHERE Overtime_ID = SProID;
	ELSEIF SProName = 'Deduction' THEN
		UPDATE hrm_payroll_deduction SET Deduction_Status = PStatus WHERE Deduction_ID = SProID;
	ELSEIF SProName = 'Leave' THEN
		UPDATE hrm_timesheet_leave SET Leave_Status = PStatus WHERE Leave_ID = SProID;
		SELECT Leave_EmpID INTO SEmpID FROM hrm_timesheet_leave WHERE Leave_ID = SProID LIMIT 1;
		call spHRMCheckGroupAuthorisationApprove(SProID, SEmpID); 
	ELSEIF SProName = 'Dayoff' THEN
		UPDATE hrm_timesheet_dayoff SET Dayoff_Status = PStatus WHERE Dayoff_ID = SProID;
		SELECT Dayoff_EmpID INTO SEmpID FROM hrm_timesheet_dayoff WHERE Dayoff_ID = SProID LIMIT 1;
		call spHRMCheckAddAttendanceLeave(SProID, SEmpID);

	ELSEIF SProName = 'Customer'  THEN
		IF PStatus = 'approved' THEN
			UPDATE crm_customer SET var_crm_approval = "Approved" WHERE var_id = SProID;
			UPDATE crm_contact SET CO_IsApproved = "Approved" WHERE CO_CustID = SProID;
			UPDATE crm_opportunity SET OP_IsApproved = "Approved" WHERE OP_CustID = SProID;

			INSERT INTO ame_mt_cus (var_id,var_name,var_name_other,var_name_con,var_tel1,var_tel2,var_fax,var_web,var_email,var_addr,var_desc,var_pricecode,var_groupid,var_accid,var_tax,var_term,var_pmttype,var_cur,var_img,var_addr1,var_addr2,var_addr3,var_addr4,var_addr5,var_addr6,var_addr7,dou_limit,int_msg,tin_so,tin_si ,tin_overcredit ,tin_overduedate ,tin_block ,tin_alertmsg ,tin_inactive ,var_create ,var_modify ,dat_create ,dat_modify ,var_crm_latitude ,var_crm_longitude ,var_crm_approval,var_crm_facebook ,var_crm_line ,var_crm_viber ,var_crm_whatapp ,var_crm_industry ,var_crm_type ,tin_editable ,var_authId) SELECT var_id,var_name,var_name_other,var_name_con,var_tel1,var_tel2,var_fax,var_web,var_email,var_addr,var_desc,var_pricecode,var_groupid,var_accid,var_tax,var_term,var_pmttype,var_cur,var_img,var_addr1,var_addr2,var_addr3,var_addr4,var_addr5,var_addr6,var_addr7,dou_limit,int_msg,tin_so,tin_si ,tin_overcredit ,tin_overduedate ,tin_block ,tin_alertmsg ,tin_inactive ,var_create ,var_modify ,dat_create ,dat_modify ,var_crm_latitude ,var_crm_longitude ,var_crm_approval,var_crm_facebook ,var_crm_line ,var_crm_viber ,var_crm_whatapp ,var_crm_industry ,var_crm_type ,tin_editable ,var_authId FROM crm_customer WHERE var_id = SProID;
		ELSEIF PStatus = 'rejected' THEN
			UPDATE crm_customer SET var_crm_approval = "Rejected" WHERE var_id = SProID;
			UPDATE crm_contact SET CO_IsApproved = "Rejected" WHERE CO_CustID = SProID;
			UPDATE crm_opportunity SET OP_IsApproved = "Rejected" WHERE OP_CustID = SProID;
		END IF;
	ELSEIF SProName = 'Material Request' THEN
			IF PStatus = 'approved' THEN
				UPDATE ats_materialrequest SET `Status` = "Approved",`Generated` = "Open", dat_approved = NOW() WHERE EntryNo = SProID;
			ELSEIF PStatus = 'rejected' THEN
				UPDATE ats_materialrequest SET `Status` = "Rejected", dat_approved = NOW() WHERE EntryNo = SProID;
			END IF;
	ELSEIF SProName = 'Sale Order' THEN
		 IF PStatus = 'approved' THEN
				UPDATE ame_ar_so SET ame_ar_so.`var_auth_status` = "Approved", ame_ar_so.dat_approved = NOW() WHERE ame_ar_so.var_id = SProID;
			ELSEIF PStatus = 'rejected' THEN
				UPDATE ame_ar_so SET ame_ar_so.`var_auth_status` = "Rejected", ame_ar_so.dat_approved = NOW() WHERE ame_ar_so.var_id = SProID;
			END IF;
	ELSEIF SProName = 'Quote' THEN
			 IF PStatus = 'approved' THEN
				UPDATE ame_ar_quo SET ame_ar_quo.`var_auth_status` = "Approved", ame_ar_quo.dat_approved = NOW() WHERE ame_ar_quo.var_id = SProID;
			ELSEIF PStatus = 'rejected' THEN
				UPDATE ame_ar_quo SET ame_ar_quo.`var_auth_status` = "Rejected", ame_ar_quo.dat_approved = NOW() WHERE ame_ar_quo.var_id = SProID;
			END IF;
	ELSEIF SProName = 'Temporary Credit' THEN
			 IF PStatus = 'approved' THEN
				UPDATE ame_mt_tem_tc SET ame_mt_tem_tc.`var_status` = "Approved", ame_mt_tem_tc.dat_da = NOW() WHERE ame_mt_tem_tc.var_id = SProID;
			ELSEIF PStatus = 'rejected' THEN
				UPDATE ame_mt_tem_tc SET `var_status` = "Rejected", ame_mt_tem_tc.dat_da = NOW() WHERE ame_mt_tem_tc.var_id = SProID;
			END IF;
	ELSEIF SProName = 'Over Due Date' THEN
			 IF PStatus = 'approved' THEN
				UPDATE ame_mt_tem_odd SET ame_mt_tem_odd.`var_status` = "Approved", dat_date = NOW() WHERE ame_mt_tem_odd.var_id = SProID;
			ELSEIF PStatus = 'rejected' THEN
				UPDATE ame_mt_tem_odd SET ame_mt_tem_odd.`var_status` = "Rejected", dat_date = NOW() WHERE ame_mt_tem_odd.var_id = SProID;
			END IF;
	ELSEIF SProName = 'Budget Requisition' THEN
			 IF PStatus = 'approved' THEN
				UPDATE crm_frm_budget SET crm_frm_budget.`approvalstatus` = "Approved", crm_frm_budget.approvaldate = NOW() WHERE crm_frm_budget.FrmID = SProID;
			ELSEIF PStatus = 'rejected' THEN
				UPDATE crm_frm_budget SET crm_frm_budget.`approvalstatus` = "Rejected", crm_frm_budget.approvaldate = NOW() WHERE crm_frm_budget.FrmID = SProID;
			END IF;
	ELSEIF SProName = 'General Requisition' THEN
			 IF PStatus = 'approved' THEN
				UPDATE crm_frm_general SET crm_frm_general.`ApprovalStatus` = "Approved", crm_frm_general.ApprovalDate = NOW() WHERE crm_frm_general.FrmID = SProID;
			ELSEIF PStatus = 'rejected' THEN
				UPDATE crm_frm_general SET crm_frm_general.`ApprovalStatus` = "Rejected", crm_frm_general.ApprovalDate = NOW() WHERE crm_frm_general.FrmID = SProID;
			END IF;
	END IF;
END IF;
	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetCompany`;
DELIMITER |
CREATE PROCEDURE `spHRMGetCompany`()
    DETERMINISTIC
BEGIN
	
	SELECT COALESCE(var_id, '') AS ComID
	,COALESCE(var_name2, '') AS ComName
	,COALESCE(var_name1,'') AS ComNameKh
	,COALESCE(var_logo1, '') AS Logo
	,COALESCE(var_logo1, '') AS Logo1
	,COALESCE(var_logo2, '') AS Logo2
	,COALESCE(var_addr1,'') AS ComAddKH
	,COALESCE(var_addr2,'') AS ComAddEn
	,COALESCE(var_tel1, '') AS Phone1
	,COALESCE(var_tel2, '') AS Phone2
	,COALESCE(var_email, '') AS Email
	,COALESCE(var_website, '') AS Website
	,COALESCE(var_fax, '') AS Fax
	,COALESCE(var_fax, '') AS Fax
 FROM ame_mt_com;

	SELECT COALESCE(var_name, '') AS ImagePath FROM ame_sys_config WHERE var_id = 'IMG_PATH_WEB';

END |
DELIMITER ;

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

	SELECT Currency_ID,Currency_Name,Currency_Placing,Currency_Rate,Currency_Description,Currency_Default FROM hrm_payroll_currency WHERE Currency_ID = ID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetDashboard`;
DELIMITER |
CREATE PROCEDURE `spHRMGetDashboard`(SUserID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE SEmpID 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);

	BEGIN
			DECLARE Cur CURSOR FOR
			SELECT SQL_CALC_FOUND_ROWS var_empid FROM ame_user WHERE var_id = SUserID 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';
	SELECT Deduct_Leave_Balance_Hourly;
	IF Deduct_Leave_Balance_Hourly = 'Half of Day' THEN
		SELECT lt.LeaveType_ID, lt.LeaveType_Name, fnHRMCheckLeaveBaanceRate(SEmpID, lt.LeaveType_BaseBalance, lt.LeaveType_AmountAllowed) AS 'AmountAllowed', fnHRMCheckLeaveBaanceRate(SEmpID, lt.LeaveType_BaseBalance, lt.LeaveType_AmountAllowed) - COALESCE(SUM(ld.Leave_Amount), 0) AS 'Balance',
		SUM(IF(LOWER(l.Leave_Status) = 'requested', ld.Leave_Amount, 0)) 'Pending', SUM(IF(LOWER(l.Leave_Status) = 'approved', ld.Leave_Amount, 0)) 'Taken'
		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 OR ld.LeaveD_ID IS NULL) 
		GROUP BY lt.LeaveType_ID
		ORDER BY lt.LeaveType_ID;
	ELSE
		SELECT lt.LeaveType_ID, lt.LeaveType_Name, fnHRMCheckLeaveBaanceRate(SEmpID, lt.LeaveType_BaseBalance, lt.LeaveType_AmountAllowed) AS 'AmountAllowed', fnHRMCheckLeaveBaanceRate(SEmpID, lt.LeaveType_BaseBalance, lt.LeaveType_AmountAllowed) - COALESCE(SUM(IF(LOWER(ld.LeaveD_Duration) = 'full day', ld.Leave_Total, 0)) + FLOOR(SUM(IF(LOWER(ld.LeaveD_Duration) = 'hourly', ld.Leave_Total, 0))/WorkHour) + IF(MOD(SUM(IF(LOWER(ld.LeaveD_Duration) = 'hourly', ld.Leave_Total, 0)), WorkHour) > 0, 1, 0), 0) AS 'Balance',
		IF(MOD(SUM(IF(LOWER(ld.LeaveD_Duration) = 'hourly', ld.Leave_Total, 0)), WorkHour) > 0, WorkHour - MOD(SUM(IF(LOWER(ld.LeaveD_Duration) = 'hourly', ld.Leave_Total, 0)), WorkHour), 0) AS 'Balance_H',
		SUM(IF(LOWER(l.Leave_Status) = 'requested' AND LOWER(ld.LeaveD_Duration) = 'full day', ld.Leave_Total, 0)) + FLOOR(SUM(IF(LOWER(l.Leave_Status) = 'requested' AND LOWER(ld.LeaveD_Duration) = 'hourly', ld.Leave_Total, 0))/WorkHour) 'Pending', 
		MOD(SUM(IF(LOWER(l.Leave_Status) = 'requested' AND LOWER(ld.LeaveD_Duration) = 'hourly', ld.Leave_Total, 0)), WorkHour) 'Pending_H', 
		SUM(IF(LOWER(l.Leave_Status) = 'approved' AND LOWER(ld.LeaveD_Duration) = 'full day', ld.Leave_Total, 0)) + FLOOR(SUM(IF(LOWER(l.Leave_Status) = 'approved' AND LOWER(ld.LeaveD_Duration) = 'hourly', ld.Leave_Total, 0))/WorkHour) 'Taken', 
		MOD(SUM(IF(LOWER(l.Leave_Status) = 'approved' AND LOWER(ld.LeaveD_Duration) = 'hourly', ld.Leave_Total, 0)), WorkHour) 'Taken_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 OR ld.LeaveD_ID IS NULL) 
		GROUP BY lt.LeaveType_ID
		ORDER BY lt.LeaveType_ID;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetDayoff`;
DELIMITER |
CREATE PROCEDURE `spHRMGetDayoff`(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 INTO CheckU FROM ame_user WHERE 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);

		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(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_internal_id, '') AS Emp_InternalID, 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 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, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, 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 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;
		
	
		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(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_internal_id, '') AS Emp_InternalID, 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 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, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, 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 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;
	
		CALL spHRMGetDayoffSub(userid);
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetDayoffSub`;
DELIMITER |
CREATE PROCEDURE `spHRMGetDayoffSub`(userid varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE CheckU VARCHAR(255) DEFAULT("");
	DECLARE SEmpID VARCHAR(255) DEFAULT("");
	
	SELECT var_hrm_utype INTO CheckU FROM ame_user WHERE var_id = userid; 
	
	IF CheckU = "ESS" THEN
		SELECT var_empid INTO SEmpID FROM ame_user WHERE var_id = userid;

		DELETE FROM hrm_temp_supervisor WHERE UID = userid AND Type = 'Dayoff';
		IF SEmpID != "" THEN
			INSERT INTO hrm_temp_supervisor(UID,EmpID,Type) VALUES (userid, SEmpID, 'Dayoff');
			CALL spHRMGetEmpInSuper(SEmpID,userid, 'Dayoff');
		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_id, '') AS 'PositionID', 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 = 'Dayoff')
		ORDER BY e.var_id;
	ELSE
		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_id, '') AS 'PositionID', 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)
		ORDER BY e.var_id;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetDeductionID`;
DELIMITER |
CREATE PROCEDURE `spHRMGetDeductionID`(ID varchar(255))
    DETERMINISTIC
BEGIN
		DECLARE SAuthID VARCHAR(255) DEFAULT("");

		SELECT Deduction_AuthID INTO SAuthID FROM hrm_payroll_deduction WHERE Deduction_ID = ID;
	
		SELECT Deduction_ID,Deduction_EmpID,Deduction_Date,Deduction_Reason,Deduction_Amount,Deduction_Description,Deduction_Status FROM hrm_payroll_deduction WHERE Deduction_ID = ID ;

		SELECT dd_id,dd_empid,dd_date,dd_amount,dd_status,dd_line FROM hrm_payroll_deduction_detail WHERE dd_id = ID ORDER BY dd_line;

		SELECT a.Auth_ID,a.Auth_Name,a.Auth_Type,a.Auth_AndOr,a.Auth_Amount, fnHRMCheckAuthorisationApproved(ID, 'Deduction', 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, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, 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 = "Deduction" 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, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, 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 = "Deduction" 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;
	
		CALL spHRMGetDeductionSub;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetDeductionSub`;
DELIMITER |
CREATE PROCEDURE `spHRMGetDeductionSub`()
    DETERMINISTIC
BEGIN
	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_id, '') AS 'PositionID', 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)
	ORDER BY e.var_id;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetEmpInSuper`;
DELIMITER |
CREATE PROCEDURE `spHRMGetEmpInSuper`(IN var_SuperID varchar(255), SUID varchar(255),SType varchar(255))
    DETERMINISTIC
BEGIN
		DECLARE v_finished INTEGER DEFAULT 0;
		DECLARE var_EmpID varchar(255) DEFAULT "";
		DEClARE CustID_Cursor CURSOR FOR SELECT var_id FROM ame_mt_emp WHERE var_hrm_supervisor = var_SuperID ORDER BY var_id;
		DECLARE CONTINUE HANDLER
		FOR NOT FOUND SET v_finished = 1;
		SET max_sp_recursion_depth=255;
		OPEN CustID_Cursor;
			GetCustID: LOOP
				FETCH CustID_Cursor INTO var_EmpID;
				IF v_finished = 1 THEN
					LEAVE GetCustID;
				END IF;
				INSERT INTO hrm_temp_supervisor(UID,EmpID,Type) VALUES (SUID, var_EmpID, SType);
				CALL spHRMGetEmpInSuper(var_EmpID, SUID, SType);
			END LOOP GetCustID;
		CLOSE CustID_Cursor;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetEmployeeAllowanceSub`;
DELIMITER |
CREATE PROCEDURE `spHRMGetEmployeeAllowanceSub`()
    DETERMINISTIC
BEGIN
	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_id, '') AS 'PositionID', 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)
	ORDER BY e.var_id;

	SELECT b.Allowance_ID,b.Allowance_Name,b.Allowance_PayType,b.Allowance_PayAmount FROM hrm_payroll_allowance b ORDER BY b.Allowance_ID;
END |
DELIMITER ;

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

	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_id, '') AS 'PositionID', 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 Allowance_EmpID FROM hrm_payroll_allowance_employee WHERE Allowance_ID = ID)
	ORDER BY e.var_id;

	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_id, '') AS PositionID, 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;

	SELECT Allowance_ID,Allowance_Name,Allowance_PayType,Allowance_PayAmount FROM hrm_payroll_allowance WHERE Allowance_ID = ID;

	SELECT ae.Allowance_EmpID,ae.Allowance_ID
	,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_id, '') AS 'PositionID', 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_allowance_employee ae
	INNER JOIN ame_mt_emp e ON ae.Allowance_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 ae.Allowance_ID = ID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetEmployeeAuthorisationByProcessName`;
DELIMITER |
CREATE PROCEDURE `spHRMGetEmployeeAuthorisationByProcessName`(ID varchar(255))
    DETERMINISTIC
BEGIN
	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_internal_id, '') AS Emp_InternalID,
	a.Emp_ID, a.Auth_Process, a.Auth_ID,
	auth.Auth_ID,auth.Auth_Name,auth.Auth_Type,auth.Auth_AndOr,auth.Auth_Amount
	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_authorisation_employee a ON a.Emp_ID = e.var_id AND IF(LOWER(ProcessName) = 'ame' OR LOWER(ProcessName) = 'hrm', LOWER(a.Auth_Process) IN((SELECT LOWER(AM_ID) FROM hrm_authorisation_module WHERE LOWER(AM_APP) = LOWER(ProcessName))), LOWER(a.Auth_Process) = LOWER(ProcessName))
	LEFT JOIN hrm_authorisation auth on auth.Auth_ID = a.Auth_ID
	ORDER BY e.var_id; 


END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetEmployeeAuthorisationOffset`;
DELIMITER |
CREATE PROCEDURE `spHRMGetEmployeeAuthorisationOffset`(AuthOffset int)
    DETERMINISTIC
BEGIN
	DECLARE ID VARCHAR(255);

	SELECT DISTINCT(a.Emp_ID) INTO ID FROM hrm_employee_authorisation a ORDER BY a.Emp_ID LIMIT 1 OFFSET AuthOffset; 

	SELECT a.Emp_ID, a.Auth_Process, a.Auth_ID FROM hrm_employee_authorisation a WHERE a.Emp_ID = ID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetEmployeeAuthorisationSub`;
DELIMITER |
CREATE PROCEDURE `spHRMGetEmployeeAuthorisationSub`()
    DETERMINISTIC
BEGIN
	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_internal_id, '') AS Emp_InternalID
	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)
	ORDER BY e.var_id;
	
	SELECT d.Setting_Name FROM hrm_setting d WHERE d.Setting_Type = "Authorisation" AND d.Setting_Value != "1" AND d.Setting_Value != "0";

	SELECT a.Auth_ID,a.Auth_Name,a.Auth_Type,a.Auth_AndOr,a.Auth_Amount FROM hrm_authorisation a ORDER BY a.Auth_ID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetEmployeeAuthorisationSubAdd`;
DELIMITER |
CREATE PROCEDURE `spHRMGetEmployeeAuthorisationSubAdd`(ProcessName varchar(255))
    DETERMINISTIC
BEGIN
	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_internal_id, '') AS Emp_InternalID
	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)
	WHERE e.var_id NOT IN(SELECT Emp_ID FROM hrm_authorisation_employee WHERE LOWER(Auth_Process) = ProcessName)
	ORDER BY e.var_id;
	
	SELECT d.Setting_Name FROM hrm_setting d WHERE d.Setting_Type = "Authorisation" AND d.Setting_Value != "1" AND d.Setting_Value != "0";

	SELECT a.Auth_ID,a.Auth_Name,a.Auth_Type,a.Auth_AndOr,a.Auth_Amount FROM hrm_authorisation a ORDER BY a.Auth_ID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetEmployeeBankID`;
DELIMITER |
CREATE PROCEDURE `spHRMGetEmployeeBankID`(ID varchar(255))
    DETERMINISTIC
BEGIN
	SELECT b.Bank_ID,b.Bank_Name,b.Bank_Description FROM hrm_emp_bank b WHERE b.Bank_ID = ID;

END |
DELIMITER ;

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

	SELECT Branch_ID,Branch_Name,Branch_Tel,Branch_Description,Branch_Address,Branch_HomeNo,Branch_Street,Branch_Village,Branch_District,Branch_Commune,Branch_City,Branch_State,Branch_Country FROM hrm_emp_branch WHERE Branch_ID = ID;

END |
DELIMITER ;

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

	SELECT Department_ID,Department_Name,Department_Description,Department_Parent FROM hrm_emp_department WHERE Department_ID = ID;

	SELECT Department_ID,Department_Name,Department_Description,Department_Parent FROM hrm_emp_department ORDER BY Department_ID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetEmployeeEmpID`;
DELIMITER |
CREATE PROCEDURE `spHRMGetEmployeeEmpID`(EmpID varchar(255))
    DETERMINISTIC
BEGIN
	SELECT COALESCE(e.var_id, '') AS EmpID
	,COALESCE(e.var_name, '') AS EmpName
	,COALESCE(e.var_name_other, '') AS EmpNameKh
	,COALESCE(e.var_hrm_salutation, '') AS Emp_Salutation
	,COALESCE(e.var_hrm_sex, '') AS EmpSex
	,COALESCE(e.var_hrm_marital_status, '') AS Emp_MaritalStatus
	,COALESCE(e.dat_hrm_dob, '0000-00-00') AS EmpDOB
	,COALESCE(e.var_cardid, '') AS EmpICNo
	,COALESCE(e.var_hrm_nssfid, '') AS Emp_NSSFID
	,COALESCE(e.var_hrm_passportid, '') AS Emp_PassportID
	,COALESCE(e.dat_hrm_visaexpire, '0000-00-00') AS Emp_VisaExpire
	,COALESCE(e.var_tel1, '') AS Emp_Tel1
	,COALESCE(e.var_tel2, '') AS Emp_Tel2
	,COALESCE(e.var_hrm_home_tel, '') AS Emp_HomeTel
	,COALESCE(e.var_hrm_company_tel, '') AS Emp_CompanyTel
	,COALESCE(e.var_hrm_emergency_person_name, '') AS Emp_EmergencyPersonName
	,COALESCE(e.var_hrm_emergency_relationship, '') AS Emp_EmergencyRelationship
	,COALESCE(e.var_hrm_emergency_tel, '') AS Emp_EmergencyTel
	,COALESCE(e.var_email, '') AS EmpEmail
	,COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail
	,COALESCE(e.var_web, '') AS EmpWebsite
	,COALESCE(e.var_addr, '') AS EmpAddress
	,COALESCE(e.var_hrm_address_kh, '') AS EmpAddressKh
	,COALESCE(e.var_posid, '') AS EmpPositionID
	,COALESCE(pos.var_name, '') AS EmpPosition
	,COALESCE(pos.var_addr, '') AS EmpPositionKh
	,COALESCE(e.var_img, '') AS EmpImg
	,COALESCE(e.var_hrm_status, '') AS EmpStatus
	,COALESCE(e.dat_hrm_date, '0000-00-00') AS EmpDate
	,COALESCE(e.var_hrm_supervisor, '') AS Supervisor
	,COALESCE(e.dat_hrm_contact_date, '0000-00-00') AS ContactDate
	,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_department_id, '') AS Emp_DepartmentID
	,COALESCE(e.var_hrm_branch_id, '') AS Emp_BranchID
	,COALESCE(e.var_hrm_nationality, '') AS Emp_Nationality
	,COALESCE(e.var_hrm_nationals, '') AS Emp_Nationals
	,COALESCE(e.var_hrm_bank_id, '') AS Emp_BankID
	,COALESCE(e.var_hrm_account_no, '') AS Emp_AccountNo
	,COALESCE(e.var_hrm_shift_type, '') AS Emp_ShiftType
	,COALESCE(e.var_hrm_shift_id, '') AS Emp_ShiftID
	,COALESCE(e.tin_hrm_allow_login, 0) AS Emp_AllowLogin
	,COALESCE(e.tin_hrm_notification_email, 0) AS Emp_NotificationEmail
	,COALESCE(e.dat_hrm_joindate, '0000-00-00') AS Emp_JoinDate
	,COALESCE(e.var_addr1, '') AS Emp_HomeNo
	,COALESCE(e.var_addr2, '') AS Emp_Street
	,COALESCE(e.var_addr3, '') AS Emp_Village
	,COALESCE(e.var_addr5, '') AS Emp_District
	,COALESCE(e.var_addr4, '') AS Emp_Commune
	,COALESCE(e.var_addr6, '') AS Emp_City
	,COALESCE(e.var_hrm_state, '') AS Emp_State
	,COALESCE(e.var_addr7, '') AS Emp_Country
	,COALESCE(e.var_hrm_permanent_address, '') AS Emp_PermanentAddress
	,COALESCE(e.var_hrm_permanent_home_no, '') AS Emp_PermanentHomeNo
	,COALESCE(e.var_hrm_permanent_street, '') AS Emp_PermanentStreet
	,COALESCE(e.var_hrm_permanent_village, '') AS Emp_PermanentVillage
	,COALESCE(e.var_hrm_permanent_district, '') AS Emp_PermanentDistrict
	,COALESCE(e.var_hrm_permanent_commune, '') AS Emp_PermanentCommune
	,COALESCE(e.var_hrm_permanent_city, '') AS Emp_PermanentCity
	,COALESCE(e.var_hrm_permanent_state, '') AS Emp_PermanentState
	,COALESCE(e.var_hrm_permanent_country, '') AS Emp_PermanentCountry
	,COALESCE(e.var_hrm_description, '') AS Emp_Description
	,COALESCE(e.var_hrm_fpid, '') AS Emp_FPID
	,COALESCE(pos.int_level, 0) AS Emp_PositionLevel
	,COALESCE(e.tin_hrm_late_deduction, 0) AS Emp_LateDeduction
	,COALESCE(e.tin_hrm_probation, 0) AS Emp_Probation
	,COALESCE(e.dat_hrm_enddateprobation, '0000-00-00') AS Emp_EndDateProbation
	,COALESCE(e.dat_hrm_date_status) AS Emp_DateStatus 
	from ame_mt_emp e 
	LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
	WHERE e.var_id = EmpID;
	
	SELECT s.Emp_ID,s.SocialCommunication,s.SocialCommunication_Value FROM hrm_employee_social_communication s WHERE s.Emp_ID = EmpID;

	SELECT sk.Emp_ID,sk.Skill_Name,sk.Skill_Level,sk.Skill_Description FROM hrm_employee_skill sk WHERE sk.Emp_ID = EmpID;

	SELECT l.Emp_ID,l.`Language`,l.Language_ReadLevel,l.Language_WriteLevel,l.Language_SpeakLevel,l.Language_UnderstandLevel,l.Language_Type FROM hrm_employee_language l WHERE l.Emp_ID = EmpID;

	SELECT ed.Emp_ID,ed.Edu_Name,ed.Edu_StartDate,ed.Edu_EndDate,ed.Edu_Degree,ed.Edu_School,ed.Edu_Major,ed.Edu_Description,ed.Edu_Attachfile FROM hrm_employee_education ed WHERE ed.Emp_ID = EmpID;

	SELECT ex.Emp_ID,ex.Ex_Position,ex.Ex_Company,ex.Ex_StartDate,ex.Ex_EndDate,ex.Ex_Description FROM hrm_employee_experience ex WHERE ex.Emp_ID = EmpID;

	SELECT f.Emp_ID,f.Fam_Name,f.Fam_NameKh,f.Fam_DOB,f.Fam_Relative,f.Fam_Occupation,f.Fam_Tel,f.Fam_TaxDeduct FROM hrm_employee_family f WHERE f.Emp_ID = EmpID; 
	
	SELECT c.Emp_ID,c.Con_Name,c.Con_Type,c.Con_StartDate,c.Con_EndDate,c.Con_Description,c.Con_EmpPosition,c.Con_EmpType,c.Con_EmpCategory,c.Con_EmpGrade,c.Con_EmpBranchID,c.Con_EmpDepartmentID,c.Con_AttachFile FROM hrm_employee_contract c WHERE c.Emp_ID = EmpID; 
	
	SELECT t.Emp_ID,t.Train_InstituteName,t.Train_Certificate,t.Train_Course,t.Train_StartDate,t.Train_EndDate,t.Train_Description,t.Train_AttachFile FROM hrm_employee_training t WHERE t.Emp_ID = EmpID;

	SELECT att.Emp_ID,att.Att_FileName,att.Att_FilePath FROM hrm_employee_attachment att WHERE att.Emp_ID = EmpID;

	SELECT m.Emp_ID,m.Mem_Name,m.Mem_Institute,m.Mem_GrantedOn,m.Mem_ValidThru,m.Mem_Type,m.Mem_Description,m.Mem_Attachfile FROM hrm_employee_membership m WHERE m.Emp_ID = EmpID;

	SELECT ins.Emp_ID,ins.Ins_InsuranceID,ins.Ins_StartDate,ins.Ins_ExpireDate,ins.Ins_Description,ins.Ins_SumInsured,ins.Ins_Premium FROM hrm_employee_insurance ins WHERE ins.Emp_ID = EmpID;

	SELECT COALESCE(u.var_name, '') AS UName, COALESCE(u.var_pwd, '') AS UPassword FROM ame_user u WHERE u.var_empid = EmpID; 

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetEmployeeIDAuthorisation`;
DELIMITER |
CREATE PROCEDURE `spHRMGetEmployeeIDAuthorisation`(ID varchar(255))
    DETERMINISTIC
BEGIN
	SELECT a.Emp_ID, a.Auth_Process, a.Auth_ID 
	,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_internal_id, '') AS Emp_InternalID
	,auth.Auth_ID,auth.Auth_Name,auth.Auth_Type,auth.Auth_AndOr,auth.Auth_Amount
	FROM hrm_authorisation_employee a
	INNER JOIN ame_mt_emp e ON a.Emp_ID = e.var_id
	INNER JOIN hrm_authorisation auth on auth.Auth_ID = a.Auth_ID
	INNER JOIN hrm_authorisation_module m ON LOWER(m.AM_ID) = LOWER(a.Auth_Process) AND LOWER(m.AM_APP) = 'hrm' 
	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.Emp_ID = ID;

END |
DELIMITER ;

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

	SELECT lte.Leave_EmpID,lte.Leave_TypeID
	,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_internal_id, '') AS Emp_InternalID
	,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_type_employee lte
	INNER JOIN ame_mt_emp e ON lte.Leave_EmpID = e.var_id
	INNER JOIN hrm_timesheet_leave_type lt ON lte.Leave_TypeID = lt.LeaveType_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 lte.Leave_EmpID = ID;

END |
DELIMITER ;

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

	SELECT Insurance_ID,Insurance_Name,Insurance_Company,Insurance_Type,Insurance_Description FROM hrm_emp_insurance WHERE Insurance_ID = ID;
	SELECT * FROM hrm_emp_insurance_type;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetEmployeeLeaveTypeSub`;
DELIMITER |
CREATE PROCEDURE `spHRMGetEmployeeLeaveTypeSub`()
    DETERMINISTIC
BEGIN

	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)
	ORDER BY e.var_id;

END |
DELIMITER ;

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

	DECLARE g VARCHAR(255) DEFAULT('');
	SELECT LeaveType_GenderRestriction INTO g FROM hrm_timesheet_leave_type WHERE LeaveType_ID = 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_id, '') AS 'PositionID', 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 Leave_EmpID FROM hrm_timesheet_leave_type_employee WHERE Leave_TypeID = ID) AND IF(LOWER(g) = 'all', TRUE, LOWER(e.var_hrm_sex) = LOWER(g))
	ORDER BY e.var_id;

	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_id, '') AS 'PositionID', 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;

	SELECT LeaveType_ID,LeaveType_Name,LeaveType_PayStatus,LeaveType_Year,LeaveType_AmountAllowed,LeaveType_GenderRestriction,LeaveType_PayType,LeaveType_PayAmount 
	FROM hrm_timesheet_leave_type b 
	WHERE b.LeaveType_ID = ID;

	SELECT lte.Leave_EmpID,lte.Leave_TypeID
	,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_id, '') AS 'PositionID', 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_type_employee lte
	INNER JOIN ame_mt_emp e ON lte.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 lte.Leave_TypeID = ID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetEmployeeLeaveTypeSubSearch`;
DELIMITER |
CREATE PROCEDURE `spHRMGetEmployeeLeaveTypeSubSearch`(ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE EmpSex VARCHAR(255);

	SELECT e.var_hrm_sex into EmpSex FROM ame_mt_emp e WHERE e.var_id = ID;
	IF LOWER(EmpSex) = "male" THEN
		SELECT LeaveType_ID,LeaveType_Name,LeaveType_PayStatus,LeaveType_Year,LeaveType_AmountAllowed,LeaveType_GenderRestriction,LeaveType_PayType,LeaveType_PayAmount FROM hrm_timesheet_leave_type b WHERE b.LeaveType_GenderRestriction <> "Female" AND LeaveType_ID NOT IN(SELECT COALESCE(Setting_Value, '') FROM hrm_setting WHERE Setting_Type = 'Leave' AND (Setting_Name = 'Leave_Type_Full_Day' OR Setting_Name = 'Leave_Type_Hourly')) ORDER BY b.LeaveType_ID;
	ELSEIF LOWER(EmpSex) = "female" THEN
		SELECT LeaveType_ID,LeaveType_Name,LeaveType_PayStatus,LeaveType_Year,LeaveType_AmountAllowed,LeaveType_GenderRestriction,LeaveType_PayType,LeaveType_PayAmount FROM hrm_timesheet_leave_type b WHERE b.LeaveType_GenderRestriction <> "Male" AND LeaveType_ID NOT IN(SELECT COALESCE(Setting_Value, '') FROM hrm_setting WHERE Setting_Type = 'Leave' AND (Setting_Name = 'Leave_Type_Full_Day' OR Setting_Name = 'Leave_Type_Hourly')) ORDER BY b.LeaveType_ID;
	END IF;
	

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetEmployeeOffset`;
DELIMITER |
CREATE PROCEDURE `spHRMGetEmployeeOffset`(EmpOffset int)
    DETERMINISTIC
BEGIN
	
	DECLARE EmpID VARCHAR(255);

	SELECT e.var_id INTO EmpID FROM ame_mt_emp e ORDER BY e.var_id LIMIT 1 OFFSET EmpOffset; 
	
	SELECT COALESCE(e.var_id, '') AS EmpID
	,COALESCE(e.var_name, '') AS EmpName
	,COALESCE(e.var_name_other, '') AS EmpNameKh
	,COALESCE(e.var_hrm_salutation, '') AS Emp_Salutation
	,COALESCE(e.var_hrm_sex, '') AS EmpSex
	,COALESCE(e.var_hrm_marital_status, '') AS Emp_MaritalStatus
	,COALESCE(e.dat_hrm_dob, '0000-00-00') AS EmpDOB
	,COALESCE(e.var_cardid, '') AS EmpICNo
	,COALESCE(e.var_hrm_nssfid, '') AS Emp_NSSFID
	,COALESCE(e.var_hrm_passportid, '') AS Emp_PassportID
	,COALESCE(e.dat_hrm_visaexpire, '0000-00-00') AS Emp_VisaExpire
	,COALESCE(e.var_tel1, '') AS Emp_Tel1
	,COALESCE(e.var_tel2, '') AS Emp_Tel2
	,COALESCE(e.var_hrm_home_tel, '') AS Emp_HomeTel
	,COALESCE(e.var_hrm_company_tel, '') AS Emp_CompanyTel
	,COALESCE(e.var_hrm_emergency_person_name, '') AS Emp_EmergencyPersonName
	,COALESCE(e.var_hrm_emergency_relationship, '') AS Emp_EmergencyRelationship
	,COALESCE(e.var_hrm_emergency_tel, '') AS Emp_EmergencyTel
	,COALESCE(e.var_email, '') AS EmpEmail
	,COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail
	,COALESCE(e.var_web, '') AS EmpWebsite
	,COALESCE(e.var_addr, '') AS EmpAddress
	,COALESCE(e.var_hrm_address_kh, '') AS EmpAddressKh
	,COALESCE(e.var_posid, '') AS EmpPositionID
	,COALESCE(pos.var_name, '') AS EmpPosition
	,COALESCE(pos.var_addr, '') AS EmpPositionKh
	,COALESCE(e.var_img, '') AS EmpImg
	,COALESCE(e.var_hrm_status, '') AS EmpStatus
	,COALESCE(e.dat_hrm_date, '0000-00-00') AS EmpDate
	,COALESCE(e.var_hrm_supervisor, '') AS Supervisor
	,COALESCE(e.dat_hrm_contact_date, '0000-00-00') AS ContactDate
	,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_department_id, '') AS Emp_DepartmentID
	,COALESCE(e.var_hrm_branch_id, '') AS Emp_BranchID
	,COALESCE(e.var_hrm_nationality, '') AS Emp_Nationality
	,COALESCE(e.var_hrm_nationals, '') AS Emp_Nationals
	,COALESCE(e.var_hrm_bank_id, '') AS Emp_BankID
	,COALESCE(e.var_hrm_account_no, '') AS Emp_AccountNo
	,COALESCE(e.var_hrm_shift_type, '') AS Emp_ShiftType
	,COALESCE(e.var_hrm_shift_id, '') AS Emp_ShiftID
	,COALESCE(e.tin_hrm_allow_login, 0) AS Emp_AllowLogin
	,COALESCE(e.tin_hrm_notification_email, 0) AS Emp_NotificationEmail
	,COALESCE(e.dat_hrm_joindate, '0000-00-00') AS Emp_JoinDate
	,COALESCE(e.var_addr1, '') AS Emp_HomeNo
	,COALESCE(e.var_addr2, '') AS Emp_Street
	,COALESCE(e.var_addr3, '') AS Emp_Village
	,COALESCE(e.var_addr5, '') AS Emp_District
	,COALESCE(e.var_addr4, '') AS Emp_Commune
	,COALESCE(e.var_addr6, '') AS Emp_City
	,COALESCE(e.var_hrm_state, '') AS Emp_State
	,COALESCE(e.var_addr7, '') AS Emp_Country
	,COALESCE(e.var_hrm_permanent_address, '') AS Emp_PermanentAddress
	,COALESCE(e.var_hrm_permanent_home_no, '') AS Emp_PermanentHomeNo
	,COALESCE(e.var_hrm_permanent_street, '') AS Emp_PermanentStreet
	,COALESCE(e.var_hrm_permanent_village, '') AS Emp_PermanentVillage
	,COALESCE(e.var_hrm_permanent_district, '') AS Emp_PermanentDistrict
	,COALESCE(e.var_hrm_permanent_commune, '') AS Emp_PermanentCommune
	,COALESCE(e.var_hrm_permanent_city, '') AS Emp_PermanentCity
	,COALESCE(e.var_hrm_permanent_state, '') AS Emp_PermanentState
	,COALESCE(e.var_hrm_permanent_country, '') AS Emp_PermanentCountry
	,COALESCE(e.var_hrm_description, '') AS Emp_Description
	,COALESCE(e.var_hrm_fpid, '') AS Emp_FPID
	,COALESCE(pos.int_level, 0) AS Emp_PositionLevel
	,COALESCE(e.tin_hrm_late_deduction, 0) AS Emp_LateDeduction
	,COALESCE(e.tin_hrm_probation, 0) AS Emp_Probation
	,COALESCE(e.dat_hrm_enddateprobation, '0000-00-00') AS Emp_EndDateProbation
	,COALESCE(e.dat_hrm_date_status) AS Emp_DateStatus 
	from ame_mt_emp e 
	LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
	WHERE e.var_id = EmpID;
	
	SELECT s.Emp_ID,s.SocialCommunication,s.SocialCommunication_Value FROM hrm_employee_social_communication s WHERE s.Emp_ID = EmpID;

	SELECT sk.Emp_ID,sk.Skill_Name,sk.Skill_Level,sk.Skill_Description FROM hrm_employee_skill sk WHERE sk.Emp_ID = EmpID;

	SELECT l.Emp_ID,l.`Language`,l.Language_ReadLevel,l.Language_WriteLevel,l.Language_SpeakLevel,l.Language_UnderstandLevel,l.Language_Type FROM hrm_employee_language l WHERE l.Emp_ID = EmpID;

	SELECT ed.Emp_ID,ed.Edu_Name,ed.Edu_StartDate,ed.Edu_EndDate,ed.Edu_Degree,ed.Edu_School,ed.Edu_Major,ed.Edu_Description,ed.Edu_Attachfile FROM hrm_employee_education ed WHERE ed.Emp_ID = EmpID;

	SELECT ex.Emp_ID,ex.Ex_Position,ex.Ex_Company,ex.Ex_StartDate,ex.Ex_EndDate,ex.Ex_Description FROM hrm_employee_experience ex WHERE ex.Emp_ID = EmpID;

	SELECT f.Emp_ID,f.Fam_Name,f.Fam_NameKh,f.Fam_DOB,f.Fam_Relative,f.Fam_Occupation,f.Fam_Tel,f.Fam_TaxDeduct FROM hrm_employee_family f WHERE f.Emp_ID = EmpID; 
	
	SELECT c.Emp_ID,c.Con_Name,c.Con_Type,c.Con_StartDate,c.Con_EndDate,c.Con_Description,c.Con_EmpPosition,c.Con_EmpType,c.Con_EmpCategory,c.Con_EmpGrade,c.Con_EmpBranchID,c.Con_EmpDepartmentID,c.Con_AttachFile FROM hrm_employee_contract c WHERE c.Emp_ID = EmpID; 
	
	SELECT t.Emp_ID,t.Train_InstituteName,t.Train_Certificate,t.Train_Course,t.Train_StartDate,t.Train_EndDate,t.Train_Description,t.Train_AttachFile FROM hrm_employee_training t WHERE t.Emp_ID = EmpID;

	SELECT att.Emp_ID,att.Att_FileName,att.Att_FilePath FROM hrm_employee_attachment att WHERE att.Emp_ID = EmpID;

	SELECT m.Emp_ID,m.Mem_Name,m.Mem_Institute,m.Mem_GrantedOn,m.Mem_ValidThru,m.Mem_Type,m.Mem_Description,m.Mem_Attachfile FROM hrm_employee_membership m WHERE m.Emp_ID = EmpID;

	SELECT ins.Emp_ID,ins.Ins_InsuranceID,ins.Ins_StartDate,ins.Ins_ExpireDate,ins.Ins_Description,ins.Ins_SumInsured,ins.Ins_Premium FROM hrm_employee_insurance ins WHERE ins.Emp_ID = EmpID;

	SELECT COUNT(*) 'Count' FROM ame_mt_emp;

	SELECT COALESCE(u.var_name, '') AS UName, COALESCE(u.var_pwd, '') AS UPassword FROM ame_user u WHERE u.var_empid = EmpID; 

END |
DELIMITER ;

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

	SELECT COALESCE(pos.var_id, '') AS PositionID, 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 
	WHERE pos.var_id = ID
	ORDER BY pos.var_id;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetEmployeeSub`;
DELIMITER |
CREATE PROCEDURE `spHRMGetEmployeeSub`()
    DETERMINISTIC
BEGIN

	SELECT b.Bank_ID,b.Bank_Name,b.Bank_Description FROM hrm_emp_bank b ORDER BY b.Bank_Name;

	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.Category_Name FROM hrm_emp_category b ORDER BY b.Category_Name;

	SELECT b.ContractType_Name FROM hrm_emp_contract_type b ORDER BY b.ContractType_Name;

	SELECT COALESCE(pos.var_id, '') AS PositionID, 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;

	SELECT b.Status_Name FROM hrm_emp_status b ORDER BY b.Status_Name;

	SELECT b.Type_Name FROM hrm_emp_type b ORDER BY b.Type_Name;

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

	SELECT b.MembershipType_Name FROM hrm_emp_membership_type b ORDER BY b.MembershipType_Name;

	SELECT l.Language_Name FROM hrm_emp_language l ORDER BY l.Language_Name;

	SELECT b.Level_Name FROM hrm_emp_level b ORDER BY b.Level_Name;

	SELECT b.InsuranceType_Name FROM hrm_emp_insurance_type b ORDER BY b.InsuranceType_Name;

	SELECT b.SocialCommunication_Name FROM hrm_emp_social_communication b ORDER BY b.SocialCommunication_Name;

	SELECT b.Nationnality_Name FROM hrm_emp_nationality b ORDER BY b.Nationnality_Name;

	SELECT b.Nationals_Name FROM hrm_emp_nationals b ORDER BY b.Nationals_Name;

	SELECT b.School_Name FROM hrm_emp_school b ORDER BY b.School_Name;

	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_id, '') AS 'PositionID', 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_internal_id, '') AS Emp_InternalID
	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)
	ORDER BY e.var_id;

	SELECT b.Shift_ID,b.Shift_Name FROM hrm_timesheet_workshift b WHERE b.Shift_Type = "Normal" ORDER BY b.Shift_ID;

	SELECT Insurance_ID,Insurance_Name,Insurance_Company,Insurance_Type,Insurance_Description FROM hrm_emp_insurance b ORDER BY b.Insurance_ID;

	SELECT b.Country_Name FROM hrm_location_country b ORDER BY b.Country_Name;

	SELECT COALESCE(var_id, '') AS UID FROM ame_user;

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

	SELECT COALESCE(var_id, '') AS UID FROM ame_user WHERE var_empid NOT IN(SELECT var_id FROM ame_mt_emp);

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetEmployeeSubUpdate`;
DELIMITER |
CREATE PROCEDURE `spHRMGetEmployeeSubUpdate`(EmpID varchar(255))
    DETERMINISTIC
BEGIN

	SELECT b.Bank_ID,b.Bank_Name,b.Bank_Description FROM hrm_emp_bank b ORDER BY b.Bank_Name;

	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.Category_Name FROM hrm_emp_category b ORDER BY b.Category_Name;

	SELECT b.ContractType_Name FROM hrm_emp_contract_type b ORDER BY b.ContractType_Name;

	SELECT COALESCE(pos.var_id, '') AS PositionID, 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;

	SELECT b.Status_Name FROM hrm_emp_status b ORDER BY b.Status_Name;

	SELECT b.Type_Name FROM hrm_emp_type b ORDER BY b.Type_Name;

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

	SELECT b.MembershipType_Name FROM hrm_emp_membership_type b ORDER BY b.MembershipType_Name;

	SELECT l.Language_Name FROM hrm_emp_language l ORDER BY l.Language_Name;

	SELECT b.Level_Name FROM hrm_emp_level b ORDER BY b.Level_Name;

	SELECT b.InsuranceType_Name FROM hrm_emp_insurance_type b ORDER BY b.InsuranceType_Name;

	SELECT b.SocialCommunication_Name FROM hrm_emp_social_communication b ORDER BY b.SocialCommunication_Name;

	SELECT b.Nationnality_Name FROM hrm_emp_nationality b ORDER BY b.Nationnality_Name;

	SELECT b.Nationals_Name FROM hrm_emp_nationals b ORDER BY b.Nationals_Name;

	SELECT b.School_Name FROM hrm_emp_school b ORDER BY b.School_Name;

	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_internal_id, '') AS Emp_InternalID
	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)
	ORDER BY e.var_id;

	SELECT b.Shift_ID,b.Shift_Name FROM hrm_timesheet_workshift b WHERE b.Shift_Type = "Normal" ORDER BY b.Shift_ID;

	SELECT Insurance_ID,Insurance_Name,Insurance_Company,Insurance_Type,Insurance_Description FROM hrm_emp_insurance b ORDER BY b.Insurance_ID;

	SELECT b.Country_Name FROM hrm_location_country b ORDER BY b.Country_Name;

	-- Employee-------------------------------------------------------

	SELECT COALESCE(e.var_id, '') AS EmpID
	,COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID
	,COALESCE(e.var_name, '') AS EmpName
	,COALESCE(e.var_name_other, '') AS EmpNameKh
	,COALESCE(e.var_hrm_salutation, '') AS Emp_Salutation
	,COALESCE(e.var_hrm_sex, '') AS EmpSex
	,COALESCE(e.var_hrm_marital_status, '') AS Emp_MaritalStatus
	,COALESCE(e.dat_hrm_dob, '0000-00-00') AS EmpDOB
	,COALESCE(e.var_cardid, '') AS EmpICNo
	,COALESCE(e.var_hrm_nssfid, '') AS Emp_NSSFID
	,COALESCE(e.var_hrm_passportid, '') AS Emp_PassportID
	,COALESCE(e.dat_hrm_visaexpire, '0000-00-00') AS Emp_VisaExpire
	,COALESCE(e.var_tel1, '') AS Emp_Tel1
	,COALESCE(e.var_tel2, '') AS Emp_Tel2
	,COALESCE(e.var_hrm_home_tel, '') AS Emp_HomeTel
	,COALESCE(e.var_hrm_company_tel, '') AS Emp_CompanyTel
	,COALESCE(e.var_hrm_emergency_person_name, '') AS Emp_EmergencyPersonName
	,COALESCE(e.var_hrm_emergency_relationship, '') AS Emp_EmergencyRelationship
	,COALESCE(e.var_hrm_emergency_tel, '') AS Emp_EmergencyTel
	,COALESCE(e.var_email, '') AS EmpEmail
	,COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail
	,COALESCE(e.var_web, '') AS EmpWebsite
	,COALESCE(e.var_addr, '') AS EmpAddress
	,COALESCE(e.var_hrm_address_kh, '') AS EmpAddressKh
	,COALESCE(pos.var_id, '') AS EmpPositionID
	,COALESCE(e.var_img, '') AS EmpImg
	,COALESCE(e.var_hrm_status, '') AS EmpStatus
	,COALESCE(e.dat_hrm_date, '0000-00-00') AS EmpDate
	,COALESCE(e.var_hrm_supervisor, '') AS Supervisor
	,COALESCE(e.dat_hrm_contact_date, '0000-00-00') AS ContactDate
	,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_department_id, '') AS Emp_DepartmentID
	,COALESCE(e.var_hrm_branch_id, '') AS Emp_BranchID
	,COALESCE(e.var_hrm_nationality, '') AS Emp_Nationality
	,COALESCE(e.var_hrm_nationals, '') AS Emp_Nationals
	,COALESCE(e.var_hrm_bank_id, '') AS Emp_BankID
	,COALESCE(e.var_hrm_account_no, '') AS Emp_AccountNo
	,COALESCE(e.var_hrm_shift_type, '') AS Emp_ShiftType
	,COALESCE(e.var_hrm_shift_id, '') AS Emp_ShiftID
	,COALESCE(e.tin_hrm_allow_login, 0) AS Emp_AllowLogin
	,COALESCE(e.tin_hrm_notification_email, 0) AS Emp_NotificationEmail
	,COALESCE(e.dat_hrm_joindate, '0000-00-00') AS Emp_JoinDate
	,COALESCE(e.var_addr1, '') AS Emp_HomeNo
	,COALESCE(e.var_addr2, '') AS Emp_Street
	,COALESCE(e.var_addr3, '') AS Emp_Village
	,COALESCE(e.var_addr5, '') AS Emp_District
	,COALESCE(e.var_addr4, '') AS Emp_Commune
	,COALESCE(e.var_addr6, '') AS Emp_City
	,COALESCE(e.var_hrm_state, '') AS Emp_State
	,COALESCE(e.var_addr7, '') AS Emp_Country
	,COALESCE(e.var_hrm_permanent_address, '') AS Emp_PermanentAddress
	,COALESCE(e.var_hrm_permanent_home_no, '') AS Emp_PermanentHomeNo
	,COALESCE(e.var_hrm_permanent_street, '') AS Emp_PermanentStreet
	,COALESCE(e.var_hrm_permanent_village, '') AS Emp_PermanentVillage
	,COALESCE(e.var_hrm_permanent_district, '') AS Emp_PermanentDistrict
	,COALESCE(e.var_hrm_permanent_commune, '') AS Emp_PermanentCommune
	,COALESCE(e.var_hrm_permanent_city, '') AS Emp_PermanentCity
	,COALESCE(e.var_hrm_permanent_state, '') AS Emp_PermanentState
	,COALESCE(e.var_hrm_permanent_country, '') AS Emp_PermanentCountry
	,COALESCE(e.var_hrm_description, '') AS Emp_Description
	,COALESCE(e.var_hrm_fpid, '') AS Emp_FPID
	,COALESCE(pos.int_level, 0) AS Emp_PositionLevel
	,COALESCE(e.tin_hrm_late_deduction, 0) AS Emp_LateDeduction
	,COALESCE(e.tin_hrm_probation, 0) AS Emp_Probation
	,COALESCE(e.dat_hrm_enddateprobation, '0000-00-00') AS Emp_EndDateProbation
	,COALESCE(e.dat_hrm_date_status) AS Emp_DateStatus 
	from ame_mt_emp e 
	LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
	WHERE e.var_id = EmpID;
	
	SELECT s.Emp_ID,s.SocialCommunication,s.SocialCommunication_Value,s.SocailCommunication_AutoID FROM hrm_employee_social_communication s WHERE s.Emp_ID = EmpID;

	SELECT sk.Emp_ID,sk.Skill_Name,sk.Skill_Level,sk.Skill_Description,sk.Skill_AutoID FROM hrm_employee_skill sk WHERE sk.Emp_ID = EmpID;

	SELECT l.Emp_ID,l.`Language`,l.Language_ReadLevel,l.Language_WriteLevel,l.Language_SpeakLevel,l.Language_UnderstandLevel,l.Language_Type,l.Language_AutoID FROM hrm_employee_language l WHERE l.Emp_ID = EmpID;

	SELECT ed.Emp_ID,ed.Edu_Name,ed.Edu_StartDate,ed.Edu_EndDate,ed.Edu_Degree,ed.Edu_School,ed.Edu_Major,ed.Edu_Description,ed.Edu_Attachfile,ed.Edu_AutoID FROM hrm_employee_education ed WHERE ed.Emp_ID = EmpID;

	SELECT ex.Emp_ID,ex.Ex_Position,ex.Ex_Company,ex.Ex_StartDate,ex.Ex_EndDate,ex.Ex_Description,ex.Ex_AutoID FROM hrm_employee_experience ex WHERE ex.Emp_ID = EmpID;

	SELECT f.Emp_ID,f.Fam_Name,f.Fam_NameKh,f.Fam_DOB,f.Fam_Relative,f.Fam_Occupation,f.Fam_Tel,f.Fam_TaxDeduct,f.Fam_AutoID FROM hrm_employee_family f WHERE f.Emp_ID = EmpID; 
	
	SELECT c.Emp_ID,c.Con_Name,c.Con_Type,c.Con_StartDate,c.Con_EndDate,c.Con_Description,c.Con_EmpPosition,c.Con_EmpType,c.Con_EmpCategory,c.Con_EmpGrade,c.Con_EmpBranchID,c.Con_EmpDepartmentID,c.Con_AttachFile,c.Con_AutoID FROM hrm_employee_contract c WHERE c.Emp_ID = EmpID; 
	
	SELECT t.Emp_ID,t.Train_InstituteName,t.Train_Certificate,t.Train_Course,t.Train_StartDate,t.Train_EndDate,t.Train_Description,t.Train_AttachFile,t.Train_AutoID FROM hrm_employee_training t WHERE t.Emp_ID = EmpID;

	SELECT att.Emp_ID,att.Att_FileName,att.Att_FilePath,att.MainID FROM hrm_employee_attachment att WHERE att.Emp_ID = EmpID;

	SELECT m.Emp_ID,m.Mem_Name,m.Mem_Institute,m.Mem_GrantedOn,m.Mem_ValidThru,m.Mem_Type,m.Mem_Description,m.Mem_Attachfile,m.Mem_AutoID FROM hrm_employee_membership m WHERE m.Emp_ID = EmpID;

	SELECT ins.Emp_ID,ins.Ins_InsuranceID,ins.Ins_StartDate,ins.Ins_ExpireDate,ins.Ins_Description,ins.Ins_SumInsured,ins.Ins_Premium,Ins_AutoID FROM hrm_employee_insurance ins WHERE ins.Emp_ID = EmpID;

	SELECT COALESCE(u.var_id, '') AS UID, COALESCE(u.var_name, '') AS UName, COALESCE(u.var_pwd, '') AS UPassword FROM ame_user u WHERE u.var_empid = EmpID;

	-- Get UID To CHECK

	SELECT COALESCE(var_id, '') AS UID, COALESCE(var_empid, '') AS EmpID FROM ame_user;

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

	-- User Not Assign
	SELECT COALESCE(var_id, '') AS UID FROM ame_user WHERE COALESCE(var_empid, '') NOT IN(SELECT var_id FROM ame_mt_emp);

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetFile`;
DELIMITER |
CREATE PROCEDURE `spHRMGetFile`(IN fileName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Path text;
	DECLARE L BIGINT DEFAULT(1);
	
	SELECT Setting_Value INTO Path FROM hrm_setting WHERE Setting_Type='Path' AND Setting_Name = 'File_Path'; 
	SET Path = CONCAT(Path , "/", fileName);
	-- SELECT COALESCE(MAX(File_Line) + 1, 1) INTO L FROM hrm_save_file_temp;
	-- INSERT INTO hrm_save_file_temp(File_Name,File_Data,File_Line) VALUES(Path,LOAD_FILE(Path),L);
	SELECT LOAD_FILE(Path) AS "File";
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetFilePath`;
DELIMITER |
CREATE PROCEDURE `spHRMGetFilePath`()
    DETERMINISTIC
BEGIN
	SELECT COALESCE(var_name, '') AS ImagePath FROM ame_sys_config WHERE var_id = 'IMG_PATH_WEB';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetFingerIDByInternalID`;
DELIMITER |
CREATE PROCEDURE `spHRMGetFingerIDByInternalID`(InternalID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE fpid VARCHAR(255) DEFAULT('');
		BEGIN
			DECLARE Done_Over INTEGER DEFAULT 0;
			DECLARE Cur_Over CURSOR FOR SELECT SQL_CALC_FOUND_ROWS var_hrm_fpid FROM ame_mt_emp WHERE var_hrm_internal_id = InternalID;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET Done_Over = 1;
			OPEN Cur_Over;
				SET @R = FOUND_ROWS();
				IF @R > 0 THEN FETCH Cur_Over INTO fpid; END IF;
			CLOSE Cur_Over;
		END;
	SELECT fpid;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetFingerPrint`;
DELIMITER |
CREATE PROCEDURE `spHRMGetFingerPrint`(SUserID varchar(255), SEmp Text, SFDate varchar(255), STDate varchar(255))
    DETERMINISTIC
BEGIN
	
	SET @SQL1 = CONCAT("SELECT fp_id, fp_date, fp_punch1, fp_punch2, fp_punch3, fp_punch4, fp_punch5, fp_punch6, fp_punch7, fp_punch8, fp_punch9, fp_punch10,
	COALESCE(e.var_id, '') AS empid, COALESCE(e.var_name, '') AS empname,COALESCE(e.var_hrm_internal_id, '') AS emp_internalid
	FROM hrm_timesheet_fingerprint fp
	LEFT JOIN ame_mt_emp e ON(fp.fp_id = e.var_id)
	WHERE e.var_id IN(", SEmp,") AND (fp_date BETWEEN '", SFDate,"' AND '", STDate,"')
	ORDER BY e.var_id, fp.fp_date;");
	PREPARE St FROM @SQL1;
	EXECUTE St;
	DEALLOCATE PREPARE St;
END |
DELIMITER ;

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

	SELECT Holiday_ID,Holiday_Name,Holiday_Type,Holiday_Duration,Holiday_StartDate,Holiday_EndDate,Holiday_Description
	FROM hrm_timesheet_holiday WHERE Holiday_ID = ID;

	SELECT HolidayD_ID,HolidayD_Status,HolidayD_BranchID,HolidayD_DepartmentID
	FROM hrm_timesheet_holiday_detail WHERE HolidayD_ID = ID ORDER BY HolidayD_Index;

	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,
	(SELECT GROUP_CONCAT(DISTINCT d.Department_ID, '!@#$%', d.Department_Name, '!@#$%', d.Department_Description, '!@#$%', d.Department_Parent SEPARATOR ';') FROM ame_mt_emp e LEFT JOIN hrm_emp_department d ON(e.var_hrm_department_id = d.Department_ID) WHERE e.var_hrm_branch_id = b.Branch_ID) AS 'SubBranch'
	FROM hrm_emp_branch b ORDER BY b.Branch_ID;
	
	SELECT Department_ID, Department_Name, Department_Description, Department_Parent FROM hrm_emp_department;
END |
DELIMITER ;

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

	SET @SQL1 = CONCAT("SELECT s.Salary_EmpID,s.Salary_PayrollID,s.Salary_Type,", REPLACE(SK,'TempSA','s.Salary_Amount'), " AS 'Salary_Amount',s.Salary_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_internal_id, '') AS Emp_InternalID
	FROM hrm_payroll_salary s INNER JOIN ame_mt_emp e ON s.Salary_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 s.Salary_EmpID = ", ID, " ORDER BY s.Salary_Line DESC LIMIT 1;");
	PREPARE St FROM @SQL1;
	EXECUTE St;
	DEALLOCATE PREPARE St;

	

	SELECT b.Payroll_ID,b.Payroll_Name,b.Payroll_Type,b.Payroll_StartDate,b.Payroll_LastSubmitDate,b.Payroll_SubmitDate FROM hrm_payroll b ORDER BY b.Payroll_ID;
	

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetLeaveID`;
DELIMITER |
CREATE PROCEDURE `spHRMGetLeaveID`(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 l.Leave_EmpID IN(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 (ld.LeaveD_ID IN(SELECT RecordID FROM hrm_log WHERE RecordID = ID AND FrmSysName = "Leave" AND ActionType = "insert" AND UID = userid) OR LeaveD_ID IN(SELECT DISTINCT Leave_ID FROM hrm_timesheet_leave WHERE Leave_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 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 ;

		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, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, 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, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, 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 `spHRMGetLeaveSub`;
DELIMITER |
CREATE PROCEDURE `spHRMGetLeaveSub`(userid varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE CheckU VARCHAR(255) DEFAULT("");
	DECLARE SEmpID VARCHAR(255) DEFAULT("");
	SELECT u.var_hrm_utype, u.var_empid INTO CheckU, SEmpID FROM ame_user u WHERE u.var_id = userid;

	IF CheckU = "ESS" THEN

		DELETE FROM hrm_temp_supervisor WHERE UID = userid AND Type = 'Leave';
		IF SEmpID != "" THEN
			INSERT INTO hrm_temp_supervisor(UID,EmpID,Type) VALUES (userid, SEmpID, 'Leave');
			CALL spHRMGetEmpInSuper(SEmpID,userid, 'Leave');
		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_id, '') AS 'PositionID', 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 = 'Leave')
		ORDER BY e.var_id;
	ELSE
		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_id, '') AS 'PositionID', 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)
		ORDER BY e.var_id;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetLeaveSubSearch`;
DELIMITER |
CREATE PROCEDURE `spHRMGetLeaveSubSearch`(ID varchar(255), SYear int, SDuration varchar(255))
    DETERMINISTIC
BEGIN
DECLARE TypeIDFullDay VARCHAR(255);
DECLARE TypeIDHourly VARCHAR(255);
DECLARE CheckExist INT DEFAULT(0);
	
SELECT Setting_Value INTO TypeIDFullDay FROM hrm_setting WHERE Setting_Type = "Leave" AND Setting_Name = "Leave_Type_Full_Day";
SELECT Setting_Value INTO TypeIDHourly FROM hrm_setting WHERE Setting_Type = "Leave" AND Setting_Name = "Leave_Type_Hourly";
IF LOWER(SDuration) = "full day" THEN
	-- Check Full Day
	IF TypeIDFullDay != "" OR !ISNULL(TypeIDFullDay) THEN

		SELECT COUNT(*) INTO CheckExist FROM hrm_timesheet_leave_type b INNER JOIN hrm_timesheet_leave_type_employee e ON(b.LeaveType_ID = e.Leave_TypeID) WHERE e.Leave_EmpID = ID AND (b.LeaveType_Year = SYear OR b.LeaveType_Year = 0) AND b.LeaveType_ID = TypeIDFullDay;
		IF CheckExist > 0 THEN

			SELECT LeaveType_ID,LeaveType_Name,LeaveType_PayStatus,LeaveType_Year,LeaveType_AmountAllowed,LeaveType_GenderRestriction,LeaveType_PayType,LeaveType_PayAmount
			FROM hrm_timesheet_leave_type b
			INNER JOIN hrm_timesheet_leave_type_employee e on(b.LeaveType_ID = e.Leave_TypeID)
			WHERE (b.LeaveType_Year = SYear OR (b.LeaveType_Year = 0 AND LOWER(b.LeaveType_PayType) IN('fixed dialy','percent dialy','dialy rate'))) AND e.Leave_EmpID = ID
			GROUP BY b.LeaveType_ID
			ORDER BY b.LeaveType_ID;

		ELSE

			SELECT * FROM (

				SELECT LeaveType_ID,LeaveType_Name,LeaveType_PayStatus,LeaveType_Year,LeaveType_AmountAllowed,LeaveType_GenderRestriction,LeaveType_PayType,LeaveType_PayAmount
				FROM hrm_timesheet_leave_type b
				INNER JOIN hrm_timesheet_leave_type_employee e on(b.LeaveType_ID = e.Leave_TypeID)
				WHERE (b.LeaveType_Year = SYear OR (b.LeaveType_Year = 0 AND LOWER(b.LeaveType_PayType) IN('fixed dialy','percent dialy','dialy rate'))) AND e.Leave_EmpID = ID
				GROUP BY b.LeaveType_ID
				
				UNION

				SELECT LeaveType_ID,LeaveType_Name,LeaveType_PayStatus,LeaveType_Year,LeaveType_AmountAllowed,LeaveType_GenderRestriction,LeaveType_PayType,LeaveType_PayAmount
				FROM hrm_timesheet_leave_type b
				WHERE b.LeaveType_ID = TypeIDFullDay
				GROUP BY b.LeaveType_ID	
				
			) al ORDER BY al.LeaveType_ID;
		END IF;

	ELSE

		SELECT LeaveType_ID,LeaveType_Name,LeaveType_PayStatus,LeaveType_Year,LeaveType_AmountAllowed,LeaveType_GenderRestriction,LeaveType_PayType,LeaveType_PayAmount
		FROM hrm_timesheet_leave_type b
		INNER JOIN hrm_timesheet_leave_type_employee e on(b.LeaveType_ID = e.Leave_TypeID)
		WHERE (b.LeaveType_Year = SYear OR (b.LeaveType_Year = 0 AND LOWER(b.LeaveType_PayType) IN('fixed dialy','percent dialy','dialy rate'))) AND e.Leave_EmpID = ID
		GROUP BY b.LeaveType_ID
		ORDER BY b.LeaveType_ID;
	END IF;

ELSE
	-- Check Hourly
	IF TypeIDHourly != "" OR !ISNULL(TypeIDHourly) THEN
		SELECT COUNT(*) INTO CheckExist FROM hrm_timesheet_leave_type b INNER JOIN hrm_timesheet_leave_type_employee e ON(b.LeaveType_ID = e.Leave_TypeID) WHERE e.Leave_EmpID = ID AND (b.LeaveType_Year = SYear OR b.LeaveType_Year = 0) AND b.LeaveType_ID = TypeIDHourly;
		IF CheckExist > 0 THEN
			SELECT LeaveType_ID,LeaveType_Name,LeaveType_PayStatus,LeaveType_Year,LeaveType_AmountAllowed,LeaveType_GenderRestriction,LeaveType_PayType,LeaveType_PayAmount
			FROM hrm_timesheet_leave_type b
			INNER JOIN hrm_timesheet_leave_type_employee e on(b.LeaveType_ID = e.Leave_TypeID)
			WHERE (b.LeaveType_Year = SYear OR (b.LeaveType_Year = 0 AND LOWER(b.LeaveType_PayType) IN('fixed hourly','percent hourly','hourly rate'))) AND e.Leave_EmpID = ID
			GROUP BY b.LeaveType_ID
			ORDER BY b.LeaveType_ID;

		ELSE

			SELECT * FROM (

				SELECT LeaveType_ID,LeaveType_Name,LeaveType_PayStatus,LeaveType_Year,LeaveType_AmountAllowed,LeaveType_GenderRestriction,LeaveType_PayType,LeaveType_PayAmount
				FROM hrm_timesheet_leave_type b
				INNER JOIN hrm_timesheet_leave_type_employee e on(b.LeaveType_ID = e.Leave_TypeID)
				WHERE (b.LeaveType_Year = SYear OR (b.LeaveType_Year = 0 AND LOWER(b.LeaveType_PayType) IN('fixed hourly','percent hourly','hourly rate'))) AND e.Leave_EmpID = ID
				GROUP BY b.LeaveType_ID
				
				UNION

				SELECT LeaveType_ID,LeaveType_Name,LeaveType_PayStatus,LeaveType_Year,LeaveType_AmountAllowed,LeaveType_GenderRestriction,LeaveType_PayType,LeaveType_PayAmount
				FROM hrm_timesheet_leave_type b
				WHERE b.LeaveType_ID = TypeIDHourly
				GROUP BY b.LeaveType_ID	
				
			) al ORDER BY al.LeaveType_ID;
		END IF;

	ELSE

		SELECT LeaveType_ID,LeaveType_Name,LeaveType_PayStatus,LeaveType_Year,LeaveType_AmountAllowed,LeaveType_GenderRestriction,LeaveType_PayType,LeaveType_PayAmount
		FROM hrm_timesheet_leave_type b
		INNER JOIN hrm_timesheet_leave_type_employee e on(b.LeaveType_ID = e.Leave_TypeID)
		WHERE (b.LeaveType_Year = SYear OR (b.LeaveType_Year = 0 AND LOWER(b.LeaveType_PayType) IN('fixed hourly','percent hourly','hourly rate'))) AND e.Leave_EmpID = ID
		GROUP BY b.LeaveType_ID
		ORDER BY b.LeaveType_ID;
	END IF;

END IF;
-- (b.LeaveType_Year = SYear OR (b.LeaveType_Year = 0 AND LOWER(b.LeaveType_PayType) = 'hourly'))
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetNumberPrefix`;
DELIMITER |
CREATE PROCEDURE `spHRMGetNumberPrefix`(IN MID varchar(255), OUT ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE TempID VARCHAR(255);
	DECLARE Num LONG;
	DECLARE N INT;
	SELECT NumberPrefix,LastID,Length INTO TempID, Num, N FROM  hrm_numberprefix WHERE ModuleID = MID ;
	IF Num = 0 THEN
		SET Num = 1;
	END IF;
	SET ID = CONCAT(TempID, '-',LPAD(CONCAT(Num,''),N,'0'));

END |
DELIMITER ;

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

	SELECT u.var_hrm_utype INTO CheckU 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_id, '') AS 'PositionID', 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);

		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);

		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_id, '') AS 'PositionID', 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_id, '') AS 'PositionID', 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_internal_id, '') AS Emp_InternalID,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_id, '') AS 'PositionID', 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_internal_id, '') AS Emp_InternalID, 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 var_empid INTO SEmpID FROM ame_user WHERE var_id = userid;
		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_id, '') AS 'PositionID', 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_id, '') AS 'PositionID', 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_id, '') AS 'PositionID', 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_id, '') AS 'PositionID', 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_internal_id, '') AS Emp_InternalID,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_id, '') AS 'PositionID', 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_internal_id, '') AS Emp_InternalID, 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_id, '') AS 'PositionID', 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_id, '') AS PositionID, 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 `spHRMGetOvertimeSub`;
DELIMITER |
CREATE PROCEDURE `spHRMGetOvertimeSub`(userid varchar(255))
    DETERMINISTIC
BEGIN

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

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

	IF CheckU = "ESS" THEN
		
		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_id, '') AS 'PositionID', 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;

	ELSE
		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_id, '') AS 'PositionID', 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)
		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_id, '') AS PositionID, 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 `spHRMGetPayrollID`;
DELIMITER |
CREATE PROCEDURE `spHRMGetPayrollID`(ID varchar(255))
    DETERMINISTIC
BEGIN

	SELECT Payroll_ID,Payroll_Name,Payroll_Type,Payroll_StartDate,Payroll_LastSubmitDate,Payroll_SubmitDate,Payroll_SalaryStartDate,Payroll_LastSalaryDate,Payroll_SalaryDate FROM hrm_payroll WHERE Payroll_ID = ID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetReportSub`;
DELIMITER |
CREATE PROCEDURE `spHRMGetReportSub`(SUserID varchar(255), SRPTName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE CheckU VARCHAR(255) DEFAULT("");

	SELECT e.var_hrm_utype INTO CheckU FROM ame_user e WHERE e.var_id = SUserID;

	IF SRPTName = "FingerPrint" OR SRPTName = "Attendance" OR SRPTName = "Employee" OR SRPTName = "EmployeeInfo" THEN
		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 IF(LOWER(CheckU) = "ess" AND (SRPTName = "FingerPrint" OR SRPTName = "Attendance"),u.var_id = SUserID,TRUE)
		ORDER BY e.var_id;
	END IF;

	IF SRPTName = "FingerPrint" OR SRPTName = "Attendance" THEN
		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;
	END IF;

	IF SRPTName = "FingerPrint" OR SRPTName = "Attendance" THEN
		SELECT b.Department_ID,b.Department_Name,b.Department_Description,b.Department_Parent FROM hrm_emp_department b ORDER BY b.Department_ID;
	END IF;

	IF SRPTName = "FingerPrint" OR SRPTName = "Attendance" THEN
		SELECT b.Type_Name FROM hrm_emp_type b ORDER BY b.Type_Name;
	END IF;

	IF SRPTName = "FingerPrint" OR SRPTName = "Attendance" THEN
		SELECT b.Category_Name FROM hrm_emp_category b ORDER BY b.Category_Name;
	END IF;

	IF SRPTName = "FingerPrint" OR SRPTName = "Attendance" THEN
		SELECT b.Grade_Name FROM hrm_emp_grade b ORDER BY b.Grade_Name;
	END IF;

	IF SRPTName = "FingerPrint" OR SRPTName = "Attendance" THEN
		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 IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetRoleID`;
DELIMITER |
CREATE PROCEDURE `spHRMGetRoleID`(ID varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_ID,RM_Name,RM_Des,RM_Status FROM hrm_role WHERE RM_ID = ID;

	SELECT RM_ModuleID,RM_Delete,RM_Edit,RM_Export,RM_Import,RM_List,RM_View,RM_Access,RM_RoleID FROM hrm_role_detail WHERE RM_RoleID = ID;

	SELECT RMR_RoleID, RMR_RPTID, RMR_View FROM hrm_role_rpt_detail WHERE RMR_RoleID = ID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetRoleSub`;
DELIMITER |
CREATE PROCEDURE `spHRMGetRoleSub`()
    DETERMINISTIC
BEGIN
	SELECT RM_ModuleID,RM_Delete,RM_Edit,RM_Export,RM_Import,RM_List,RM_View,RM_Access,RM_RoleID FROM hrm_role_detail WHERE RM_RoleID='ADMIN';

	SELECT RMR_RoleID,RMR_RPTID,RMR_View FROM hrm_role_rpt_detail WHERE RMR_RoleID = 'ADMIN';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetRoster`;
DELIMITER |
CREATE PROCEDURE `spHRMGetRoster`(UserID varchar(255), SDate Date, SEmpID varchar(255))
    DETERMINISTIC
BEGIN
	SELECT r.Roster_Date,r.Roster_EmpID,r.Roster_ShiftID
	,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
	,ws.Shift_ID,ws.Shift_Name,ws.Shift_Type,ws.Shift_Description
	FROM hrm_timesheet_roster r
	INNER JOIN hrm_timesheet_workshift ws ON r.Roster_ShiftID = ws.Shift_ID
	INNER JOIN ame_mt_emp e ON r.Roster_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 MONTH(Roster_Date) = MONTH(SDate) AND YEAR(Roster_Date) = YEAR(SDate) AND Roster_EmpID = SEmpID 
	ORDER BY e.var_id;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetRosterDate`;
DELIMITER |
CREATE PROCEDURE `spHRMGetRosterDate`(UserID varchar(255), SDate Date)
    DETERMINISTIC
BEGIN
	SELECT r.Roster_Date,r.Roster_EmpID,r.Roster_ShiftID
	,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_internal_id, '') AS Emp_InternalID
	,ws.Shift_ID,ws.Shift_Name,ws.Shift_Type,ws.Shift_Description
	FROM hrm_timesheet_roster r
	INNER JOIN hrm_timesheet_workshift ws ON r.Roster_ShiftID = ws.Shift_ID
	INNER JOIN ame_mt_emp e ON r.Roster_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 MONTH(Roster_Date) = MONTH(SDate) AND YEAR(Roster_Date) = YEAR(SDate) ORDER BY r.Roster_Date;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetRosterSub`;
DELIMITER |
CREATE PROCEDURE `spHRMGetRosterSub`(Userid varchar(255))
    DETERMINISTIC
BEGIN
	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_id, '') AS 'PositionID', 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 LOWER(e.var_hrm_shift_type) = 'roster' 
	ORDER BY e.var_id;

	SELECT Shift_ID,Shift_Name,Shift_Type,Shift_Description	FROM hrm_timesheet_workshift b WHERE LOWER(Shift_Type) = "roster" ORDER BY b.Shift_ID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetSalaryAdjustmentSub`;
DELIMITER |
CREATE PROCEDURE `spHRMGetSalaryAdjustmentSub`()
    DETERMINISTIC
BEGIN
	SELECT SubmitPayroll_ID FROM hrm_payroll_submit_payroll ORDER BY SubmitPayroll_ID DESC;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetSalaryAdjustmentSubSearch`;
DELIMITER |
CREATE PROCEDURE `spHRMGetSalaryAdjustmentSubSearch`(SID varchar(255), SK varchar(255))
    DETERMINISTIC
BEGIN
			SET @SQL1 = CONCAT("SELECT sp.SubmitPayroll_ID,sp.SubmitPayroll_Date,sp.SubmitPayroll_StartDate,sp.SubmitPayroll_EndDate,s.Salary_EmpID,COALESCE(e.var_name, '') AS EmpName,COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID,s.Salary_Type,IF(NOT ISNULL(sa.adj_submitpayrollID), sa.adj_salary, 
																																																																																																					IF(LOWER(s.Salary_Type)='hourly',COALESCE(SUM(att.Att_WorkHour)*", REPLACE(SK,'TempSA','s.Salary_Amount'), ",0),
																																																																																																					IF(LOWER(s.Salary_Type)= 'daily', COALESCE(SUM(IF(LOWER(att.Att_Status) = 'la' OR LOWER(att.Att_Status) = 'p', 1, 0.0)) * ", REPLACE(SK,'TempSA','s.Salary_Amount'), ", 0), 
																																																																																																					IF(LOWER(s.Salary_Type)= 'basic', IF(sp.SubmitPayroll_SalaryStartDate < e.dat_hrm_joindate AND e.dat_hrm_joindate < sp.SubmitPayroll_SalaryEndDate, (", REPLACE(SK,'TempSA','s.Salary_Amount'), " / p.Payroll_AmtWorkingDay)* COALESCE(SUM(IF(LOWER(att.Att_Status) != 'ho' AND LOWER(att.Att_Status) != 'b', 1, 0)), 0) , ", REPLACE(SK,'TempSA','s.Salary_Amount'), "),0.00)))) AS 'Salary_Amount'
								FROM hrm_payroll_submit_payroll sp 
								INNER JOIN hrm_payroll_salary s ON sp.SubmitPayroll_PayrollID = s.Salary_PayrollID AND LOWER(s.Salary_Status) = 'active' 
								LEFT JOIN hrm_timesheet_attendance att ON att.Att_EmpID=s.Salary_EmpID AND att.Att_Date >= sp.SubmitPayroll_StartDate AND att.Att_Date <= sp.SubmitPayroll_EndDate
								LEFT JOIN hrm_payroll p ON(p.Payroll_ID = sp.SubmitPayroll_PayrollID)
								LEFT JOIN hrm_payroll_salary_adjustment sa ON(sa.adj_submitpayrollID = sp.SubmitPayroll_ID AND sa.adj_empid = s.Salary_EmpID)
								LEFT JOIN ame_mt_emp e ON(e.var_id = s.Salary_EmpID)
								WHERE sp.SubmitPayroll_ID = '", SID, "'	GROUP BY s.Salary_EmpID;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
END |
DELIMITER ;

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

	SET @SQL1 = CONCAT("SELECT s.Salary_EmpID,s.Salary_PayrollID,s.Salary_Type,", REPLACE(SK,'TempSA','s.Salary_Amount'), " AS 'Salary_Amount',s.Salary_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_internal_id, '') AS Emp_InternalID
	,Payroll_ID,Payroll_Name,Payroll_Type,Payroll_StartDate,Payroll_LastSubmitDate,Payroll_SubmitDate
	FROM hrm_payroll_salary s INNER JOIN ame_mt_emp e ON s.Salary_EmpID = e.var_id 
	INNER JOIN hrm_payroll pay ON pay.Payroll_ID = s.Salary_PayrollID
	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 s.Salary_EmpID = '", ID ,"' ORDER BY s.Salary_Line;");
	
	PREPARE St FROM @SQL1;
	EXECUTE St;
	DEALLOCATE PREPARE St;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetSalarySub`;
DELIMITER |
CREATE PROCEDURE `spHRMGetSalarySub`()
    DETERMINISTIC
BEGIN
	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_id, '') AS 'PositionID', 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)
	ORDER BY e.var_id;

	SELECT b.Payroll_ID,b.Payroll_Name,b.Payroll_Type,b.Payroll_StartDate,b.Payroll_LastSubmitDate,b.Payroll_SubmitDate FROM hrm_payroll b ORDER BY b.Payroll_ID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetSetting`;
DELIMITER |
CREATE PROCEDURE `spHRMGetSetting`()
    DETERMINISTIC
BEGIN
	
	SELECT d.Setting_Type, d.Setting_Name, d.Setting_Value FROM hrm_setting d;

	SELECT LeaveType_ID,LeaveType_Name,LeaveType_PayStatus,LeaveType_Year,LeaveType_AmountAllowed,LeaveType_GenderRestriction,LeaveType_PayType,LeaveType_PayAmount FROM hrm_timesheet_leave_type b WHERE LOWER(LeaveType_PayStatus)='unpaid' ORDER BY b.LeaveType_ID;

	SELECT a.Auth_ID,a.Auth_Name,a.Auth_Type,a.Auth_AndOr,a.Auth_Amount FROM hrm_authorisation a ORDER BY a.Auth_ID;
	
	SELECT COALESCE(v.var_id, '') AS VendID, COALESCE(v.var_name, '') AS VendName FROM ame_mt_ven v ORDER BY v.var_id;

	SELECT r.RM_ID,r.RM_Name FROM hrm_role r WHERE r.RM_Status = 1 ORDER BY r.RM_ID;

	SELECT COALESCE(var_name, '') AS ImagePath FROM ame_sys_config WHERE var_id = 'IMG_PATH_WEB' LIMIT 1;

	SELECT COALESCE(var_type, '') AS AccType, COALESCE(var_groupid, '') AS GroupID, COALESCE(var_accid, '') AS AccID FROM ame_mt_acc_set WHERE var_type = 'Payroll';

	SELECT COALESCE(var_id, '') AS AccID, COALESCE(var_name, '') AS AccName FROM ame_mt_acc WHERE tin_inactive='0';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetSettingDeductLeaveBalance`;
DELIMITER |
CREATE PROCEDURE `spHRMGetSettingDeductLeaveBalance`()
    DETERMINISTIC
BEGIN
	SELECT Setting_Value FROM hrm_setting WHERE Setting_Type = 'Leave' AND Setting_Name = 'Deduct_Leave_Balance_Hourly';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetSubmitPayrollDetailOpen`;
DELIMITER |
CREATE PROCEDURE `spHRMGetSubmitPayrollDetailOpen`(SID varchar(255), SK varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE PercentageType VARCHAR(20) DEFAULT('');
	DECLARE LateType VARCHAR(20) DEFAULT('');
	DECLARE LatePayAmount FLOAT DEFAULT(0);
	DECLARE LatePayType VARCHAR(20) DEFAULT('');
	DECLARE AbsentType VARCHAR(20) DEFAULT('');
	DECLARE AbsentPayAmount FLOAT DEFAULT(0);
	DECLARE AbsentPayType VARCHAR(20) DEFAULT('');
	DECLARE PayrollType VARCHAR(255) DEFAULT('');
	DECLARE TempLastDay INT DEFAULT(0);

	DECLARE StartDate DATE;
	DECLARE EndDate DATE;

	SELECT SubmitPayroll_StartDate, SubmitPayroll_EndDate into StartDate,EndDate FROM hrm_payroll_submit_payroll WHERE SubmitPayroll_ID = SID;	
	
	SELECT Setting_Value INTO PercentageType FROM hrm_setting WHERE Setting_Type = 'Percentage' AND Setting_Name = 'Percentage';

	SELECT Setting_Value INTO LateType FROM hrm_setting WHERE Setting_Type = 'Attendance_Late' AND Setting_Name = 'Deduct_Type';

	SELECT Setting_Value,Setting_Name INTO LatePayAmount,LatePayType FROM hrm_setting WHERE Setting_Type = 'Attendance_Late_PayAmount';

	SELECT Setting_Value INTO AbsentType FROM hrm_setting WHERE Setting_Type = 'Attendance_Absent' AND Setting_Name = 'Deduct_Type';

	SELECT Setting_Value,Setting_Name INTO AbsentPayAmount,AbsentPayType FROM hrm_setting WHERE Setting_Type = 'Attendance_Absent_PayAmount';


SELECT tbl7.*, 0 as 'Tax_DeductAmount', (Salary_Amount+Allowance_PayAmount+Bonus_PayAmount+OT_PayAmount)-(Deduction_Amount+Leave_DeductAmount+Late_DeductAmount+Absent_DeductAmount) AS 'NetSalary_PayAmount',
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 (

	SELECT tbl6.SubmitPayroll_ID,tbl6.SubmitPayroll_Date,tbl6.SubmitPayroll_StartDate,tbl6.SubmitPayroll_EndDate,tbl6.Payroll_AmtWorkingDay,tbl6.Payroll_AmtWorkingHourPerDay,tbl6.Salary_EmpID,tbl6.Emp_LateDeduction,tbl6.Salary_Type,tbl6.Salary_Amount,tbl6.Allowance_PayAmount,tbl6.Bonus_PayAmount,tbl6.OT_PayAmount,tbl6.Deduction_Amount,tbl6.Leave_DeductAmount, IF(tbl6.Emp_LateDeduction = 0, 0, COALESCE(SUM(IF(LOWER(LatePayType) = 'pro-rata based', 
																																																																																																																																																		((tbl6.Salary_Amount/tbl6.Payroll_AmtWorkingDay)/tbl6.Payroll_AmtWorkingHourPerDay) * fnHRMTimeToFloat(att.Att_LateDurationDeduct), 
																																																																																																																																																 IF(LOWER(LateType) = 'unique', 
																																																																																																																																																			IF(att.Att_LateAmount > 0, 
																																																																																																																																																						IF(LOWER(LatePayType) = 'fixed',LatePayAmount, 
																																																																																																																																																						IF(LOWER(LatePayType) = 'percent', IF(PercentageType = 'Salary', tbl6.Salary_Amount * (LatePayAmount/100), PercentageType * (LatePayAmount/100)), 0.0)), 0), 
																																																																																																																																																 IF(LOWER(LateType) = 'normal', 
																																																																																																																																																			IF(att.Att_LateAmount > 0, 
																																																																																																																																																						IF(LOWER(LatePayType) = 'fixed', LatePayAmount * att.Att_LateAmount, 
																																																																																																																																																						IF(LOWER(LatePayType) = 'percent', IF(PercentageType = 'Salary', (tbl6.Salary_Amount * (LatePayAmount/100))* att.Att_LateAmount, (PercentageType * (LatePayAmount/100))* att.Att_LateAmount), 0.0)), 0), 0.00)))), 0)) AS 'Late_DeductAmount', 
																																																																																																																																										COALESCE(SUM(IF(LOWER(AbsentPayType) = 'pro-rata based', 
																																																																																																																																																			((tbl6.Salary_Amount/tbl6.Payroll_AmtWorkingDay)/tbl6.Payroll_AmtWorkingHourPerDay) * fnHRMTimeToFloat(att.Att_ABDurationDeduct), 
																																																																																																																																																	IF(LOWER(AbsentType)='unique', 
																																																																																																																																																			IF(att.Att_ABAmount>0, 
																																																																																																																																																						IF(LOWER(AbsentPayType)='fixed', AbsentPayAmount, 
																																																																																																																																																						IF(LOWER(AbsentPayType)='percent', IF(PercentageType='Salary', (tbl6.Salary_Amount * (AbsentPayAmount/100)), (PercentageType * (AbsentPayAmount/100))), 0.0)), 0),
																																																																																																																																																	IF(LOWER(AbsentType)='normal', 
																																																																																																																																																			IF(att.Att_ABAmount>0, 
																																																																																																																																																						IF(LOWER(AbsentPayType)='fixed', AbsentPayAmount*att.Att_ABAmount, 
																																																																																																																																																						IF(LOWER(AbsentPayType)='percent', IF(PercentageType='Salary', (tbl6.Salary_Amount * (AbsentPayAmount/100))*att.Att_ABAmount, (PercentageType * (AbsentPayAmount/100))*att.Att_ABAmount), 0.0)), 0), 0.00)))), 0) AS 'Absent_DeductAmount' FROM (

		SELECT tbl5.SubmitPayroll_ID,tbl5.SubmitPayroll_Date,tbl5.SubmitPayroll_StartDate,tbl5.SubmitPayroll_EndDate,tbl5.Payroll_AmtWorkingDay,tbl5.Payroll_AmtWorkingHourPerDay,tbl5.Salary_EmpID,tbl5.Emp_LateDeduction,tbl5.Salary_Type,tbl5.Salary_Amount,tbl5.Allowance_PayAmount,tbl5.Bonus_PayAmount,tbl5.OT_PayAmount,tbl5.Deduction_Amount, COALESCE(SUM(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', (tbl5.Salary_Amount * (lt.LeaveType_PayAmount/100)) * l.Leave_Total, (PercentageType * (lt.LeaveType_PayAmount/100)) * l.Leave_Total), 
																																																																																																																																																																						IF(LOWER(lt.LeaveType_PayType) = 'hourly rate', ((tbl5.Salary_Amount / tbl5.Payroll_AmtWorkingDay) / tbl5.Payroll_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', tbl5.Salary_Amount , PercentageType)* (lt.LeaveType_PayAmount/100)) * l.Leave_Total, 0), 
																																																																																																																																																																						IF(LOWER(lt.LeaveType_PayType) = 'dialy rate', COALESCE((tbl5.Salary_Amount/tbl5.Payroll_AmtWorkingDay) * l.Leave_Total, 0), 0.0))), 0.00))),0) AS 'Leave_DeductAmount' FROM (

			SELECT tbl4.SubmitPayroll_ID,tbl4.SubmitPayroll_Date,tbl4.SubmitPayroll_StartDate,tbl4.SubmitPayroll_EndDate,tbl4.Payroll_AmtWorkingDay,tbl4.Payroll_AmtWorkingHourPerDay,tbl4.Salary_EmpID,tbl4.Emp_LateDeduction,tbl4.Salary_Type,tbl4.Salary_Amount,tbl4.Allowance_PayAmount,tbl4.Bonus_PayAmount,tbl4.OT_PayAmount, COALESCE(SUM(de.dd_amount), 0) AS 'Deduction_Amount' FROM (

				SELECT tbl3.SubmitPayroll_ID,tbl3.SubmitPayroll_Date,tbl3.SubmitPayroll_StartDate,tbl3.SubmitPayroll_EndDate,tbl3.Payroll_AmtWorkingDay,tbl3.Payroll_AmtWorkingHourPerDay,tbl3.Salary_EmpID,tbl3.Emp_LateDeduction,tbl3.Salary_Type,tbl3.Salary_Amount,tbl3.Allowance_PayAmount,tbl3.Bonus_PayAmount, COALESCE(SUM(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)))) > tbl3.Payroll_AmtWorkingHourPerDay, (tbl3.Salary_Amount / tbl3.Payroll_AmtWorkingDay) * o.od_multiplier, (IF(o.Att_OvertimeOut >= o.od_timeout, o.od_hours, HOUR(TIMEDIFF(o.Att_OvertimeOut,o.od_timein)))) * ((tbl3.Salary_Amount / tbl3.Payroll_AmtWorkingDay)/tbl3.Payroll_AmtWorkingHourPerDay))) * o.od_multiplier), 0.00))), 0) AS 'OT_PayAmount' FROM (
		
					SELECT tbl2.SubmitPayroll_ID,tbl2.SubmitPayroll_Date,tbl2.SubmitPayroll_StartDate,tbl2.SubmitPayroll_EndDate,tbl2.Payroll_AmtWorkingDay,tbl2.Payroll_AmtWorkingHourPerDay,tbl2.Salary_EmpID,tbl2.Emp_LateDeduction,tbl2.Salary_Type,tbl2.Salary_Amount,tbl2.Allowance_PayAmount, COALESCE(SUM(IF(LOWER(bd.Bonus_PayType)='fixed',bd.Bonus_PayAmount,IF(LOWER(bd.Bonus_PayType)='percent', COALESCE(IF(PercentageType='Salary',(tbl2.Salary_Amount * (bd.Bonus_PayAmount/100)),(PercentageType * (bd.Bonus_PayAmount/100))),0),IF(LOWER(bd.Bonus_PayType)='pro-rate', TRUNCATE(fnHRMCheckBonusProrate(tbl2.Emp_JoinDate,tbl2.Emp_Probation,tbl2.Emp_EndDateProbation,b.Bonus_Date,tbl2.Salary_Amount), 2), 0)))), 0) AS 'Bonus_PayAmount' FROM(

							SELECT tbl1.SubmitPayroll_ID,tbl1.SubmitPayroll_Date,tbl1.SubmitPayroll_StartDate,tbl1.SubmitPayroll_EndDate,tbl1.Payroll_AmtWorkingDay,tbl1.Payroll_AmtWorkingHourPerDay,tbl1.Salary_EmpID,tbl1.Emp_LateDeduction,tbl1.Emp_JoinDate,tbl1.Emp_Probation,tbl1.Emp_EndDateProbation,tbl1.Salary_Type,tbl1.Salary_Amount, COALESCE(SUM(IF(LOWER(a.Allowance_PayType) ='fixed',a.Allowance_PayAmount,IF(LOWER(a.Allowance_PayType) ='percent', COALESCE(IF(PercentageType='Salary', (tbl1.Salary_Amount * (a.Allowance_PayAmount/100)), (PercentageType * (a.Allowance_PayAmount/100))), 0), 0))), 0) AS 'Allowance_PayAmount' FROM(
					
								SELECT sp.SubmitPayroll_ID,sp.SubmitPayroll_Date,sp.SubmitPayroll_StartDate,sp.SubmitPayroll_EndDate,p.Payroll_AmtWorkingDay,p.Payroll_AmtWorkingHourPerDay,s.Salary_EmpID,COALESCE(e.tin_hrm_late_deduction, 0) AS Emp_LateDeduction,COALESCE(e.dat_hrm_joindate, '0000-00-00') AS Emp_JoinDate,COALESCE(e.tin_hrm_probation, 0) AS Emp_Probation,COALESCE(e.dat_hrm_enddateprobation, '0000-00-00') AS Emp_EndDateProbation,s.Salary_Type,IF(NOT ISNULL(sa.adj_submitpayrollID), sa.adj_salary, 
																																																																																																					IF(LOWER(s.Salary_Type)='hourly',COALESCE(SUM(att.Att_WorkHour) * CAST(AES_DECRYPT(unhex(s.Salary_Amount),SK) AS DECIMAL(9,2)),0),
																																																																																																					IF(LOWER(s.Salary_Type)= 'daily', COALESCE(SUM(IF(LOWER(att.Att_Status) = 'la' OR LOWER(att.Att_Status) = 'p', 1, 0.0)) * CAST(AES_DECRYPT(unhex(s.Salary_Amount),SK) AS DECIMAL(9,2)), 0), 
																																																																																																					IF(LOWER(s.Salary_Type)= 'basic', IF(sp.SubmitPayroll_SalaryStartDate < e.dat_hrm_joindate AND e.dat_hrm_joindate < sp.SubmitPayroll_SalaryEndDate, (CAST(AES_DECRYPT(unhex(s.Salary_Amount),SK) AS DECIMAL(9,2)) / p.Payroll_AmtWorkingDay)* COALESCE(SUM(IF(LOWER(att.Att_Status) != 'ho' AND LOWER(att.Att_Status) != 'b', 1, 0)), 0) , CAST(AES_DECRYPT(unhex(s.Salary_Amount),SK) AS DECIMAL(9,2)) ),0.00)))) AS 'Salary_Amount'
								FROM hrm_payroll_submit_payroll sp 
								INNER JOIN hrm_payroll_salary s ON sp.SubmitPayroll_PayrollID = s.Salary_PayrollID AND LOWER(s.Salary_Status) = 'active' 
								LEFT JOIN hrm_timesheet_attendance att ON att.Att_EmpID=s.Salary_EmpID AND att.Att_Date >= sp.SubmitPayroll_StartDate AND att.Att_Date <= sp.SubmitPayroll_EndDate
								LEFT JOIN hrm_payroll p ON(p.Payroll_ID = sp.SubmitPayroll_PayrollID)
								LEFT JOIN hrm_payroll_salary_adjustment sa ON(sa.adj_submitpayrollID = sp.SubmitPayroll_ID AND sa.adj_empid = s.Salary_EmpID)
								LEFT JOIN ame_mt_emp e ON(e.var_id = s.Salary_EmpID)
								WHERE sp.SubmitPayroll_ID = SID AND s.Salary_EmpID NOT IN(SELECT spd.SubmitPayroll_EmpID FROM hrm_payroll_submit_payroll_detail spd WHERE spd.SubmitPayroll_ID = SID)
								GROUP BY s.Salary_EmpID ) tbl1

							LEFT JOIN (hrm_payroll_allowance_employee ae INNER JOIN hrm_payroll_allowance a ON a.Allowance_ID = ae.Allowance_ID) ON ae.Allowance_EmpID = tbl1.Salary_EmpID
							GROUP BY tbl1.Salary_EmpID ) tbl2

					LEFT JOIN (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)) 
					ON bd.Bonus_EmpID = tbl2.Salary_EmpID
					GROUP BY tbl2.Salary_EmpID) tbl3

				LEFT JOIN (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
				ON o.od_empid = tbl3.Salary_EmpID AND o.od_date >= tbl3.SubmitPayroll_StartDate AND o.od_date <= tbl3.SubmitPayroll_EndDate
				GROUP BY tbl3.Salary_EmpID) tbl4

			LEFT JOIN (SELECT MIN(dd_line) ,de.Deduction_ID,de.Deduction_EmpID,de.Deduction_Status,ded.dd_status,ded.dd_amount
									FROM hrm_payroll_deduction de
									LEFT JOIN hrm_payroll_deduction_detail ded ON(de.Deduction_ID = ded.dd_id)
									WHERE LOWER(ded.dd_status) = 'open'
									GROUP BY de.Deduction_ID
									ORDER BY de.Deduction_ID,ded.dd_line) de 
			ON de.Deduction_EmpID = tbl4.Salary_EmpID AND LOWER(de.Deduction_Status) = 'approved'
			GROUP BY tbl4.Salary_EmpID) tbl5

		LEFT JOIN (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')) l ON(l.Leave_EmpID = tbl5.Salary_EmpID AND l.LeaveD_Date >= tbl5.SubmitPayroll_StartDate AND l.LeaveD_Date <= tbl5.SubmitPayroll_EndDate) 
		LEFT JOIN hrm_timesheet_leave_type lt ON l.LeaveD_TypeID = lt.LeaveType_ID AND LOWER(LeaveType_PayStatus) = 'unpaid'
		GROUP BY tbl5.Salary_EmpID) tbl6

	LEFT JOIN hrm_timesheet_attendance att ON att.Att_EmpID = tbl6.Salary_EmpID AND att.Att_Date >= tbl6.SubmitPayroll_StartDate AND att.Att_Date <= tbl6.SubmitPayroll_EndDate
	GROUP BY tbl6.Salary_EmpID) tbl7 

LEFT JOIN ame_mt_emp e ON tbl7.Salary_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 e.var_hrm_status NOT IN('Death', 'Resigned', 'Retired', 'Terminated');

SELECT SubmitPayroll_ID,SubmitPayroll_PayrollID,SubmitPayroll_Date,SubmitPayroll_StartDate,SubmitPayroll_EndDate,
p.Payroll_ID,p.Payroll_Name,p.Payroll_Type,p.Payroll_StartDate,p.Payroll_LastSubmitDate,p.Payroll_SubmitDate
FROM hrm_payroll_submit_payroll b LEFT JOIN hrm_payroll p ON(b.SubmitPayroll_PayrollID=p.Payroll_ID)
WHERE SubmitPayroll_ID=SID;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetSubmitPayrollDetailPaid`;
DELIMITER |
CREATE PROCEDURE `spHRMGetSubmitPayrollDetailPaid`(SID varchar(255), SK varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE PercentageType VARCHAR(20) DEFAULT('');
	DECLARE LateType VARCHAR(20) DEFAULT('');
	DECLARE LatePayAmount FLOAT DEFAULT(0);
	DECLARE LatePayType VARCHAR(20) DEFAULT('');
	DECLARE AbsentType VARCHAR(20) DEFAULT('');
	DECLARE AbsentPayAmount FLOAT DEFAULT(0);
	DECLARE AbsentPayType VARCHAR(20) DEFAULT('');
	DECLARE PayrollType VARCHAR(255) DEFAULT('');
	DECLARE TempLastDay INT DEFAULT(0);

	DECLARE StartDate DATE;
	DECLARE EndDate DATE;

	SELECT SubmitPayroll_StartDate, SubmitPayroll_EndDate into StartDate,EndDate FROM hrm_payroll_submit_payroll WHERE SubmitPayroll_ID = SID;	
	
	SELECT Setting_Value INTO PercentageType FROM hrm_setting WHERE Setting_Type = 'Percentage' AND Setting_Name = 'Percentage';

	SELECT Setting_Value INTO LateType FROM hrm_setting WHERE Setting_Type = 'Attendance_Late' AND Setting_Name = 'Deduct_Type';

	SELECT Setting_Value,Setting_Name INTO LatePayAmount,LatePayType FROM hrm_setting WHERE Setting_Type = 'Attendance_Late_PayAmount';

	SELECT Setting_Value INTO AbsentType FROM hrm_setting WHERE Setting_Type = 'Attendance_Absent' AND Setting_Name = 'Deduct_Type';

	SELECT Setting_Value,Setting_Name INTO AbsentPayAmount,AbsentPayType FROM hrm_setting WHERE Setting_Type = 'Attendance_Absent_PayAmount';


SELECT tbl7.*, 0 as 'Tax_DeductAmount', (Salary_Amount+Allowance_PayAmount+Bonus_PayAmount+OT_PayAmount)-(Deduction_Amount+Leave_DeductAmount+Late_DeductAmount+Absent_DeductAmount) AS 'NetSalary_PayAmount',
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 (

	SELECT tbl6.SubmitPayroll_ID,tbl6.SubmitPayroll_Date,tbl6.SubmitPayroll_StartDate,tbl6.SubmitPayroll_EndDate,tbl6.Payroll_AmtWorkingDay,tbl6.Payroll_AmtWorkingHourPerDay,tbl6.Salary_EmpID,tbl6.Emp_LateDeduction,tbl6.Salary_Type,tbl6.Salary_Amount,tbl6.Allowance_PayAmount,tbl6.Bonus_PayAmount,tbl6.OT_PayAmount,tbl6.Deduction_Amount,tbl6.Leave_DeductAmount, IF(tbl6.Emp_LateDeduction = 0, 0, COALESCE(SUM(IF(LOWER(LatePayType) = 'pro-rata based', 
																																																																																																																																																		((tbl6.Salary_Amount/tbl6.Payroll_AmtWorkingDay)/tbl6.Payroll_AmtWorkingHourPerDay) * fnHRMTimeToFloat(att.Att_LateDurationDeduct), 
																																																																																																																																																 IF(LOWER(LateType) = 'unique', 
																																																																																																																																																			IF(att.Att_LateAmount > 0, 
																																																																																																																																																						IF(LOWER(LatePayType) = 'fixed',LatePayAmount, 
																																																																																																																																																						IF(LOWER(LatePayType) = 'percent', IF(PercentageType = 'Salary', tbl6.Salary_Amount * (LatePayAmount/100), PercentageType * (LatePayAmount/100)), 0.0)), 0), 
																																																																																																																																																 IF(LOWER(LateType) = 'normal', 
																																																																																																																																																			IF(att.Att_LateAmount > 0, 
																																																																																																																																																						IF(LOWER(LatePayType) = 'fixed', LatePayAmount * att.Att_LateAmount, 
																																																																																																																																																						IF(LOWER(LatePayType) = 'percent', IF(PercentageType = 'Salary', (tbl6.Salary_Amount * (LatePayAmount/100))* att.Att_LateAmount, (PercentageType * (LatePayAmount/100))* att.Att_LateAmount), 0.0)), 0), 0.00)))), 0)) AS 'Late_DeductAmount', 
																																																																																																																																										COALESCE(SUM(IF(LOWER(AbsentPayType) = 'pro-rata based', 
																																																																																																																																																			((tbl6.Salary_Amount/tbl6.Payroll_AmtWorkingDay)/tbl6.Payroll_AmtWorkingHourPerDay) * fnHRMTimeToFloat(att.Att_ABDurationDeduct), 
																																																																																																																																																	IF(LOWER(AbsentType)='unique', 
																																																																																																																																																			IF(att.Att_ABAmount>0, 
																																																																																																																																																						IF(LOWER(AbsentPayType)='fixed', AbsentPayAmount, 
																																																																																																																																																						IF(LOWER(AbsentPayType)='percent', IF(PercentageType='Salary', (tbl6.Salary_Amount * (AbsentPayAmount/100)), (PercentageType * (AbsentPayAmount/100))), 0.0)), 0),
																																																																																																																																																	IF(LOWER(AbsentType)='normal', 
																																																																																																																																																			IF(att.Att_ABAmount>0, 
																																																																																																																																																						IF(LOWER(AbsentPayType)='fixed', AbsentPayAmount*att.Att_ABAmount, 
																																																																																																																																																						IF(LOWER(AbsentPayType)='percent', IF(PercentageType='Salary', (tbl6.Salary_Amount * (AbsentPayAmount/100))*att.Att_ABAmount, (PercentageType * (AbsentPayAmount/100))*att.Att_ABAmount), 0.0)), 0), 0.00)))), 0) AS 'Absent_DeductAmount' FROM (

		SELECT tbl5.SubmitPayroll_ID,tbl5.SubmitPayroll_Date,tbl5.SubmitPayroll_StartDate,tbl5.SubmitPayroll_EndDate,tbl5.Payroll_AmtWorkingDay,tbl5.Payroll_AmtWorkingHourPerDay,tbl5.Salary_EmpID,tbl5.Emp_LateDeduction,tbl5.Salary_Type,tbl5.Salary_Amount,tbl5.Allowance_PayAmount,tbl5.Bonus_PayAmount,tbl5.OT_PayAmount,tbl5.Deduction_Amount, COALESCE(SUM(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', (tbl5.Salary_Amount * (lt.LeaveType_PayAmount/100)) * l.Leave_Total, (PercentageType * (lt.LeaveType_PayAmount/100)) * l.Leave_Total), 
																																																																																																																																																																						IF(LOWER(lt.LeaveType_PayType) = 'hourly rate', ((tbl5.Salary_Amount / tbl5.Payroll_AmtWorkingDay) / tbl5.Payroll_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', tbl5.Salary_Amount , PercentageType)* (lt.LeaveType_PayAmount/100)) * l.Leave_Total, 0), 
																																																																																																																																																																						IF(LOWER(lt.LeaveType_PayType) = 'dialy rate', COALESCE((tbl5.Salary_Amount/tbl5.Payroll_AmtWorkingDay) * l.Leave_Total, 0), 0.0))), 0.00))),0) AS 'Leave_DeductAmount' FROM (

			SELECT tbl4.SubmitPayroll_ID,tbl4.SubmitPayroll_Date,tbl4.SubmitPayroll_StartDate,tbl4.SubmitPayroll_EndDate,tbl4.Payroll_AmtWorkingDay,tbl4.Payroll_AmtWorkingHourPerDay,tbl4.Salary_EmpID,tbl4.Emp_LateDeduction,tbl4.Salary_Type,tbl4.Salary_Amount,tbl4.Allowance_PayAmount,tbl4.Bonus_PayAmount,tbl4.OT_PayAmount, COALESCE(SUM(de.dd_amount), 0) AS 'Deduction_Amount' FROM (

				SELECT tbl3.SubmitPayroll_ID,tbl3.SubmitPayroll_Date,tbl3.SubmitPayroll_StartDate,tbl3.SubmitPayroll_EndDate,tbl3.Payroll_AmtWorkingDay,tbl3.Payroll_AmtWorkingHourPerDay,tbl3.Salary_EmpID,tbl3.Emp_LateDeduction,tbl3.Salary_Type,tbl3.Salary_Amount,tbl3.Allowance_PayAmount,tbl3.Bonus_PayAmount, COALESCE(SUM(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)))) > tbl3.Payroll_AmtWorkingHourPerDay, (tbl3.Salary_Amount / tbl3.Payroll_AmtWorkingDay) * o.od_multiplier, (IF(o.Att_OvertimeOut >= o.od_timeout, o.od_hours, HOUR(TIMEDIFF(o.Att_OvertimeOut,o.od_timein)))) * ((tbl3.Salary_Amount / tbl3.Payroll_AmtWorkingDay)/tbl3.Payroll_AmtWorkingHourPerDay))) * o.od_multiplier), 0.00))), 0) AS 'OT_PayAmount' FROM (
		
					SELECT tbl2.SubmitPayroll_ID,tbl2.SubmitPayroll_Date,tbl2.SubmitPayroll_StartDate,tbl2.SubmitPayroll_EndDate,tbl2.Payroll_AmtWorkingDay,tbl2.Payroll_AmtWorkingHourPerDay,tbl2.Salary_EmpID,tbl2.Emp_LateDeduction,tbl2.Salary_Type,tbl2.Salary_Amount,tbl2.Allowance_PayAmount, COALESCE(SUM(IF(LOWER(bd.Bonus_PayType)='fixed',bd.Bonus_PayAmount,IF(LOWER(bd.Bonus_PayType)='percent', COALESCE(IF(PercentageType='Salary',(tbl2.Salary_Amount * (bd.Bonus_PayAmount/100)),(PercentageType * (bd.Bonus_PayAmount/100))),0),IF(LOWER(bd.Bonus_PayType)='pro-rate', TRUNCATE(fnHRMCheckBonusProrate(tbl2.Emp_JoinDate,tbl2.Emp_Probation,tbl2.Emp_EndDateProbation,b.Bonus_Date,tbl2.Salary_Amount), 2), 0)))), 0) AS 'Bonus_PayAmount' FROM(

							SELECT tbl1.SubmitPayroll_ID,tbl1.SubmitPayroll_Date,tbl1.SubmitPayroll_StartDate,tbl1.SubmitPayroll_EndDate,tbl1.Payroll_AmtWorkingDay,tbl1.Payroll_AmtWorkingHourPerDay,tbl1.Salary_EmpID,tbl1.Emp_LateDeduction,tbl1.Emp_JoinDate,tbl1.Emp_Probation,tbl1.Emp_EndDateProbation,tbl1.Salary_Type,tbl1.Salary_Amount, COALESCE(SUM(IF(LOWER(a.Allowance_PayType) ='fixed',a.Allowance_PayAmount,IF(LOWER(a.Allowance_PayType) ='percent', COALESCE(IF(PercentageType='Salary', (tbl1.Salary_Amount * (a.Allowance_PayAmount/100)), (PercentageType * (a.Allowance_PayAmount/100))), 0), 0))), 0) AS 'Allowance_PayAmount' FROM(
					
								SELECT sp.SubmitPayroll_ID,sp.SubmitPayroll_Date,sp.SubmitPayroll_StartDate,sp.SubmitPayroll_EndDate,p.Payroll_AmtWorkingDay,p.Payroll_AmtWorkingHourPerDay,s.Salary_EmpID,COALESCE(e.tin_hrm_late_deduction, 0) AS Emp_LateDeduction,COALESCE(e.dat_hrm_joindate, '0000-00-00') AS Emp_JoinDate,COALESCE(e.tin_hrm_probation, 0) AS Emp_Probation,COALESCE(e.dat_hrm_enddateprobation, '0000-00-00') AS Emp_EndDateProbation,s.Salary_Type,IF(NOT ISNULL(sa.adj_submitpayrollID), sa.adj_salary, 
																																																																																																					IF(LOWER(s.Salary_Type)='hourly',COALESCE(SUM(att.Att_WorkHour) * CAST(AES_DECRYPT(unhex(s.Salary_Amount),SK) AS DECIMAL(9,2)),0),
																																																																																																					IF(LOWER(s.Salary_Type)= 'daily', COALESCE(SUM(IF(LOWER(att.Att_Status) = 'la' OR LOWER(att.Att_Status) = 'p', 1, 0.0)) * CAST(AES_DECRYPT(unhex(s.Salary_Amount),SK) AS DECIMAL(9,2)), 0), 
																																																																																																					IF(LOWER(s.Salary_Type)= 'basic', IF(sp.SubmitPayroll_SalaryStartDate < e.dat_hrm_joindate AND e.dat_hrm_joindate < sp.SubmitPayroll_SalaryEndDate, (CAST(AES_DECRYPT(unhex(s.Salary_Amount),SK) AS DECIMAL(9,2)) / p.Payroll_AmtWorkingDay)* COALESCE(SUM(IF(LOWER(att.Att_Status) != 'ho' AND LOWER(att.Att_Status) != 'b', 1, 0)), 0) , CAST(AES_DECRYPT(unhex(s.Salary_Amount),SK) AS DECIMAL(9,2)) ),0.00)))) AS 'Salary_Amount'
								FROM hrm_payroll_submit_payroll sp 
								INNER JOIN hrm_payroll_salary s ON sp.SubmitPayroll_PayrollID = s.Salary_PayrollID AND LOWER(s.Salary_Status) = 'active' 
								LEFT JOIN hrm_timesheet_attendance att ON att.Att_EmpID=s.Salary_EmpID AND att.Att_Date >= sp.SubmitPayroll_StartDate AND att.Att_Date <= sp.SubmitPayroll_EndDate
								LEFT JOIN hrm_payroll p ON(p.Payroll_ID = sp.SubmitPayroll_PayrollID)
								LEFT JOIN hrm_payroll_salary_adjustment sa ON(sa.adj_submitpayrollID = sp.SubmitPayroll_ID AND sa.adj_empid = s.Salary_EmpID)
								LEFT JOIN ame_mt_emp e ON(e.var_id = s.Salary_EmpID)
								WHERE sp.SubmitPayroll_ID = SID AND s.Salary_EmpID IN(SELECT spd.SubmitPayroll_EmpID FROM hrm_payroll_submit_payroll_detail spd WHERE spd.SubmitPayroll_ID = SID)
								GROUP BY s.Salary_EmpID ) tbl1

							LEFT JOIN (hrm_payroll_allowance_employee ae INNER JOIN hrm_payroll_allowance a ON a.Allowance_ID = ae.Allowance_ID) ON ae.Allowance_EmpID = tbl1.Salary_EmpID
							GROUP BY tbl1.Salary_EmpID ) tbl2

					
					LEFT JOIN (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)) 
					ON bd.Bonus_EmpID = tbl2.Salary_EmpID
					GROUP BY tbl2.Salary_EmpID) tbl3

				LEFT JOIN (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')) o
				ON o.od_empid = tbl3.Salary_EmpID AND o.od_date >= tbl3.SubmitPayroll_StartDate AND o.od_date <= tbl3.SubmitPayroll_EndDate
				GROUP BY tbl3.Salary_EmpID) tbl4

			LEFT JOIN (SELECT COALESCE(SubmitPayroll_DeductionEmpID, '') AS 'Deduction_EmpID', COALESCE(SubmitPayroll_DeductionAmount, 0) AS 'dd_amount' 
									FROM hrm_payroll_submit_payroll_detail_deduction
									WHERE SubmitPayroll_ID = SID) de 
			ON de.Deduction_EmpID = tbl4.Salary_EmpID
			GROUP BY tbl4.Salary_EmpID) tbl5

		LEFT JOIN (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')) l ON(l.Leave_EmpID = tbl5.Salary_EmpID AND l.LeaveD_Date >= tbl5.SubmitPayroll_StartDate AND l.LeaveD_Date <= tbl5.SubmitPayroll_EndDate) 
		LEFT JOIN hrm_timesheet_leave_type lt ON l.LeaveD_TypeID = lt.LeaveType_ID AND LOWER(LeaveType_PayStatus) = 'unpaid'
		GROUP BY tbl5.Salary_EmpID) tbl6

	LEFT JOIN hrm_timesheet_attendance att ON att.Att_EmpID = tbl6.Salary_EmpID AND att.Att_Date >= tbl6.SubmitPayroll_StartDate AND att.Att_Date <= tbl6.SubmitPayroll_EndDate
	GROUP BY tbl6.Salary_EmpID) tbl7

LEFT JOIN ame_mt_emp e ON tbl7.Salary_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 e.var_hrm_status NOT IN('Death', 'Resigned', 'Retired', 'Terminated');
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetSubmitPayrollDetailPaidByEmpID`;
DELIMITER |
CREATE PROCEDURE `spHRMGetSubmitPayrollDetailPaidByEmpID`(SUID varchar(255))
    DETERMINISTIC
BEGIN

	DECLARE SEmpID VARCHAR(255);

	SELECT var_empid INTO SEmpID FROM ame_user WHERE var_id = SUID;

	SELECT 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,DATE(SubmitPayroll_CreateDate) AS 'SubmitPayroll_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_internal_id, '') AS Emp_InternalID
	FROM hrm_payroll_submit_payroll_detail pd 
	LEFT JOIN ame_mt_emp e ON(e.var_id = pd.SubmitPayroll_EmpID) 
	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 SubmitPayroll_EmpID = SEmpID
	ORDER BY pd.SubmitPayroll_CreateDate DESC LIMIT 1;

END |
DELIMITER ;

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

	SELECT 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,SubmitPayroll_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_internal_id, '') AS Emp_InternalID
	FROM hrm_payroll_submit_payroll_detail pd 
	LEFT JOIN ame_mt_emp e ON(e.var_id = pd.SubmitPayroll_EmpID)
	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 SubmitPayroll_ID = SID;

	SELECT SubmitPayroll_ID,SubmitPayroll_PayrollID,SubmitPayroll_Date,SubmitPayroll_StartDate,SubmitPayroll_EndDate,
	p.Payroll_ID,p.Payroll_Name,p.Payroll_Type,p.Payroll_StartDate,p.Payroll_LastSubmitDate,p.Payroll_SubmitDate
	FROM hrm_payroll_submit_payroll b LEFT JOIN hrm_payroll p ON(b.SubmitPayroll_PayrollID=p.Payroll_ID)
	WHERE SubmitPayroll_ID=SID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetSubmitPayrollMaster`;
DELIMITER |
CREATE PROCEDURE `spHRMGetSubmitPayrollMaster`(SID varchar(255))
    DETERMINISTIC
BEGIN
			SELECT SubmitPayroll_ID,SubmitPayroll_PayrollID,SubmitPayroll_Date,SubmitPayroll_StartDate,SubmitPayroll_EndDate,
			p.Payroll_ID,p.Payroll_Name,p.Payroll_Type,p.Payroll_StartDate,p.Payroll_LastSubmitDate,p.Payroll_SubmitDate
			FROM hrm_payroll_submit_payroll b LEFT JOIN hrm_payroll p ON(b.SubmitPayroll_PayrollID=p.Payroll_ID)
			WHERE SubmitPayroll_ID=SID;

			SELECT COALESCE(var_id, '') AS AccID, COALESCE(var_name, '') AS AccName, COALESCE(int_typeid, 0) AS AccTypeID, COALESCE(tin_inactive, 0) AS ActiveStatus FROM ame_mt_acc WHERE tin_inactive='0';
			
			SELECT COALESCE(var_accid, '') AS AccID FROM ame_mt_acc_set WHERE var_type = 'Payroll' AND var_groupid = 'CashAcc';

			SELECT COALESCE(var_accid, '') AS AccID FROM ame_mt_acc_set WHERE var_type = 'Payroll' AND var_groupid = 'Acc';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetTblNumberPrefix`;
DELIMITER |
CREATE PROCEDURE `spHRMGetTblNumberPrefix`(IN MID varchar(255), OUT ID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE TempID VARCHAR(255);
	DECLARE Num LONG;
	DECLARE N INT;
	SELECT var_id,int_lastid,int_length INTO TempID, Num, N FROM  ame_sys_prefix WHERE var_modid = MID ;
	IF Num = 0 THEN
		SET Num = 1;
	END IF;
	SET ID = CONCAT(TempID, '-',LPAD(CONCAT(Num,''),N,'0'));

END |
DELIMITER ;

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

	SELECT LeaveType_ID,LeaveType_Name,LeaveType_PayStatus,LeaveType_Year,LeaveType_AmountAllowed,LeaveType_GenderRestriction,LeaveType_PayType,LeaveType_PayAmount,LeaveType_BaseBalance
	FROM hrm_timesheet_leave_type WHERE LeaveType_ID = ID;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetTimeZone`;
DELIMITER |
CREATE PROCEDURE `spHRMGetTimeZone`()
    DETERMINISTIC
BEGIN
	DECLARE tz VARCHAR(20) DEFAULT('');
	SELECT Setting_Value INTO tz FROM hrm_setting WHERE Setting_Type = 'TimeZone' AND Setting_Name = 'TimeZone';
	SELECT convert_tz(now(), @@session.time_zone, tz) AS 'Timezone';

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetUser`;
DELIMITER |
CREATE PROCEDURE `spHRMGetUser`(UserID varchar(255), ID varchar(255))
    DETERMINISTIC
BEGIN
	if UserID = 'ADMIN' THEN
		SELECT COALESCE(u.var_id, '') AS UID, COALESCE(u.var_hrm_utype, '') AS UType, COALESCE(var_name, '') AS UName, COALESCE(var_pwd, '') AS UPassword,COALESCE(u.var_hrm_role, '') AS UHRMRoleID, COALESCE(u.var_empid, '') AS EmpID, COALESCE(tin_inactive, 0) AS UStatus FROM ame_user u WHERE u.var_id = ID;
	ELSE
		SELECT COALESCE(u.var_id, '') AS UID, COALESCE(u.var_hrm_utype, '') AS UType, COALESCE(var_name, '') AS UName, COALESCE(var_pwd, '') AS UPassword,COALESCE(u.var_hrm_role, '') AS UHRMRoleID, COALESCE(u.var_empid, '') AS EmpID, COALESCE(tin_inactive, 0) AS UStatus FROM ame_user u WHERE u.var_id = ID AND u.var_id <> 'ADMIN';
	END IF;
	

	SELECT COALESCE(var_id, '') AS UID, COALESCE(var_appid, '') AS AppID FROM ame_user_app WHERE var_id = ID;

	SELECT RM_ID,RM_Name,RM_Des,RM_Status	FROM hrm_role b	ORDER BY b.RM_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_id, '') AS 'PositionID', 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_internal_id, '') AS Emp_InternalID
	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)
	WHERE e.var_id NOT IN(SELECT var_empid FROM ame_user WHERE var_id <> Id)
	ORDER BY e.var_id;

END |
DELIMITER ;

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

	SELECT COALESCE(u.var_id, '') AS UID
	,COALESCE(var_hrm_utype,'') AS UType
	,COALESCE(u.var_name,'') AS UName
	,COALESCE(var_pwd,'') AS UPassword
	,COALESCE(var_hrm_role,'') AS UHRMRoleID
	,COALESCE(var_appid,'') AS AppID
	,COALESCE(e.var_img,'') AS EmpImg
	,COALESCE(e.var_name,'') AS EmpName
	FROM ame_user u 
	INNER JOIN ame_user_app up ON(u.var_id = up.var_id AND up.var_appid = 'HRM')
	LEFT JOIN ame_mt_emp e ON(e.var_id = u.var_empid)
	WHERE u.var_id = ID AND u.tin_inactive = 0 LIMIT 1;


END |
DELIMITER ;

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

	SELECT COALESCE(u.var_id, '') AS UID, COALESCE(u.var_hrm_utype, '') AS UType, COALESCE(u.var_name, '') AS UName, COALESCE(var_pwd, '') AS UPassword, COALESCE(u.var_hrm_role, '') AS UHRMRoleID, COALESCE(up.var_appid, '') AS AppID, COALESCE(e.var_img, '') AS EmpImg, COALESCE(e.var_name, '') AS EmpName
	FROM ame_user u 
	INNER JOIN ame_user_app up ON(u.var_id=up.var_id AND up.var_appid='HRM')
	LEFT JOIN ame_mt_emp e ON(u.var_empid = e.var_id)
	WHERE u.var_name = ID AND u.tin_inactive = 0 LIMIT 1;

	

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetUserSub`;
DELIMITER |
CREATE PROCEDURE `spHRMGetUserSub`(UserID varchar(255))
    DETERMINISTIC
BEGIN
	SELECT RM_ID,RM_Name,RM_Des,RM_Status	FROM hrm_role b	ORDER BY b.RM_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_internal_id, '') AS Emp_InternalID
	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)
	WHERE e.var_id NOT IN(SELECT var_empid FROM ame_user)
	ORDER BY e.var_id;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMGetWorkShift`;
DELIMITER |
CREATE PROCEDURE `spHRMGetWorkShift`(ID varchar(255))
    DETERMINISTIC
BEGIN
	SELECT Shift_ID,Shift_Name,Shift_Type,Shift_Description FROM hrm_timesheet_workshift WHERE Shift_ID = ID;
	
	SELECT 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
  FROM hrm_timesheet_workshift_detail WHERE Shift_ID = ID ORDER BY FIELD(Shift_Day, 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', '');
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMLanguage`;
DELIMITER |
CREATE PROCEDURE `spHRMLanguage`(IN ItemID Varchar(255))
    DETERMINISTIC
BEGIN
		SELECT l.LanguageName, l.LanguageInKhmer
		FROM hrm_language l
		WHERE l.LanguageName LIKE ItemID OR l.LanguageInKhmer LIKE ItemID
		ORDER BY l.LanguageName;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMLanguageCount`;
DELIMITER |
CREATE PROCEDURE `spHRMLanguageCount`(Filter Varchar(255),IN ItemID Varchar(255))
    DETERMINISTIC
BEGIN
IF Filter = "Language" THEN
	SELECT COUNT(l.LanguageName)
	FROM hrm_language l
	WHERE l.LanguageName LIKE ItemID OR l.LanguageInKhmer LIKE ItemID
	ORDER BY l.LanguageName;
ELSE
	SELECT COUNT(l.LanguageName)
	FROM hrm_language l
	ORDER BY l.LanguageName;
END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMLanguageOffset`;
DELIMITER |
CREATE PROCEDURE `spHRMLanguageOffset`(IN ID varchar(255))
    DETERMINISTIC
BEGIN
SET @RowIndex = -1;
SELECT RowIndex
FROM (SELECT @RowIndex:=@RowIndex + 1 As RowIndex,LanguageName FROM hrm_language ORDER BY LanguageName) AS tbl
WHERE  LanguageName = ID ;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMLanguageSearch`;
DELIMITER |
CREATE PROCEDURE `spHRMLanguageSearch`(Filter Varchar(255),ItemID Varchar(255), Limited INT(11),Offseted INT(11))
    DETERMINISTIC
BEGIN
	IF Filter = "Language" THEN
		SELECT l.LanguageName, l.LanguageInKhmer
		FROM hrm_language l
		WHERE l.LanguageName LIKE ItemID OR l.LanguageInKhmer LIKE ItemID
		ORDER BY l.LanguageName LIMIT Limited OFFSET Offseted;
	ELSE
		SELECT l.LanguageName, l.LanguageInKhmer
		FROM hrm_language l
		ORDER BY l.LanguageName LIMIT Limited OFFSET Offseted;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMListEmployee`;
DELIMITER |
CREATE PROCEDURE `spHRMListEmployee`()
    DETERMINISTIC
BEGIN
	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_id, '') AS 'PositionID', 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
	,COALESCE(e.var_hrm_status, '') AS EmpStatus, COALESCE(e.var_tel1, '') AS Emp_Tel1, COALESCE(e.var_hrm_company_tel, '') AS Emp_CompanyTel
	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)
	ORDER BY e.var_id DESC;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMLoadRAttendance`;
DELIMITER |
CREATE PROCEDURE `spHRMLoadRAttendance`(IN userid varchar(255), IN `FDate` date,IN `TDate` date)
    DETERMINISTIC
BEGIN
DECLARE CompanyName VARCHAR(255) DEFAULT("");
DECLARE Deduct_Leave_Balance_Hourly VARCHAR(255);
SET @sql1 = NULL;
SET @sql2 = NULL;
SET @sql3 = NULL;
SET @sql4 = null;
SET group_concat_max_len = 1000000;

SELECT Setting_Value INTO Deduct_Leave_Balance_Hourly FROM hrm_setting WHERE Setting_Type = 'Leave' AND Setting_Name = 'Deduct_Leave_Balance_Hourly';

Select COALESCE(GROUP_CONCAT(DISTINCT CONCAT("COALESCE(MAX(`",selected_date,"`),0)") SEPARATOR "+"),"")
INTO @sql4 from 
	(select adddate(FDate,t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between FDate and TDate;

select COALESCE(GROUP_CONCAT(DISTINCT CONCAT("COALESCE(IF(MAX(`",selected_date,"`) > 1, 1, MAX(`",selected_date,"`)), 0) AS `",DAY(selected_date), "-", MONTH(selected_date),"`, GROUP_CONCAT(`", selected_date, "_Status` SEPARATOR '') AS `",DAY(selected_date), "-", MONTH(selected_date),"_Status`") ORDER BY selected_date),"")
INTO @sql1 from 
	(select adddate(FDate,t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between FDate and TDate;

IF Deduct_Leave_Balance_Hourly = 'Half of Day' THEN

	SELECT COALESCE(GROUP_CONCAT(DISTINCT CONCAT("CASE Att_Date WHEN \'" ,v.selected_date,"\' THEN (SUM(IF(a.Att_RStatus LIKE '%AB%', CEIL(fnHRMTimeToFloat(a.Att_ABDurationDeduct)*2) / 2, 0)) / fnHRMCheckWorkHour(a.Att_EmpID)) + (SUM(IF(a.Att_RStatus LIKE '%LE%', ld.Leave_Amount, 0))) ELSE NULL END AS `",v.selected_date,"`", ",CASE Att_Date WHEN \'" ,v.selected_date,"\' THEN CONCAT( IF(a.Att_RStatus LIKE '%AB%', CONCAT(DAY(Att_Date), '=Unpaid;'), ''), IF(a.Att_RStatus LIKE '%LE%', CONCAT(DAY(Att_Date), '=', lt.LeaveType_Name, ';'), '')) ELSE NULL END AS '",v.selected_date, "_Status", "'") order by v.selected_date),"")
	INTO @sql2 from 
		(select adddate(FDate,t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
		(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
		(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
		(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
		(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
		(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
	WHERE date(v.selected_date) BETWEEN FDate AND TDAte;
	
ELSE

	SELECT COALESCE(GROUP_CONCAT(DISTINCT CONCAT("CASE Att_Date WHEN \'" ,v.selected_date,"\' THEN (SUM(IF(a.Att_RStatus LIKE '%AB%', CEIL(fnHRMTimeToFloat(a.Att_ABDurationDeduct)*2) / 2, 0)) / fnHRMCheckWorkHour(a.Att_EmpID)) + (SUM(IF(a.Att_RStatus LIKE '%LE%' AND ld.LeaveD_Duration = 'Hourly', COALESCE(ld.Leave_Total, 0), 0)) / fnHRMCheckWorkHour(a.Att_EmpID)) + (SUM(IF(a.Att_RStatus LIKE '%LE%' AND ld.LeaveD_Duration = 'Full Day', 1, 0))) ELSE NULL END AS `",v.selected_date,"`", ",CASE Att_Date WHEN \'" ,v.selected_date,"\' THEN CONCAT( IF(a.Att_RStatus LIKE '%AB%', CONCAT(DAY(Att_Date), '=Unpaid;'), ''), IF(a.Att_RStatus LIKE '%LE%', CONCAT(DAY(Att_Date), '=', lt.LeaveType_Name, ';'), '')) ELSE NULL END AS '",v.selected_date, "_Status", "'") order by v.selected_date),"")
	INTO @sql2 from 
		(select adddate(FDate,t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
		(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
		(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
		(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
		(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
		(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
	WHERE date(v.selected_date) BETWEEN FDate AND TDAte;

END IF;

IF COALESCE(@sql1, '') <> '' THEN
	SET @sql1 = CONCAT(",", @sql1);
END IF;
IF COALESCE(@sql2, '') <> '' THEN
	SET @sql2 = CONCAT(",", @sql2);
END IF;

SET @sql3 = CONCAT("SELECT tbl.Att_EmpID, tbl.EmpName, tbl.EmpImg, tbl.EmpPosition, tbl.Department_Name, tbl.Emp_InternalID ",@sql1,",fnHRMRound(", @sql4, ", 2) AS TOTAL FROM (SELECT Att_EmpID,COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(var_img, '') AS EmpImg, COALESCE(pos.var_name, '') AS EmpPosition, dep.Department_Name, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, Att_Date ",@sql2," FROM hrm_timesheet_attendance a
																																																																													LEFT JOIN (hrm_timesheet_leave l LEFT JOIN (hrm_timesheet_leave_detail ld LEFT JOIN hrm_timesheet_leave_type lt ON(ld.LeaveD_TypeID = lt.LeaveType_ID)) ON(l.Leave_ID = ld.LeaveD_ID)) ON(a.Att_EmpID = l.Leave_EmpID AND a.Att_Date = ld.LeaveD_Date)
																																																																													LEFT JOIN ame_mt_emp e ON(a.Att_EmpID = e.var_id)
																																																																													LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
																																																																													LEFT JOIN hrm_emp_department dep ON(dep.Department_ID = e.var_hrm_department_id) WHERE a.Att_Date BETWEEN '", FDate,"' AND '", TDate,"' AND e.var_hrm_status NOT IN('Death', 'Resigned', 'Retired', 'Terminated') GROUP BY a.Att_EmpID, a.Att_Date) as tbl GROUP BY tbl.Att_EmpID ORDER BY tbl.Att_EmpID");
PREPARE stmt FROM @sql3;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SELECT Setting_Value INTO CompanyName FROM hrm_setting WHERE Setting_Type = "Company" AND Setting_Name = "Name";
SELECT CompanyName;

CALL spHRMLoadRLeaveBalanceByType(userid, FDate, TDate);
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMLoadREmployee`;
DELIMITER |
CREATE PROCEDURE `spHRMLoadREmployee`(IN userid varchar(255), SFrom varchar(255), STo varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE CompanyName VARCHAR(255) DEFAULT("");

	SELECT COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_img, '') AS EmpImg, COALESCE(pos.var_name, '') AS EmpPosition, COALESCE(e.var_hrm_department_id, '') AS Emp_DepartmentID, dep.Department_Name, COALESCE(e.var_hrm_sex, '') AS EmpSex, COALESCE(e.var_hrm_marital_status, '') AS Emp_MaritalStatus, COALESCE(e.var_hrm_branch_id, '') AS Emp_BranchID, br.Branch_Name, COALESCE(e.dat_hrm_joindate, NULL) AS Emp_JoinDate, COALESCE(e.dat_hrm_enddateprobation, NULL) AS Emp_EndDateProbation, COALESCE(e.dat_hrm_dob, NULL) AS EmpDOB, 
	CONCAT(e.var_hrm_permanent_home_no, IF(e.var_hrm_permanent_home_no <> '', ', ', ''), e.var_hrm_permanent_street, IF(e.var_hrm_permanent_street <> '', ', ', ''), e.var_hrm_permanent_village, IF(e.var_hrm_permanent_village <> '', ', ', ''), e.var_hrm_permanent_commune, IF(e.var_hrm_permanent_commune <> '', ', ', ''), e.var_hrm_permanent_district, IF(e.var_hrm_permanent_district <> '', ', ', ''), e.var_hrm_permanent_city, IF(e.var_hrm_permanent_city <> '', ' City', '')) AS 'EmpPOB',
	CONCAT(var_addr1, IF(e.var_addr1 <> '', ', ', ''), e.var_addr2, IF(e.var_addr2 <> '', ', ', ''), e.var_addr3, IF(e.var_addr3 <> '', ', ', ''), e.var_addr4, IF(e.var_addr4 <> '', ', ', ''), e.var_addr5, IF(e.var_addr5 <> '', ', ', ''), e.var_addr6, IF(e.var_addr6 <> '', ' City', '')) AS 'EmpPresentAddress',
	COALESCE(e.var_hrm_company_tel, '') AS Emp_CompanyTel, COALESCE(e.var_tel1, '') AS EmpTel1, COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail, COALESCE(e.var_email, '') AS EmpEmail, GROUP_CONCAT(DISTINCT ed.Edu_School SEPARATOR '\n') AS 'edu_school', GROUP_CONCAT(DISTINCT CONCAT(ed.Edu_Degree, " of ", ed.Edu_Major) SEPARATOR '\n') AS 'edu_degree',
	GROUP_CONCAT(DISTINCT lan.`Language` SEPARATOR '\n') AS 'lan_language', 
	(SELECT GROUP_CONCAT(l.Language_ReadLevel ORDER BY l.`Language` SEPARATOR '\n') FROM hrm_employee_language l WHERE l.Emp_ID = e.var_id ORDER BY l.`Language`) AS 'lan_read',
	(SELECT GROUP_CONCAT(l.Language_SpeakLevel ORDER BY l.`Language` SEPARATOR '\n') FROM hrm_employee_language l WHERE l.Emp_ID = e.var_id ORDER BY l.`Language`) AS 'lan_speak',
	(SELECT GROUP_CONCAT(l.Language_WriteLevel ORDER BY l.`Language` SEPARATOR '\n') FROM hrm_employee_language l WHERE l.Emp_ID = e.var_id ORDER BY l.`Language`) AS 'lan_write',
	(SELECT GROUP_CONCAT(l.Language_UnderstandLevel ORDER BY l.`Language` SEPARATOR '\n') FROM hrm_employee_language l WHERE l.Emp_ID = e.var_id ORDER BY l.`Language`) AS 'Language_UnderstandLevel',
	GROUP_CONCAT(DISTINCT ex.Ex_Company SEPARATOR '\n') AS 'ex_company', 
	(SELECT GROUP_CONCAT(ex.Ex_Position ORDER BY ex.Ex_AutoID SEPARATOR '\n') FROM hrm_employee_experience ex WHERE ex.Emp_ID = e.var_id ORDER BY ex.Ex_AutoID) AS 'ex_position',
	GROUP_CONCAT(DISTINCT sk.Skill_Name SEPARATOR '\n') AS 'sk_name',
	GROUP_CONCAT(DISTINCT CONCAT(fam.Fam_Relative, " : ", fam.Fam_Tel) SEPARATOR '\n') AS 'fam_family'
	FROM ame_mt_emp e
	LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
	LEFT JOIN hrm_emp_department dep ON(e.var_hrm_department_id = dep.Department_ID)
	LEFT JOIN hrm_emp_branch br ON(br.Branch_ID = e.var_hrm_branch_id)
	LEFT JOIN hrm_employee_education ed ON(ed.Emp_ID = e.var_id)
	LEFT JOIN (SELECT l.`Language`, l.Emp_ID FROM hrm_employee_language l ORDER BY l.`Language`) lan ON(lan.Emp_ID = e.var_id)
	LEFT JOIN (SELECT ex.Emp_ID,Ex_Company FROM hrm_employee_experience ex ORDER BY ex.Ex_AutoID) ex ON(ex.Emp_ID = e.var_id)
	LEFT JOIN hrm_employee_skill sk ON(sk.Emp_ID = e.var_id)
	LEFT JOIN hrm_employee_family fam ON(fam.Emp_ID = e.var_id)
	WHERE IF(SFrom = 'All', TRUE, e.var_id >= SFrom) AND IF(STo = 'All', TRUE, e.var_id <= STo)
	GROUP BY e.var_id
	ORDER BY e.var_id;

	SELECT Setting_Value INTO CompanyName FROM hrm_setting WHERE Setting_Type = "Company" AND Setting_Name = "Name";
	SELECT CompanyName;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMLoadRLateDuration`;
DELIMITER |
CREATE PROCEDURE `spHRMLoadRLateDuration`(IN userid varchar(255), IN `FDate` date,IN `TDate` date)
    DETERMINISTIC
BEGIN
DECLARE CompanyName VARCHAR(255) DEFAULT("");
SET @sql1 = NULL;
SET @sql2 = NULL;
SET @sql3 = NULL;
SET @sql4 = null;
SET group_concat_max_len = 1000000;

SELECT COALESCE(GROUP_CONCAT(DISTINCT CONCAT("COALESCE(MAX(`",po.Att_Date,"`),0)") SEPARATOR "+"),"")
INTO @sql4 from hrm_timesheet_attendance po
WHERE date(po.Att_Date) BETWEEN FDate AND TDate;

select COALESCE(GROUP_CONCAT(DISTINCT CONCAT("COALESCE(MAX(`",selected_date,"`), 0) AS `",DAY(selected_date), "-", MONTH(selected_date),"`") ORDER BY selected_date),"")
INTO @sql1 from 
	(select adddate(FDate,t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between FDate and TDate;

SELECT COALESCE(GROUP_CONCAT(DISTINCT CONCAT("CASE Att_Date WHEN \'" ,v.selected_date,"\' THEN fnHRMRound(fnHRMTimeToFloat(Att_LateDurationDeduct), 2) ELSE NULL END AS `",v.selected_date,"`") order by v.selected_date),"")
INTO @sql2 from hrm_timesheet_attendance po RIGHT JOIN
	(select adddate(FDate,t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
	(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v ON po.Att_Date = v.selected_date
WHERE date(v.selected_date) BETWEEN FDate AND TDate;

IF COALESCE(@sql1, '') <> '' THEN
	SET @sql1 = CONCAT(",", @sql1);
END IF;
IF COALESCE(@sql2, '') <> '' THEN
	SET @sql2 = CONCAT(",", @sql2);
END IF;
IF COALESCE(@sql4, '') = '' THEN
	SET @sql4 = "0";
END IF;

SET @sql3 = CONCAT("SELECT tbl.Att_EmpID, tbl.EmpName, tbl.EmpImg, tbl.EmpPosition, tbl.Department_Name, tbl.Emp_InternalID ",@sql1,",fnHRMRound(", @sql4, ", 2) AS TOTAL FROM (SELECT Att_EmpID, COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(var_img, '') AS EmpImg, COALESCE(pos.var_name, '') AS EmpPosition, dep.Department_Name, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, Att_Date ",@sql2," FROM hrm_timesheet_attendance a 
																																																																										LEFT JOIN ame_mt_emp e ON(a.Att_EmpID = e.var_id)
																																																																										LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
																																																																										LEFT JOIN hrm_emp_department dep ON(dep.Department_ID = e.var_hrm_department_id) WHERE a.Att_Date BETWEEN '", FDate,"' AND '", TDate,"' AND e.var_hrm_status NOT IN('Death', 'Resigned', 'Retired', 'Terminated')) as tbl GROUP BY tbl.Att_EmpID ORDER BY tbl.Att_EmpID");
PREPARE stmt FROM @sql3;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SELECT Setting_Value INTO CompanyName FROM hrm_setting WHERE Setting_Type = "Company" AND Setting_Name = "Name";
SELECT CompanyName;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMLoadRLeaveBalanceByType`;
DELIMITER |
CREATE PROCEDURE `spHRMLoadRLeaveBalanceByType`(IN userid varchar(255), IN `FDate` date,IN `TDate` date)
    DETERMINISTIC
BEGIN
DECLARE CompanyName VARCHAR(255) DEFAULT("");
DECLARE Deduct_Leave_Balance_Hourly VARCHAR(255);
SET @sql1 = NULL;
SET @sql2 = NULL;
SET @sql3 = NULL;
SET group_concat_max_len = 1000000;

SELECT Setting_Value INTO Deduct_Leave_Balance_Hourly FROM hrm_setting WHERE Setting_Type = 'Leave' AND Setting_Name = 'Deduct_Leave_Balance_Hourly';

select lt.LeaveType_Name
from hrm_timesheet_leave_type lt
where lt.LeaveType_PayStatus = "Paid" AND lt.LeaveType_Year = YEAR(TDate)
ORDER BY lt.LeaveType_ID;

select COALESCE(GROUP_CONCAT(DISTINCT CONCAT("COALESCE(SUM(`",lt.LeaveType_Name,"`), 0) AS `", lt.LeaveType_Name, "`, fnHRMCheckLeaveBaanceRate(EmpID, '",lt.LeaveType_BaseBalance, "', '", lt.LeaveType_AmountAllowed, "') - COALESCE(SUM(`",lt.LeaveType_Name,"_Old`), 0) AS `", lt.LeaveType_Name, "_Old`") ORDER BY lt.LeaveType_ID),"")
INTO @sql1 from hrm_timesheet_leave_type lt
where lt.LeaveType_PayStatus = "Paid" AND lt.LeaveType_Year = YEAR(TDate);

IF Deduct_Leave_Balance_Hourly = 'Half of Day' THEN

	SELECT COALESCE(GROUP_CONCAT(DISTINCT CONCAT("CASE lt.LeaveType_ID WHEN \'" ,lt.LeaveType_ID,"\' THEN SUM(IF(ld.LeaveD_Date BETWEEN '", FDate, "' AND '", TDate,"', COALESCE(ld.Leave_Amount, 0), 0)) ELSE NULL END AS `",lt.LeaveType_Name,"`, CASE lt.LeaveType_ID WHEN \'" ,lt.LeaveType_ID,"\' THEN  SUM(IF(ld.LeaveD_Date < '", FDate, "', COALESCE(ld.Leave_Amount, 0), 0)) ELSE NULL END AS `",lt.LeaveType_Name,"_Old`") order by lt.LeaveType_ID),"")
	INTO @sql2 from hrm_timesheet_leave_type lt
	where lt.LeaveType_PayStatus = "Paid" AND lt.LeaveType_Year = YEAR(TDate);
	
ELSE

	SELECT COALESCE(GROUP_CONCAT(DISTINCT CONCAT("CASE lt.LeaveType_ID WHEN \'" ,lt.LeaveType_ID,"\' THEN (SUM(IF(ld.LeaveD_Duration = 'Hourly' AND ld.LeaveD_Date BETWEEN '", FDate, "' AND '", TDate,"', COALESCE(ld.Leave_Total, 0), 0)) / fnHRMCheckWorkHour(e.var_id)) + (SUM(IF(ld.LeaveD_Duration = 'Full Day' AND ld.LeaveD_Date BETWEEN '", FDate, "' AND '", TDate,"', 1, 0))) ELSE NULL END AS `",lt.LeaveType_Name,"`, CASE lt.LeaveType_ID WHEN \'" ,lt.LeaveType_ID,"\' THEN  (SUM(IF(ld.LeaveD_Duration = 'Hourly' AND ld.LeaveD_Date < '", FDate, "', COALESCE(ld.Leave_Total, 0), 0)) / fnHRMCheckWorkHour(e.var_id)) + (SUM(IF(ld.LeaveD_Duration = 'Full Day' AND ld.LeaveD_Date < '", FDate, "', 1, 0))) ELSE NULL END AS `",lt.LeaveType_Name,"_Old`") order by lt.LeaveType_ID),"")
	INTO @sql2 from hrm_timesheet_leave_type lt
	where lt.LeaveType_PayStatus = "Paid" AND lt.LeaveType_Year = YEAR(TDate);

END IF;

IF COALESCE(@sql1, '') <> '' THEN
	SET @sql1 = CONCAT(",", @sql1);
END IF;
IF COALESCE(@sql2, '') <> '' THEN
	SET @sql2 = CONCAT(",", @sql2);
END IF;

SET @sql3 = CONCAT("SELECT tbl.EmpID ",@sql1," FROM (SELECT COALESCE(e.var_id, '') AS EmpID ",@sql2," FROM ame_mt_emp e
																																																			LEFT JOIN (hrm_timesheet_leave l LEFT JOIN (hrm_timesheet_leave_detail ld LEFT JOIN hrm_timesheet_leave_type lt ON(ld.LeaveD_TypeID = lt.LeaveType_ID)) ON(l.Leave_ID = ld.LeaveD_ID)) ON(l.Leave_EmpID = e.var_id AND LOWER(l.Leave_Status) <> 'rejected')
																																																			WHERE ld.LeaveD_Date <= '", TDate,"' AND e.var_hrm_status NOT IN('Death', 'Resigned', 'Retired', 'Terminated')
																																																			GROUP BY e.var_id, ld.LeaveD_TypeID) as tbl GROUP BY tbl.EmpID ORDER BY tbl.EmpID");
PREPARE stmt FROM @sql3;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMLoadRLeaveBalanceByTypeWithLateByYear`;
DELIMITER |
CREATE PROCEDURE `spHRMLoadRLeaveBalanceByTypeWithLateByYear`(IN userid varchar(255), IN `SYear` int)
    DETERMINISTIC
BEGIN
DECLARE CompanyName VARCHAR(255) DEFAULT("");
DECLARE Deduct_Leave_Balance_Hourly VARCHAR(255);
SET @sql1 = NULL;
SET @sql2 = NULL;
SET @sql3 = NULL;
SET group_concat_max_len = 1000000;

SELECT Setting_Value INTO Deduct_Leave_Balance_Hourly FROM hrm_setting WHERE Setting_Type = 'Leave' AND Setting_Name = 'Deduct_Leave_Balance_Hourly';

select lt.LeaveType_Name
from hrm_timesheet_leave_type lt
where lt.LeaveType_PayStatus = "Paid" AND lt.LeaveType_Year = SYear AND LOWER(lt.LeaveType_Name) LIKE '%annual%'
ORDER BY lt.LeaveType_ID;

select COALESCE(GROUP_CONCAT(DISTINCT CONCAT("COALESCE(SUM(`",lt.LeaveType_Name,"`), 0) AS `", lt.LeaveType_Name, "`, fnHRMCheckLeaveBaanceRate(EmpID, '",lt.LeaveType_BaseBalance, "', '", lt.LeaveType_AmountAllowed, "') AS `", lt.LeaveType_Name, "_Allowed`") ORDER BY lt.LeaveType_ID),"")
INTO @sql1 from hrm_timesheet_leave_type lt
where lt.LeaveType_PayStatus = "Paid" AND lt.LeaveType_Year = SYear AND LOWER(lt.LeaveType_Name) LIKE '%annual%';

IF Deduct_Leave_Balance_Hourly = 'Half of Day' THEN

	SELECT COALESCE(GROUP_CONCAT(DISTINCT CONCAT("CASE lt.LeaveType_ID WHEN \'" ,lt.LeaveType_ID,"\' THEN SUM(COALESCE(ld.Leave_Amount, 0)) ELSE NULL END AS `",lt.LeaveType_Name,"`") order by lt.LeaveType_ID),"")
	INTO @sql2 from hrm_timesheet_leave_type lt
	where lt.LeaveType_PayStatus = "Paid" AND lt.LeaveType_Year = SYear AND LOWER(lt.LeaveType_Name) LIKE '%annual%';
	
ELSE

	SELECT COALESCE(GROUP_CONCAT(DISTINCT CONCAT("CASE lt.LeaveType_ID WHEN \'" ,lt.LeaveType_ID,"\' THEN (SUM(IF(ld.LeaveD_Duration = 'Hourly', COALESCE(ld.Leave_Total, 0), 0)) / fnHRMCheckWorkHour(e.var_id)) + (SUM(IF(ld.LeaveD_Duration = 'Full Day', 1, 0))) ELSE NULL END AS `",lt.LeaveType_Name,"`") order by lt.LeaveType_ID),"")
	INTO @sql2 from hrm_timesheet_leave_type lt
	where lt.LeaveType_PayStatus = "Paid" AND lt.LeaveType_Year = SYear AND LOWER(lt.LeaveType_Name) LIKE '%annual%';

END IF;

IF COALESCE(@sql1, '') <> '' THEN
	SET @sql1 = CONCAT(",", @sql1);
END IF;
IF COALESCE(@sql2, '') <> '' THEN
	SET @sql2 = CONCAT(",", @sql2);
END IF;

SET @sql3 = CONCAT("SELECT tbl.EmpID, tbl.Emp_InternalID, tbl.EmpName, tbl.EmpPosition, tbl.Emp_JoinDate, tbl.Emp_DateStatus, tbl.EmpImg, tbl.Department_Name, COALESCE(tbl.LateDuration, 0) AS 'LateDuration' ",@sql1," FROM (SELECT COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, COALESCE(e.var_name, '') AS EmpName, COALESCE(pos.var_name, '') AS EmpPosition, COALESCE(e.dat_hrm_joindate, '') AS Emp_JoinDate, COALESCE(e.dat_hrm_date_status, '0000-00-00') AS Emp_DateStatus, COALESCE(e.var_img, '') AS EmpImg, dep.Department_Name, a.LateDuration ",@sql2," FROM ame_mt_emp e
																																																																																																														LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
																																																																																																														LEFT JOIN hrm_emp_department dep ON(e.var_hrm_department_id = dep.Department_ID)
																																																																																																														LEFT JOIN (hrm_timesheet_leave l LEFT JOIN (hrm_timesheet_leave_detail ld LEFT JOIN hrm_timesheet_leave_type lt ON(ld.LeaveD_TypeID = lt.LeaveType_ID)) ON(l.Leave_ID = ld.LeaveD_ID)) ON(l.Leave_EmpID = e.var_id AND LOWER(l.Leave_Status) <> 'rejected')
																																																																																																														LEFT JOIN (SELECT a.Att_EmpID, fnHRMRound(SUM(fnHRMRound(fnHRMTimeToFloat(Att_LateDurationDeduct), 2)), 2) AS 'LateDuration' FROM hrm_timesheet_attendance a
																																																																																																																					WHERE YEAR(a.Att_Date) = ", SYear,"
																																																																																																																					GROUP BY a.Att_EmpID) a ON(e.var_id = a.Att_EmpID)
																																																																																															WHERE (Year(ld.LeaveD_Date) = ", SYear," OR l.Leave_ID IS NULL) AND e.var_hrm_status NOT IN('Death', 'Resigned', 'Retired', 'Terminated')
																																																																																															GROUP BY e.var_id, ld.LeaveD_TypeID) as tbl GROUP BY tbl.EmpID ORDER BY tbl.EmpID");
PREPARE stmt FROM @sql3;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SELECT Setting_Value INTO CompanyName FROM hrm_setting WHERE Setting_Type = "Company" AND Setting_Name = "Name";
SELECT CompanyName;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMLoadRNewStaff`;
DELIMITER |
CREATE PROCEDURE `spHRMLoadRNewStaff`(IN userid varchar(255), IN `SDate` date)
    DETERMINISTIC
BEGIN
DECLARE CompanyName VARCHAR(255) DEFAULT("");

SELECT COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, COALESCE(e.var_name, '') AS EmpName, COALESCE(pos.var_name, '') AS EmpPosition, b.Branch_Name, COALESCE(e.dat_hrm_joindate, NULL) AS Emp_JoinDate, COALESCE(e.var_tel1, '') AS Emp_Tel1
FROM ame_mt_emp e
LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
LEFT JOIN hrm_emp_branch b ON(e.var_hrm_branch_id = b.Branch_ID)
WHERE MONTH(e.dat_hrm_joindate) = MONTH(SDate) AND YEAR(e.dat_hrm_joindate) = YEAR(SDate);

SELECT Setting_Value INTO CompanyName FROM hrm_setting WHERE Setting_Type = "Company" AND Setting_Name = "Name";
SELECT CompanyName;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMLoadRStaffResignLeaveBalanceByType`;
DELIMITER |
CREATE PROCEDURE `spHRMLoadRStaffResignLeaveBalanceByType`(IN userid varchar(255), IN `SDate` date)
    DETERMINISTIC
BEGIN
DECLARE CompanyName VARCHAR(255) DEFAULT("");
DECLARE Deduct_Leave_Balance_Hourly VARCHAR(255);
SET @sql1 = NULL;
SET @sql2 = NULL;
SET @sql3 = NULL;
SET group_concat_max_len = 1000000;

SET SDate = LAST_DAY(SDate);

SELECT Setting_Value INTO Deduct_Leave_Balance_Hourly FROM hrm_setting WHERE Setting_Type = 'Leave' AND Setting_Name = 'Deduct_Leave_Balance_Hourly';

select lt.LeaveType_Name
from hrm_timesheet_leave_type lt
where lt.LeaveType_PayStatus = "Paid" AND lt.LeaveType_Year = YEAR(SDate)
ORDER BY lt.LeaveType_ID;

select COALESCE(GROUP_CONCAT(DISTINCT CONCAT("COALESCE(SUM(`",lt.LeaveType_Name,"`), 0) AS `", lt.LeaveType_Name, "`, fnHRMCheckLeaveBaanceRate(EmpID, '",lt.LeaveType_BaseBalance, "', '", lt.LeaveType_AmountAllowed, "') AS `", lt.LeaveType_Name, "_Allowed`") ORDER BY lt.LeaveType_ID),"")
INTO @sql1 from hrm_timesheet_leave_type lt
where lt.LeaveType_PayStatus = "Paid" AND lt.LeaveType_Year = YEAR(SDate);

IF Deduct_Leave_Balance_Hourly = 'Half of Day' THEN

	SELECT COALESCE(GROUP_CONCAT(DISTINCT CONCAT("CASE lt.LeaveType_ID WHEN \'" ,lt.LeaveType_ID,"\' THEN SUM(COALESCE(ld.Leave_Amount, 0)) ELSE NULL END AS `",lt.LeaveType_Name,"`") order by lt.LeaveType_ID),"")
	INTO @sql2 from hrm_timesheet_leave_type lt
	where lt.LeaveType_PayStatus = "Paid" AND lt.LeaveType_Year = YEAR(SDate);
	
ELSE

	SELECT COALESCE(GROUP_CONCAT(DISTINCT CONCAT("CASE lt.LeaveType_ID WHEN \'" ,lt.LeaveType_ID,"\' THEN (SUM(IF(ld.LeaveD_Duration = 'Hourly', COALESCE(ld.Leave_Total, 0), 0)) / fnHRMCheckWorkHour(e.var_id)) + (SUM(IF(ld.LeaveD_Duration = 'Full Day', 1, 0))) ELSE NULL END AS `",lt.LeaveType_Name,"`") order by lt.LeaveType_ID),"")
	INTO @sql2 from hrm_timesheet_leave_type lt
	where lt.LeaveType_PayStatus = "Paid" AND lt.LeaveType_Year = YEAR(SDate);

END IF;

IF COALESCE(@sql1, '') <> '' THEN
	SET @sql1 = CONCAT(",", @sql1);
END IF;
IF COALESCE(@sql2, '') <> '' THEN
	SET @sql2 = CONCAT(",", @sql2);
END IF;
SET @sql3 = CONCAT("SELECT tbl.EmpID, tbl.Emp_InternalID, tbl.EmpName, tbl.EmpPosition, tbl.Emp_JoinDate, tbl.Emp_DateStatus ",@sql1," FROM (SELECT COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID, COALESCE(e.var_name, '') AS EmpName, COALESCE(pos.var_name, '') AS EmpPosition, COALESCE(e.dat_hrm_joindate, '0000-00-00') AS Emp_JoinDate, COALESCE(e.dat_hrm_date_status) AS Emp_DateStatus ",@sql2," FROM ame_mt_emp e
																																																																													LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
																																																																													LEFT JOIN (hrm_timesheet_leave l LEFT JOIN (hrm_timesheet_leave_detail ld LEFT JOIN hrm_timesheet_leave_type lt ON(ld.LeaveD_TypeID = lt.LeaveType_ID)) ON(l.Leave_ID = ld.LeaveD_ID)) ON(l.Leave_EmpID = e.var_id AND LOWER(l.Leave_Status) <> 'rejected')
																																																																													WHERE (ld.LeaveD_Date <= '", SDate,"' OR l.Leave_ID IS NULL) AND e.var_hrm_status IN('Death', 'Resigned', 'Retired', 'Terminated') AND MONTH(e.dat_hrm_date_status) = ", MONTH(SDate)," AND YEAR(e.dat_hrm_date_status) = ", YEAR(SDate),"
																																																																													GROUP BY e.var_id, ld.LeaveD_TypeID) as tbl GROUP BY tbl.EmpID ORDER BY tbl.EmpID");
PREPARE stmt FROM @sql3;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SELECT Setting_Value INTO CompanyName FROM hrm_setting WHERE Setting_Type = "Company" AND Setting_Name = "Name";
SELECT CompanyName;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMReportGetAttendance`;
DELIMITER |
CREATE PROCEDURE `spHRMReportGetAttendance`(SUserID varchar(255), SEmp Text, SFDate varchar(255), STDate varchar(255))
    DETERMINISTIC
BEGIN
	
	SET @SQL1 = CONCAT("SELECT 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_status, att_rstatus,
	COALESCE(e.var_id, '') AS empid, COALESCE(e.var_name, '') AS empname, COALESCE(e.var_hrm_internal_id, '') AS emp_internalid
	FROM hrm_timesheet_attendance att
	LEFT JOIN ame_mt_emp e ON(att_empid = e.var_id)
	WHERE e.var_id IN(", SEmp,") AND (att_date BETWEEN '", SFDate,"' AND '", STDate,"')
	ORDER BY e.var_id, att.att_date;");
	PREPARE St FROM @SQL1;
	EXECUTE St;
	DEALLOCATE PREPARE St;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMReportGetEmployee`;
DELIMITER |
CREATE PROCEDURE `spHRMReportGetEmployee`(SUserID varchar(255), SEmp Text)
    DETERMINISTIC
BEGIN
	
	SET @SQL1 = CONCAT("SELECT COALESCE(e.var_id, '') AS  empid, COALESCE(e.var_hrm_internal_id, '') AS emp_internalid, COALESCE(e.var_hrm_salutation, '') AS emp_salutation, COALESCE(e.var_name, '') AS empname, COALESCE(e.var_name_other, '') AS empnamekh, COALESCE(e.var_hrm_sex, '') AS empsex, COALESCE(e.dat_hrm_dob, '0000-00-00') AS empdob, COALESCE(e.var_hrm_marital_status, '') AS emp_maritalstatus, COALESCE(pos.var_name, '') AS empposition, COALESCE(e.var_img, '') AS empimg,
	COALESCE(e.var_hrm_permanent_home_no, '') AS emp_permanenthomeno, COALESCE(e.var_hrm_permanent_street, '') AS emp_permanentstreet, COALESCE(e.var_hrm_permanent_village, '') AS emp_permanentvillage, COALESCE(e.var_hrm_permanent_commune, '') AS emp_permanentcommune, COALESCE(e.var_hrm_permanent_district, '') AS emp_permanentdistrict, COALESCE(e.var_hrm_permanent_city, '') AS emp_permanentcity, COALESCE(e.var_hrm_permanent_country, '') AS emp_permanentcountry,
	COALESCE(e.var_addr1, '') AS emp_homeno, COALESCE(e.var_addr2, '') AS emp_street, COALESCE(e.var_addr3, '') AS emp_village, COALESCE(e.var_addr4, '') AS emp_commune, COALESCE(e.var_addr5, '') AS emp_district, COALESCE(e.var_addr6, '') AS emp_city, COALESCE(e.var_addr7, '') AS emp_country,
	COALESCE(e.var_hrm_home_tel, '') AS emp_hometel, COALESCE(e.var_tel1, '') AS emp_tel1, COALESCE(e.var_email, '') AS empemail, d.department_name, br.branch_name
	FROM ame_mt_emp e
	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)
	LEFT JOIN ame_mt_pos pos ON(e.var_posid = pos.var_id)
	WHERE e.var_id IN(", SEmp,")
	ORDER BY e.var_id;");
	PREPARE St FROM @SQL1;
	EXECUTE St;
	DEALLOCATE PREPARE St;

	SET @SQL1 = CONCAT("SELECT emp_id, edu_name, edu_startdate, edu_enddate, edu_degree, edu_school, edu_major, edu_description, edu_attachfile
	FROM hrm_employee_education ed  
	WHERE ed.emp_id IN(", SEmp,")
	ORDER BY ed.edu_autoid;");
	PREPARE St FROM @SQL1;
	EXECUTE St;
	DEALLOCATE PREPARE St;

	SET @SQL1 = CONCAT("SELECT train_institutename, train_certificate, train_course, train_startdate, train_enddate
	FROM hrm_employee_training tr 
	WHERE tr.emp_id IN(", SEmp,")
	ORDER BY tr.train_autoid;");
	PREPARE St FROM @SQL1;
	EXECUTE St;
	DEALLOCATE PREPARE St;

	SET @SQL1 = CONCAT("SELECT skill_name, skill_level, skill_description
	FROM hrm_employee_skill sk
	WHERE sk.emp_id IN(", SEmp,")
	ORDER BY sk.skill_autoid;");
	PREPARE St FROM @SQL1;
	EXECUTE St;
	DEALLOCATE PREPARE St;

	SET @SQL1 = CONCAT("SELECT ex_position, ex_company, ex_startdate, ex_enddate
	FROM hrm_employee_experience ex
	WHERE ex.emp_id IN(", SEmp,")
	ORDER BY ex.ex_autoid;");
	PREPARE St FROM @SQL1;
	EXECUTE St;
	DEALLOCATE PREPARE St;

	SET @SQL1 = CONCAT("SELECT l.`language`, l.language_readlevel, l.language_speaklevel, l.language_speaklevel, l.language_understandlevel, l.language_writelevel, l.language_type
	FROM hrm_employee_language l
	WHERE l.emp_id IN(", SEmp,")
	ORDER BY l.language_autoid;");
	PREPARE St FROM @SQL1;
	EXECUTE St;
	DEALLOCATE PREPARE St;

	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSaveFile`;
DELIMITER |
CREATE PROCEDURE `spHRMSaveFile`(IN fileData longblob, IN fileName varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Path text;
	DECLARE D LONGBLOB;
	DECLARE Ch INT DEFAULT(1);
	DECLARE L BIGINT DEFAULT(1);
	
	SELECT Setting_Value INTO Path FROM hrm_setting WHERE Setting_Type='Path' AND Setting_Name = 'File_Path';  
	SET Path = CONCAT(Path , "/", fileName);

	SELECT COALESCE(MAX(File_Line) + 1, 1) INTO L FROM hrm_save_file_temp;
	INSERT INTO hrm_save_file_temp(File_Name,File_Data,File_Line) VALUES(Path,fileData,L);
	INSERT INTO hrm_delete_file_temp(File_Name) VALUES(Path);
	
	WHILE ch > 0 DO
		SELECT COUNT(File_Name) INTO ch FROM hrm_delete_file_temp WHERE File_Name = Path;
		IF Ch <= 0 THEN
			SET @SQL1 = CONCAT("SELECT d.File_Data FROM hrm_save_file_temp d WHERE d.File_Line = ", L, " INTO DUMPFILE '", Path, "';");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
			DELETE FROM hrm_save_file_temp WHERE File_Name = Path AND File_Line = L;
		END IF;
	END WHILE;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchAllowance`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchAllowance`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.Allowance_ID,b.Allowance_Name,b.Allowance_PayType,b.Allowance_PayAmount FROM hrm_payroll_allowance b ORDER BY b.Allowance_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.Allowance_ID,b.Allowance_Name,b.Allowance_PayType,b.Allowance_PayAmount FROM hrm_payroll_allowance b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Allowance_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchAuthorisation`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchAuthorisation`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT a.Auth_ID,a.Auth_Name,a.Auth_Type,a.Auth_AndOr,a.Auth_Amount FROM hrm_authorisation a ORDER BY a.Auth_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT a.Auth_ID,a.Auth_Name,a.Auth_Type,a.Auth_AndOr,a.Auth_Amount FROM hrm_authorisation a WHERE LOWER(a.", c, ") LIKE '%", v,"%' ORDER BY a.Auth_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchAuthorisationGroup`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchAuthorisationGroup`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT a.AuthGroup_ID,a.AuthGroup_Name,a.AuthGroup_Description,(SELECT COUNT(d.AuthGroup_ID) FROM hrm_authorisation_group_detail d WHERE d.AuthGroup_ID = a.AuthGroup_ID) as 'Count' FROM hrm_authorisation_group a ORDER BY a.AuthGroup_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT a.AuthGroup_ID,a.AuthGroup_Name,a.AuthGroup_Description,(SELECT COUNT(d.AuthGroup_ID) FROM hrm_authorisation_group_detail d WHERE d.AuthGroup_ID = a.AuthGroup_ID) as 'Count' FROM hrm_authorisation_group a  WHERE LOWER(a.", c, ") LIKE '%", v,"%' ORDER BY a.AuthGroup_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchAutoFP`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchAutoFP`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT AutoFP_ID,AutoFP_ShiftID,Shift_ID,Shift_Name,Shift_Type,Shift_Description
			FROM hrm_timesheet_auto_fingerprint b
			LEFT JOIN hrm_timesheet_workshift w ON(b.AutoFP_ShiftID=w.Shift_ID)
			ORDER BY b.AutoFP_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT AutoFP_ID,AutoFP_ShiftID,Shift_ID,Shift_Name,Shift_Type,Shift_Description
			FROM hrm_timesheet_auto_fingerprint b
			LEFT JOIN hrm_timesheet_workshift w ON(b.AutoFP_ShiftID=w.Shift_ID)
			WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.AutoFP_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchBonus`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchBonus`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.Bonus_ID,b.Bonus_Date,b.Bonus_Reason,b.Bonus_Description
			FROM hrm_payroll_bonus b
			ORDER BY b.Bonus_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.Bonus_ID,b.Bonus_Date,b.Bonus_Reason,b.Bonus_Description
			FROM hrm_payroll_bonus b 
			WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Bonus_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchCurrency`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchCurrency`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.Currency_ID,b.Currency_Name,b.Currency_Placing,b.Currency_Rate,b.Currency_Description,b.Currency_Default FROM hrm_payroll_currency b ORDER BY b.Currency_ID;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.Currency_ID,b.Currency_Name,b.Currency_Placing,b.Currency_Rate,b.Currency_Description,b.Currency_Default FROM hrm_payroll_currency b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Currency_ID;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchDayoff`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchDayoff`(userid varchar(255),c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE CheckU VARCHAR(255) DEFAULT("");
	IF c != "" THEN
	SELECT var_hrm_utype INTO CheckU FROM ame_user WHERE var_id = userid; 

	IF CheckU = "ESS" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT df.Dayoff_ID,df.Dayoff_Date,df.Dayoff_EmpID,df.Dayoff_Description,df.Dayoff_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_id, '') AS 'PositionID',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_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_dayoff df INNER JOIN hrm_log l ON(df.Dayoff_ID = l.RecordID AND l.FrmSysName = 'Dayoff' AND l.ActionType = 'insert' AND l.UID = '", userid, "')
			INNER JOIN ame_mt_emp e ON df.Dayoff_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)
			ORDER BY df.Dayoff_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT df.Dayoff_ID,df.Dayoff_Date,df.Dayoff_EmpID,df.Dayoff_Description,df.Dayoff_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_id, '') AS 'PositionID',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_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_dayoff df INNER JOIN hrm_log l ON(df.Dayoff_ID = l.RecordID AND l.FrmSysName = 'Dayoff' AND l.ActionType = 'insert' AND l.UID = '", userid, "')
			INNER JOIN ame_mt_emp e ON df.Dayoff_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 LOWER(df.", c, ") LIKE '%", v,"%' ORDER BY df.Dayoff_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	ELSEIF CheckU = "Normal" OR CheckU = "Administrator" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT df.Dayoff_ID,df.Dayoff_Date,df.Dayoff_EmpID,df.Dayoff_Description,df.Dayoff_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_id, '') AS 'PositionID',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_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_dayoff df
			INNER JOIN ame_mt_emp e ON df.Dayoff_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)
			ORDER BY df.Dayoff_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT df.Dayoff_ID,df.Dayoff_Date,df.Dayoff_EmpID,df.Dayoff_Description,df.Dayoff_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_id, '') AS 'PositionID',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_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_dayoff df
			INNER JOIN ame_mt_emp e ON df.Dayoff_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 LOWER(df.", c, ") LIKE '%", v,"%' 
			ORDER BY df.Dayoff_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchDeduction`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchDeduction`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.Deduction_ID,b.Deduction_EmpID,b.Deduction_Date,b.Deduction_Reason,b.Deduction_Amount,b.Deduction_Description,b.Deduction_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_id, '') AS 'PositionID', 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_deduction b 
			INNER JOIN ame_mt_emp e ON b.Deduction_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)
			ORDER BY b.Deduction_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.Deduction_ID,b.Deduction_EmpID,b.Deduction_Date,b.Deduction_Reason,b.Deduction_Amount,b.Deduction_Description,b.Deduction_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_id, '') AS 'PositionID', 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_deduction b 
			INNER JOIN ame_mt_emp e ON b.Deduction_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 LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Deduction_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployee`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployee`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN	
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT 
												COALESCE(e.var_id, '') AS EmpID
												,COALESCE(e.var_name, '') AS EmpName
												,COALESCE(e.var_name_other, '') AS EmpNameKh
												,COALESCE(e.var_hrm_salutation, '') AS Emp_Salutation
												,COALESCE(e.var_hrm_sex, '') AS EmpSex
												,COALESCE(e.var_hrm_marital_status, '') AS Emp_MaritalStatus
												,COALESCE(e.dat_hrm_dob, '0000-00-00') AS EmpDOB
												,COALESCE(e.var_cardid, '') AS EmpICNo
												,COALESCE(e.var_hrm_nssfid, '') AS Emp_NSSFID
												,COALESCE(e.var_hrm_passportid, '') AS Emp_PassportID
												,COALESCE(e.dat_hrm_visaexpire, '0000-00-00') AS Emp_VisaExpire
												,COALESCE(e.var_tel1, '') AS Emp_Tel1
												,COALESCE(e.var_tel2, '') AS Emp_Tel2
												,COALESCE(e.var_hrm_home_tel, '') AS Emp_HomeTel
												,COALESCE(e.var_hrm_company_tel, '') AS Emp_CompanyTel
												,COALESCE(e.var_hrm_emergency_person_name, '') AS Emp_EmergencyPersonName
												,COALESCE(e.var_hrm_emergency_relationship, '') AS Emp_EmergencyRelationship
												,COALESCE(e.var_hrm_emergency_tel, '') AS Emp_EmergencyTel
												,COALESCE(e.var_email, '') AS EmpEmail
												,COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail
												,COALESCE(e.var_web, '') AS EmpWebsite
												,COALESCE(e.var_addr, '') AS EmpAddress
												,COALESCE(e.var_hrm_address_kh, '') AS EmpAddressKh
												,COALESCE(e.var_posid, '') AS EmpPositionID
												,COALESCE(e.var_img, '') AS EmpImg
												,COALESCE(e.var_hrm_status, '') AS EmpStatus
												,COALESCE(e.dat_hrm_date, '0000-00-00') AS EmpDate
												,COALESCE(e.var_hrm_supervisor, '') AS Supervisor
												,COALESCE(e.dat_hrm_contact_date, '0000-00-00') AS ContactDate
												,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_department_id, '') AS Emp_DepartmentID
												,COALESCE(e.var_hrm_branch_id, '') AS Emp_BranchID
												,COALESCE(e.var_hrm_nationality, '') AS Emp_Nationality
												,COALESCE(e.var_hrm_nationals, '') AS Emp_Nationals
												,COALESCE(e.var_hrm_bank_id, '') AS Emp_BankID
												,COALESCE(e.var_hrm_account_no, '') AS Emp_AccountNo
												,COALESCE(e.var_hrm_shift_type, '') AS Emp_ShiftType
												,COALESCE(e.var_hrm_shift_id, '') AS Emp_ShiftID
												,COALESCE(e.tin_hrm_allow_login, 0) AS Emp_AllowLogin
												,COALESCE(e.tin_hrm_notification_email, 0) AS Emp_NotificationEmail
												,COALESCE(e.dat_hrm_joindate, '0000-00-00') AS Emp_JoinDate
												,COALESCE(e.var_addr1, '') AS Emp_HomeNo
												,COALESCE(e.var_addr2, '') AS Emp_Street
												,COALESCE(e.var_addr3, '') AS Emp_Village
												,COALESCE(e.var_addr5, '') AS Emp_District
												,COALESCE(e.var_addr4, '') AS Emp_Commune
												,COALESCE(e.var_addr6, '') AS Emp_City
												,COALESCE(e.var_hrm_state, '') AS Emp_State
												,COALESCE(e.var_addr7, '') AS Emp_Country
												,COALESCE(e.var_hrm_permanent_address, '') AS Emp_PermanentAddress
												,COALESCE(e.var_hrm_permanent_home_no, '') AS Emp_PermanentHomeNo
												,COALESCE(e.var_hrm_permanent_street, '') AS Emp_PermanentStreet
												,COALESCE(e.var_hrm_permanent_village, '') AS Emp_PermanentVillage
												,COALESCE(e.var_hrm_permanent_district, '') AS Emp_PermanentDistrict
												,COALESCE(e.var_hrm_permanent_commune, '') AS Emp_PermanentCommune
												,COALESCE(e.var_hrm_permanent_city, '') AS Emp_PermanentCity
												,COALESCE(e.var_hrm_permanent_state, '') AS Emp_PermanentState
												,COALESCE(e.var_hrm_permanent_country, '') AS Emp_PermanentCountry
												,COALESCE(e.var_hrm_description, '') AS Emp_Description
												,COALESCE(e.var_hrm_fpid, '') AS Emp_FPID
												,COALESCE(e.tin_hrm_late_deduction, 0) AS Emp_LateDeduction
												,COALESCE(e.tin_hrm_probation, 0) AS Emp_Probation
												,COALESCE(e.dat_hrm_enddateprobation, '0000-00-00') AS Emp_EndDateProbation
												,COALESCE(e.dat_hrm_date_status) AS Emp_DateStatus 
												from ame_mt_emp e;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT
												COALESCE(e.var_id, '') AS EmpID
												,COALESCE(e.var_name, '') AS EmpName
												,COALESCE(e.var_name_other, '') AS EmpNameKh
												,COALESCE(e.var_hrm_salutation, '') AS Emp_Salutation
												,COALESCE(e.var_hrm_sex, '') AS EmpSex
												,COALESCE(e.var_hrm_marital_status, '') AS Emp_MaritalStatus
												,COALESCE(e.dat_hrm_dob, '0000-00-00') AS EmpDOB
												,COALESCE(e.var_cardid, '') AS EmpICNo
												,COALESCE(e.var_hrm_nssfid, '') AS Emp_NSSFID
												,COALESCE(e.var_hrm_passportid, '') AS Emp_PassportID
												,COALESCE(e.dat_hrm_visaexpire, '0000-00-00') AS Emp_VisaExpire
												,COALESCE(e.var_tel1, '') AS Emp_Tel1
												,COALESCE(e.var_tel2, '') AS Emp_Tel2
												,COALESCE(e.var_hrm_home_tel, '') AS Emp_HomeTel
												,COALESCE(e.var_hrm_company_tel, '') AS Emp_CompanyTel
												,COALESCE(e.var_hrm_emergency_person_name, '') AS Emp_EmergencyPersonName
												,COALESCE(e.var_hrm_emergency_relationship, '') AS Emp_EmergencyRelationship
												,COALESCE(e.var_hrm_emergency_tel, '') AS Emp_EmergencyTel
												,COALESCE(e.var_email, '') AS EmpEmail
												,COALESCE(e.var_hrm_company_email, '') AS Emp_CompanyEmail
												,COALESCE(e.var_web, '') AS EmpWebsite
												,COALESCE(e.var_addr, '') AS EmpAddress
												,COALESCE(e.var_hrm_address_kh, '') AS EmpAddressKh
												,COALESCE(e.var_posid, '') AS EmpPositionID
												,COALESCE(e.var_img, '') AS EmpImg
												,COALESCE(e.var_hrm_status, '') AS EmpStatus
												,COALESCE(e.dat_hrm_date, '0000-00-00') AS EmpDate
												,COALESCE(e.var_hrm_supervisor, '') AS Supervisor
												,COALESCE(e.dat_hrm_contact_date, '0000-00-00') AS ContactDate
												,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_department_id, '') AS Emp_DepartmentID
												,COALESCE(e.var_hrm_branch_id, '') AS Emp_BranchID
												,COALESCE(e.var_hrm_nationality, '') AS Emp_Nationality
												,COALESCE(e.var_hrm_nationals, '') AS Emp_Nationals
												,COALESCE(e.var_hrm_bank_id, '') AS Emp_BankID
												,COALESCE(e.var_hrm_account_no, '') AS Emp_AccountNo
												,COALESCE(e.var_hrm_shift_type, '') AS Emp_ShiftType
												,COALESCE(e.var_hrm_shift_id, '') AS Emp_ShiftID
												,COALESCE(e.tin_hrm_allow_login, 0) AS Emp_AllowLogin
												,COALESCE(e.tin_hrm_notification_email, 0) AS Emp_NotificationEmail
												,COALESCE(e.dat_hrm_joindate, '0000-00-00') AS Emp_JoinDate
												,COALESCE(e.var_addr1, '') AS Emp_HomeNo
												,COALESCE(e.var_addr2, '') AS Emp_Street
												,COALESCE(e.var_addr3, '') AS Emp_Village
												,COALESCE(e.var_addr5, '') AS Emp_District
												,COALESCE(e.var_addr4, '') AS Emp_Commune
												,COALESCE(e.var_addr6, '') AS Emp_City
												,COALESCE(e.var_hrm_state, '') AS Emp_State
												,COALESCE(e.var_addr7, '') AS Emp_Country
												,COALESCE(e.var_hrm_permanent_address, '') AS Emp_PermanentAddress
												,COALESCE(e.var_hrm_permanent_home_no, '') AS Emp_PermanentHomeNo
												,COALESCE(e.var_hrm_permanent_street, '') AS Emp_PermanentStreet
												,COALESCE(e.var_hrm_permanent_village, '') AS Emp_PermanentVillage
												,COALESCE(e.var_hrm_permanent_district, '') AS Emp_PermanentDistrict
												,COALESCE(e.var_hrm_permanent_commune, '') AS Emp_PermanentCommune
												,COALESCE(e.var_hrm_permanent_city, '') AS Emp_PermanentCity
												,COALESCE(e.var_hrm_permanent_state, '') AS Emp_PermanentState
												,COALESCE(e.var_hrm_permanent_country, '') AS Emp_PermanentCountry
												,COALESCE(e.var_hrm_description, '') AS Emp_Description
												,COALESCE(e.var_hrm_fpid, '') AS Emp_FPID
												,COALESCE(e.tin_hrm_late_deduction, 0) AS Emp_LateDeduction
												,COALESCE(e.tin_hrm_probation, 0) AS Emp_Probation
												,COALESCE(e.dat_hrm_enddateprobation, '0000-00-00') AS Emp_EndDateProbation
												,COALESCE(e.dat_hrm_date_status) AS Emp_DateStatus 
												from ame_mt_emp e WHERE LOWER(e.", c,") LIKE '%", v,"%' ORDER BY e.var_id;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeAllowance`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeAllowance`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.Allowance_EmpID,b.Allowance_ID FROM hrm_payroll_allowance_employee b ORDER BY b.Allowance_EmpID;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.Allowance_EmpID,b.Allowance_ID FROM hrm_payroll_allowance_employee b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Allowance_EmpID;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeAuthorisation`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeAuthorisation`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT a.Emp_ID, a.Auth_Process, a.Auth_ID FROM hrm_employee_authorisation a ORDER BY a.Emp_ID;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT a.Emp_ID, a.Auth_Process, a.Auth_ID FROM hrm_employee_authorisation a WHERE LOWER(a.", c, ") LIKE '%", v,"%' ORDER BY a.Emp_ID;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeBank`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeBank`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.Bank_ID,b.Bank_Name,b.Bank_Description FROM hrm_emp_bank b ORDER BY b.Bank_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.Bank_ID,b.Bank_Name,b.Bank_Description FROM hrm_emp_bank b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Bank_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeBranch`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeBranch`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("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 DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("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 WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Branch_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeCategory`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeCategory`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.Category_Name FROM hrm_emp_category b ORDER BY b.Category_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.Category_Name FROM hrm_emp_category b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Category_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeContractType`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeContractType`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.ContractType_Name FROM hrm_emp_contract_type b ORDER BY b.ContractType_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.ContractType_Name FROM hrm_emp_contract_type b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.ContractType_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeCountry`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeCountry`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.Country_Name FROM hrm_location_country b ORDER BY b.Country_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.Country_Name FROM hrm_location_country b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Country_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeDepartment`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeDepartment`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.Department_ID,b.Department_Name,b.Department_Description,b.Department_Parent FROM hrm_emp_department b ORDER BY b.Department_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.Department_ID,b.Department_Name,b.Department_Description,b.Department_Parent FROM hrm_emp_department b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Department_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeGrade`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeGrade`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.Grade_Name FROM hrm_emp_grade b ORDER BY b.Grade_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.Grade_Name FROM hrm_emp_grade b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Grade_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeInsurance`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeInsurance`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT Insurance_ID,Insurance_Name,Insurance_Company,Insurance_Type,Insurance_Description FROM hrm_emp_insurance b ORDER BY b.Insurance_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT Insurance_ID,Insurance_Name,Insurance_Company,Insurance_Type,Insurance_Description FROM hrm_emp_insurance b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Insurance_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeInsuranceType`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeInsuranceType`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.InsuranceType_Name FROM hrm_emp_insurance_type b ORDER BY b.InsuranceType_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.InsuranceType_Name FROM hrm_emp_insurance_type b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.InsuranceType_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeLanguage`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeLanguage`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT l.Language_Name FROM hrm_emp_language l ORDER BY l.Language_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT l.Language_Name FROM hrm_emp_language l WHERE LOWER(l.", c, ") LIKE '%", v,"%' ORDER BY l.Language_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeLeaveType`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeLeaveType`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.Leave_EmpID,b.Leave_TypeID FROM hrm_timesheet_leave_type_employee b ORDER BY b.Leave_EmpID;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.Leave_EmpID,b.Leave_TypeID FROM hrm_timesheet_leave_employee b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Leave_EmpID;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeLevel`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeLevel`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.Level_Name FROM hrm_emp_level b ORDER BY b.Level_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.Level_Name FROM hrm_emp_level b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Level_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeMembershipType`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeMembershipType`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.MembershipType_Name FROM hrm_emp_membership_type b ORDER BY b.MembershipType_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.MembershipType_Name FROM hrm_emp_membership_type b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.MembershipType_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeNationality`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeNationality`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.Nationnality_Name FROM hrm_emp_nationality b ORDER BY b.Nationnality_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.Nationnality_Name FROM hrm_emp_nationality b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Nationnality_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeNationals`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeNationals`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.Nationals_Name FROM hrm_emp_nationals b ORDER BY b.Nationals_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.Nationals_Name FROM hrm_emp_nationals b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Nationals_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeePosition`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeePosition`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT COALESCE(var_id, '') AS PositionID, COALESCE(var_name, '') AS Position, COALESCE(var_addr, '') AS PositionKhmer, COALESCE(int_level, 0) AS Position_Level, COALESCE(var_description, '') AS Position_Description FROM ame_mt_pos b ORDER BY b.var_id;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT COALESCE(var_id, '') AS PositionID, COALESCE(var_name, '') AS Position, COALESCE(var_addr, '') AS PositionKhmer, COALESCE(int_level, 0) AS Position_Level, COALESCE(var_description, '') AS Position_Description FROM ame_mt_pos b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.var_id;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeSchool`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeSchool`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.School_Name FROM hrm_emp_school b ORDER BY b.School_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.School_Name FROM hrm_emp_school b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.School_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeSocialCommunication`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeSocialCommunication`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.SocialCommunication_Name FROM hrm_emp_social_communication b ORDER BY b.SocialCommunication_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.SocialCommunication_Name FROM hrm_emp_social_communication b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.SocialCommunication_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeStatus`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeStatus`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.Status_Name FROM hrm_emp_status b ORDER BY b.Status_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.Status_Name FROM hrm_emp_status b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Status_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchEmployeeType`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchEmployeeType`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.Type_Name FROM hrm_emp_type b ORDER BY b.Type_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.Type_Name FROM hrm_emp_type b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Type_Name;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchHoliday`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchHoliday`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT Holiday_ID,Holiday_Name,Holiday_Type,Holiday_Duration,Holiday_StartDate,Holiday_EndDate,Holiday_Description
			FROM  hrm_timesheet_holiday h
			ORDER BY h.Holiday_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT Holiday_ID,Holiday_Name,Holiday_Type,Holiday_Duration,Holiday_StartDate,Holiday_EndDate,Holiday_Description
			FROM  hrm_timesheet_holiday h WHERE LOWER(h.", c, ") LIKE '%", v,"%' ORDER BY h.Holiday_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchHolidaySub`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchHolidaySub`()
    DETERMINISTIC
BEGIN
	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,
	(SELECT GROUP_CONCAT(DISTINCT d.Department_ID, '!@#$%', d.Department_Name, '!@#$%', d.Department_Description, '!@#$%', d.Department_Parent SEPARATOR ';') FROM ame_mt_emp e LEFT JOIN hrm_emp_department d ON(e.var_hrm_department_id = d.Department_ID) WHERE e.var_hrm_branch_id = b.Branch_ID) AS 'SubBranch'
	FROM hrm_emp_branch b ORDER BY b.Branch_ID;
	
	SELECT Department_ID, Department_Name, Department_Description, Department_Parent FROM hrm_emp_department ORDER BY Department_ID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchLateDuration`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchLateDuration`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT LD_From,LD_To,LD_Deduction FROM hrm_timesheet_late_duration b;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT LD_From,LD_To,LD_Deduction FROM hrm_timesheet_late_duration b WHERE LOWER(b.", c, ") LIKE '%", v,"%';");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchLeave`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchLeave`(userid varchar(255),c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE CheckU VARCHAR(255) DEFAULT("");
	IF c != "" THEN
	SELECT u.var_hrm_utype INTO CheckU FROM ame_user u WHERE u.var_id = userid;
	IF CheckU = "ESS" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT Leave_ID,Leave_EmpID,Leave_Tel,Leave_Email,Leave_Reason,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_id, '') AS 'PositionID',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_internal_id, '') AS Emp_InternalID
			FROM hrm_timesheet_leave le
			INNER JOIN ame_mt_emp e ON le.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)
			WHERE u.var_id = '", userid,"'
			ORDER BY le.Leave_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT Leave_ID,Leave_EmpID,Leave_Tel,Leave_Email,Leave_Reason,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_id, '') AS 'PositionID',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_internal_id, '') AS Emp_InternalID
			FROM hrm_timesheet_leave le
			INNER JOIN ame_mt_emp e ON le.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)
			WHERE u.var_id = '", userid,"' AND LOWER(le.", c, ") LIKE '%", v,"%' ORDER BY le.Leave_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	ELSEIF CheckU = "Normal" OR CheckU = "Administrator" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT Leave_ID,Leave_EmpID,Leave_Tel,Leave_Email,Leave_Reason,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_id, '') AS 'PositionID',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_internal_id, '') AS Emp_InternalID
			FROM hrm_timesheet_leave le
			INNER JOIN ame_mt_emp e ON le.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)
			ORDER BY le.Leave_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT Leave_ID,Leave_EmpID,Leave_Tel,Leave_Email,Leave_Reason,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_id, '') AS 'PositionID',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_internal_id, '') AS Emp_InternalID
			FROM hrm_timesheet_leave le
			INNER JOIN ame_mt_emp e ON le.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)
			WHERE LOWER(le.", c, ") LIKE '%", v,"%' 
			ORDER BY le.Leave_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchOverTime`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchOverTime`(userid varchar(255),c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE CheckU VARCHAR(255) DEFAULT("");
	IF c != "" THEN
	SELECT var_hrm_utype INTO CheckU FROM ame_user WHERE var_id = userid; 
	IF CheckU = "ESS" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT o.Overtime_ID, o.Overtime_Reason, o.Overtime_Type, o.Overtime_DateFrom, o.Overtime_DateTo, o.Overtime_Status, o.Overtime_RequestBy,
			COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID
			FROM hrm_payroll_overtime o 
			INNER JOIN hrm_log l ON(o.Overtime_ID = l.RecordID AND l.FrmSysName = 'Overtime' AND l.ActionType = 'insert' AND l.UID = '", userid, "')
			LEFT JOIN ame_mt_emp e ON(e.var_id = o.Overtime_RequestBy)
			ORDER BY o.Overtime_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT o.Overtime_ID, o.Overtime_Reason, o.Overtime_Type, o.Overtime_DateFrom, o.Overtime_DateTo, o.Overtime_Status, o.Overtime_RequestBy,
			COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID
			FROM hrm_payroll_overtime o INNER JOIN hrm_log l ON(b.Overtime_ID = l.RecordID AND l.FrmSysName = 'Overtime' AND l.ActionType = 'insert' AND l.UID = '", userid, "')
			LEFT JOIN ame_mt_emp e ON(e.var_id = o.Overtime_RequestBy)
			WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY o.Overtime_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	ELSEIF CheckU = "Normal" OR CheckU = "Administrator" OR CheckU = '' THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT o.Overtime_ID, o.Overtime_Reason, o.Overtime_Type, o.Overtime_DateFrom, o.Overtime_DateTo, o.Overtime_Status, o.Overtime_RequestBy,
			COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID
			FROM hrm_payroll_overtime o
			LEFT JOIN ame_mt_emp e ON(e.var_id = o.Overtime_RequestBy)
			ORDER BY o.Overtime_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT o.Overtime_ID, o.Overtime_Reason, o.Overtime_Type, o.Overtime_DateFrom, o.Overtime_DateTo, o.Overtime_Status, o.Overtime_RequestBy,
			COALESCE(e.var_id, '') AS EmpID, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID
			FROM hrm_payroll_overtime o
			LEFT JOIN ame_mt_emp e ON(e.var_id = o.Overtime_RequestBy)
			WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY o.Overtime_ID DESC;");
			
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchPayroll`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchPayroll`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.Payroll_ID,b.Payroll_Name,b.Payroll_Type,b.Payroll_StartDate,b.Payroll_LastSubmitDate,b.Payroll_SubmitDate,Payroll_SalaryStartDate,Payroll_LastSalaryDate,Payroll_SalaryDate,Payroll_AmtWorkingDay,Payroll_AmtWorkingHourPerDay FROM hrm_payroll b ORDER BY b.Payroll_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.Payroll_ID,b.Payroll_Name,b.Payroll_Type,b.Payroll_StartDate,b.Payroll_LastSubmitDate,b.Payroll_SubmitDate,Payroll_SalaryStartDate,Payroll_LastSalaryDate,Payroll_SalaryDate,Payroll_AmtWorkingDay,Payroll_AmtWorkingHourPerDay FROM hrm_payroll b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Payroll_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchRole`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchRole`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT RM_ID,RM_Name,RM_Des,RM_Status
			FROM hrm_role b WHERE RM_ID <> 'ADMIN'
			ORDER BY b.RM_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT RM_ID,RM_Name,RM_Des,RM_Status
			FROM hrm_role b 
			WHERE LOWER(b.", c, ") LIKE '%", v,"%' RM_ID <> 'ADMIN' ORDER BY b.RM_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchRoster`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchRoster`(UserID varchar(255),c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT r.Roster_Date,r.Roster_EmpID,r.Roster_ShiftID,
			b.EmpID,b.EmpName,b.EmpEmail,b.Emp_CompanyEmail,COALESCE(b.EmpPosition, '') AS 'Position', COALESCE(b.EmpPositionKh, '') AS 'PositionKhmer', COALESCE(b.Emp_PositionLevel, '') AS 'Position_Level',u.UName,
			ws.Shift_ID,ws.Shift_Name,ws.Shift_Type,ws.Shift_Description
			FROM hrm_timesheet_roster r
			INNER JOIN hrm_timesheet_workshift ws ON r.Roster_ShiftID = ws.Shift_ID
			INNER JOIN tblemployee b ON r.Roster_EmpID = b.EmpID 
			LEFT JOIN (SELECT UID,EmpID FROM tbluseremployee GROUP BY EmpID) ue ON(ue.EmpID = b.EmpID)
			LEFT JOIN tbluser u ON(u.UID = ue.UID);");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT r.Roster_Date,r.Roster_EmpID,r.Roster_ShiftID,
			b.EmpID,b.EmpName,b.EmpEmail,b.Emp_CompanyEmail,COALESCE(b.EmpPosition, '') AS 'Position', COALESCE(b.EmpPositionKh, '') AS 'PositionKhmer', COALESCE(b.Emp_PositionLevel, '') AS 'Position_Level',u.UName,
			ws.Shift_ID,ws.Shift_Name,ws.Shift_Type,ws.Shift_Description
			FROM hrm_timesheet_roster r
			INNER JOIN hrm_timesheet_workshift ws ON r.Roster_ShiftID = ws.Shift_ID
			INNER JOIN tblemployee b ON r.Roster_EmpID = b.EmpID
			LEFT JOIN (SELECT UID,EmpID FROM tbluseremployee GROUP BY EmpID) ue ON(ue.EmpID = b.EmpID)
			LEFT JOIN tbluser u ON(u.UID = ue.UID) 
			WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Shift_ID;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchSalary`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchSalary`(c varchar(255), v varchar(255), SK varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT s.Salary_EmpID,s.Salary_PayrollID,s.Salary_Type,", REPLACE(SK,'TempSA','s.Salary_Amount'), " AS 'Salary_Amount',s.Salary_Status FROM hrm_payroll_salary s ORDER BY s.Salary_EmpID;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT s.Salary_EmpID,s.Salary_PayrollID,s.Salary_Type,", REPLACE(SK,'TempSA','s.Salary_Amount'), ",s.Salary_Status FROM hrm_payroll_salary s FROM hrm_payroll_salary s WHERE LOWER(s.", c, ") LIKE '%", v,"%' ORDER BY s.Salary_EmpID;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchSalaryAdjustment`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchSalaryAdjustment`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT b.adj_submitpayrollID,b.adj_empid,b.adj_salary, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID
													FROM hrm_payroll_salary_adjustment b 
													LEFT JOIN ame_mt_emp e ON(b.adj_empid=e.var_id)
													ORDER BY b.adj_createdate DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT b.adj_submitpayrollID,b.adj_empid,b.adj_salary, COALESCE(e.var_name, '') AS EmpName, COALESCE(e.var_hrm_internal_id, '') AS Emp_InternalID
													FROM hrm_payroll_salary_adjustment b 
													LEFT JOIN ame_mt_emp e ON(b.adj_empid=e.var_id)
													WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.adj_createdate DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchSubmitPayroll`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchSubmitPayroll`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SELECT SubmitPayroll_ID,SubmitPayroll_PayrollID,SubmitPayroll_Date,SubmitPayroll_StartDate,SubmitPayroll_EndDate,SubmitPayroll_SalaryDate,SubmitPayroll_SalaryStartDate,SubmitPayroll_SalaryEndDate,
			p.Payroll_ID,p.Payroll_Name,p.Payroll_Type,p.Payroll_StartDate,p.Payroll_LastSubmitDate,p.Payroll_SubmitDate
			FROM hrm_payroll_submit_payroll b LEFT JOIN hrm_payroll p ON(b.SubmitPayroll_PayrollID=p.Payroll_ID)
			ORDER BY SubmitPayroll_ID;
		
		ELSE
			SET @SQL1 = CONCAT("SELECT SubmitPayroll_ID,SubmitPayroll_PayrollID,SubmitPayroll_Date,SubmitPayroll_StartDate,SubmitPayroll_EndDate,SubmitPayroll_SalaryDate,SubmitPayroll_SalaryStartDate,SubmitPayroll_SalaryEndDate,
			p.Payroll_ID,p.Payroll_Name,p.Payroll_Type,p.Payroll_StartDate,p.Payroll_LastSubmitDate,p.Payroll_SubmitDate
			FROM hrm_payroll_submit_payroll b LEFT JOIN hrm_payroll p ON(b.SubmitPayroll_PayrollID=p.Payroll_ID)
			WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.SubmitPayroll_ID;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchTimesheetLeaveType`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchTimesheetLeaveType`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT LeaveType_ID,LeaveType_Name,LeaveType_PayStatus,LeaveType_Year,LeaveType_AmountAllowed,LeaveType_GenderRestriction,LeaveType_PayType,LeaveType_PayAmount,LeaveType_BaseBalance FROM hrm_timesheet_leave_type b ORDER BY b.LeaveType_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT LeaveType_ID,LeaveType_Name,LeaveType_PayStatus,LeaveType_Year,LeaveType_AmountAllowed,LeaveType_GenderRestriction,LeaveType_PayType,LeaveType_PayAmount,LeaveType_BaseBalance FROM hrm_timesheet_leave_type b WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.LeaveType_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchUser`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchUser`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT COALESCE(u.var_id, '') AS UID, COALESCE(u.var_hrm_utype) AS UType, COALESCE(u.var_name) AS UName, COALESCE(var_pwd, '') AS UPassword, COALESCE(var_hrm_role, '') AS UHRMRoleID, COALESCE(var_empid, '') AS EmpID, COALESCE(tin_inactive, 0) AS UStatus
			FROM ame_user u WHERE u.var_id <> 'ADMIN';");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT COALESCE(u.var_id, '') AS UID, COALESCE(u.var_hrm_utype) AS UType, COALESCE(u.var_name) AS UName, COALESCE(var_pwd, '') AS UPassword, COALESCE(var_hrm_role, '') AS UHRMRoleID, COALESCE(var_empid, '') AS EmpID, COALESCE(tin_inactive, 0) AS UStatus
			FROM ame_user u
			WHERE LOWER(u.", c, ") LIKE '%", v,"%' AND u.UID <> 'ADMIN';");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSearchWorkShift`;
DELIMITER |
CREATE PROCEDURE `spHRMSearchWorkShift`(c varchar(255), v varchar(255))
    DETERMINISTIC
BEGIN
	IF c != "" THEN
		IF v = "all" OR v = "All" OR v = "ALL" THEN
			SET @SQL1 = CONCAT("SELECT Shift_ID,Shift_Name,Shift_Type,Shift_Description
			FROM hrm_timesheet_workshift b
			ORDER BY b.Shift_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		ELSE
			SET @SQL1 = CONCAT("SELECT Shift_ID,Shift_Name,Shift_Type,Shift_Description
			FROM hrm_timesheet_workshift b 
			WHERE LOWER(b.", c, ") LIKE '%", v,"%' ORDER BY b.Shift_ID DESC;");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;
		END IF;
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSelectFormPer`;
DELIMITER |
CREATE PROCEDURE `spHRMSelectFormPer`(UID Varchar(255),PRE tinyint(1))
    DETERMINISTIC
BEGIN
		SELECT U.UID 'UID',U.frmsysname 'Form ID',F.SortKey 'Sort Key',Mnuname 'Menu',FrmName 'Form Name',pread 'View',padd 'Add',pedit 'Edit',pdelete 'Delete',ppost 'Post',pVoid 'Void'
		FROM hrm_userpermission U Left JOIN hrm_form F on U.FrmSysName = F.FrmSysName
		WHERE U.UID = UID AND (Standard = 1 OR F.Premium = PRE) ORDER BY F.SortKey;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSelectReportPer`;
DELIMITER |
CREATE PROCEDURE `spHRMSelectReportPer`(UID Varchar(255))
    DETERMINISTIC
BEGIN
SELECT UID,rptName 'Report ID',rptdtName 'Report Name',PRead 'View Report'
FROM hrm_reportpermission U INNER JOIN hrm_reportdetail on rptName = concat(rptID,rptdtID)
WHERE U.UID = UID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMShiftDetail`;
DELIMITER |
CREATE PROCEDURE `spHRMShiftDetail`(IN ShiftID Varchar(255))
    DETERMINISTIC
BEGIN
		SELECT s.ShiftDay, DATE_FORMAT(s.TimeIn1,"%H:%i"), s.TimeIn1To, s.TimeOut1, s.TimeOut1To, s.TimeIn2, s.TimeIn2To, s.TimeOut2, s.TimeOut2To, s.TimeIn3, s.TimeIn3To, s.TimeOut3, s.TimeOut3To, s.TimeIn4, s.TimeIn4To, s.TimeOut4, s.TimeOut4To
		FROM hrm_shift_detail s
		WHERE s.ShiftID LIKE ShiftID 
		ORDER BY s.Main;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSyncField`;
DELIMITER |
CREATE PROCEDURE `spHRMSyncField`(Statuss varchar(255))
    DETERMINISTIC
BEGIN
	SELECT * from hrm_syncfield a WHERE a.Statuss = Statuss OR a.Statuss = 'All';
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMSyncSetting`;
DELIMITER |
CREATE PROCEDURE `spHRMSyncSetting`(Fieldss Text)
    DETERMINISTIC
BEGIN
	DELETE FROM autosyncsetting;
	SET @SQLPOS = CONCAT("INSERT INTO hrm_syncsetting VALUES(", fieldss, ")");
	PREPARE St FROM @SQLPOS;
	EXECUTE St;
	DEALLOCATE PREPARE St;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateAllowance`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateAllowance`(userid varchar(255),ID varchar(255),SName varchar(255),SValue text,SValue2 text)
    DETERMINISTIC
BEGIN
	DECLARE CheckExist VARCHAR(255) DEFAULT("");
	DECLARE Exist VARCHAR(7) DEFAULT("");
	DECLARE tz VARCHAR(20) DEFAULT('');
	
	IF SValue != "" THEN
		SELECT DISTINCT(Allowance_ID) INTO CheckExist FROM hrm_payroll_allowance WHERE LOWER(Allowance_Name) = SName;
		IF CheckExist = "" OR CheckExist = ID THEN
			SET @SQL1 = CONCAT("UPDATE hrm_payroll_allowance SET ", SValue, " WHERE Allowance_ID='" , ID, "';");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

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

				SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_allowance_history(Allowance_ID,Allowance_Date,Allowance_PayType,Allowance_PayAmount) VALUES ", SValue2, ";");
				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;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Allowance', ID);
			
			SET Exist = "success";
			SELECT Exist;
			CALL hrm_message('1100102', 'Allowance', 'update', ID);

		ELSE
			SET Exist = "exist";
			SELECT Exist;
			CALL hrm_message('1100104', 'Allowance', 'exist', SName);
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateAttendanceStatus`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateAttendanceStatus`(userid varchar(255), SEmpID varchar(255), SDate Date, SStatus varchar(255), SDes text)
    DETERMINISTIC
BEGIN
	DECLARE message varchar(255) DEFAULT('');

	UPDATE hrm_timesheet_attendance SET Att_RStatus = SStatus, Att_Des = SDes WHERE Att_EmpID = SEmpID AND Att_Date = SDate;

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

	SET message = "success";
	SELECT message;
	CALL hrm_message_param3('1102101', 'Attendance', 'update', SEmpID, SDate, '');
	

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateAuthorisation`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateAuthorisation`(userid varchar(255),AuthID varchar(255),AuthName varchar(255),Auth text, AuthDetail text, AuthType varchar(255),AuthAmount int, AuthRAmount int, AuthGroupID varchar(255), AuthGroupAmount varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE CheckExist VARCHAR(255) DEFAULT("");
	DECLARE Exist VARCHAR(255) DEFAULT("");
	DECLARE CheckUsed INT DEFAULT(0);
	DECLARE CheckGroupAmount TINYINT DEFAULT(0);
	DECLARE TempGroupAmount INT DEFAULT(0);
	DECLARE TempGroupID VARCHAR(255) DEFAULT('');

	-- Check Group Amount And Auth Amount
	IF LOWER(AuthType) = 'group' THEN
		myloop1: WHILE (LOCATE(',', AuthGroupID) > 0)
		DO
			SET @value = LEFT(AuthGroupID, LOCATE(',',AuthGroupID) - 1);    
			SET AuthGroupID = SUBSTRING(AuthGroupID, LOCATE(',',AuthGroupID) + 1);
			IF @value != "" THEN
				myloop2: WHILE (LOCATE(',', AuthGroupAmount) > 0)
				DO
					SET @value1 = LEFT(AuthGroupAmount, LOCATE(',',AuthGroupAmount) - 1);    
					SET AuthGroupAmount = SUBSTRING(AuthGroupAmount, LOCATE(',',AuthGroupAmount) + 1);
					IF @value1 != "" THEN
						SET TempGroupID = @value;
						SET TempGroupAmount = @value1;
						SELECT IF(COUNT(*) < TempGroupAmount, 1, 0) INTO CheckGroupAmount FROM hrm_authorisation_group_detail WHERE AuthGroup_ID = @value;
						LEAVE myloop2;
					END IF;
				END WHILE;
				IF CheckGroupAmount >0 THEN
					LEAVE myloop1;
				END IF;
			END IF;
		END WHILE;
	END IF;

	IF Auth != "" AND ((LOWER(AuthType) = 'individual' AND AuthAmount <= AuthRAmount) OR (LOWER(AuthType) = 'group' AND CheckGroupAmount <= 0)) THEN
		/*SELECT COALESCE(SUM(ap.CheckUsed), 0) INTO CheckUsed
		FROM (
			SELECT IF(ap.Auth_ProcessName = 'Overtime', (SELECT COUNT(*) FROM hrm_payroll_overtime WHERE  Overtime_ID = ap.Auth_ProcessID AND Overtime_Status = 'requested'),
			       IF(ap.Auth_ProcessName = 'Deduction', (SELECT COUNT(*) FROM hrm_payroll_deduction WHERE  Deduction_ID = ap.Auth_ProcessID AND Deduction_Status = 'requested'),
			       IF(ap.Auth_ProcessName = 'Leave', (SELECT COUNT(*) FROM hrm_timesheet_leave WHERE  Leave_ID = ap.Auth_ProcessID AND Leave_Status = 'requested'),
						 IF(ap.Auth_ProcessName = 'Dayoff', (SELECT COUNT(*) FROM hrm_timesheet_dayoff WHERE Dayoff_ID = ap.Auth_ProcessID AND Dayoff_Status='requested'), 0)))) AS 'CheckUsed' 
      FROM hrm_authorisation_approved ap WHERE ap.Auth_ID = AuthID GROUP BY ap.Auth_ProcessID 
		) ap;*/

		-- SELECT COUNT(*) INTO CheckUsed FROM hrm_authorisation_approved ap WHERE ap.Auth_ID = AuthID;
		
		IF CheckUsed <= 0 THEN
			SELECT DISTINCT(Auth_ID) INTO CheckExist FROM hrm_authorisation WHERE LOWER(Auth_Name) = AuthName;
			/*SELECT AuthName;
			SELECT AuthID;
			SELECT CheckExist;*/
			IF CheckExist = "" OR CheckExist = AuthID THEN
				SET @SQL1 = CONCAT("UPDATE hrm_authorisation SET ", Auth, " WHERE Auth_ID='" , AuthID, "';");
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

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

				DELETE FROM hrm_authorisation_detail WHERE Auth_ID = AuthID;
				IF AuthDetail != "" THEN
					SET @SQL1 = CONCAT("INSERT INTO hrm_authorisation_detail(Auth_ID,Auth_EmpID,Auth_GroupID,Auth_GroupAndOr,Auth_GroupAmount) VALUES ", AuthDetail, ";");
					SET @SQL1 = REPLACE(@SQL1,'TempAuth_ID',AuthID);
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;
				END IF;
				CALL spHRMCheckAuthorisationTemp(userid, AuthID);
				SET Exist = "success";
				SELECT Exist;
				CALL hrm_message('1101402', 'Auth', 'update', AuthID);
			ELSE
				SET Exist = "exist";
				SELECT Exist;
				CALL hrm_message('1101404', 'Auth', 'exist', AuthName);
			END IF;
		-- ELSE
			-- SET Exist = 'used';
			-- SELECT Exist;
			-- CALL hrm_message('1101405', 'Auth', 'used', AuthID);
		END IF;
	ELSE
		SET Exist = "not allowed";
		SELECT Exist;
		IF LOWER(AuthType) = 'individual' THEN
			CALL hrm_message('1101406', 'Auth', 'notallowed', AuthAmount);
		ELSE
			CALL hrm_message_param3('1101407', 'Auth', 'notallowed', TempGroupID, TempGroupAmount, '');
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateAuthorisationApprove`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateAuthorisationApprove`(IN UserID varchar(255),IN SProID varchar(255),IN  SProName varchar(255),IN SAuthID varchar(255),IN SAuthGID varchar(255),IN SEmpID varchar(255),IN SAuthStatus varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE EmpID VARCHAR(255) DEFAULT('');
	DECLARE Message VARCHAR(20) DEFAULT('not exist');
	DECLARE L BIGINT DEFAULT(0);
	DECLARE CheckStatus INT DEFAULT(0);
	DECLARE PStatus VARCHAR(255);
	
	-- Check Can Update and Find Line
	SELECT ap.Auth_Line,
	(IF(ap.Auth_ProcessName='Deduction' AND d.Deduction_Status='requested',1,
	IF(ap.Auth_ProcessName='Leave' AND l.Leave_Status='requested',1,
  IF(ap.Auth_ProcessName='Overtime' AND o.Overtime_Status='requested',1,
	IF(ap.Auth_ProcessName='Dayoff' AND df.Dayoff_Status='requested', 1, 0)))))

	INTO L, CheckStatus 
	FROM hrm_authorisation_approved ap 
	LEFT JOIN hrm_payroll_deduction d ON ap.Auth_ProcessID = d.Deduction_ID
	LEFT JOIN hrm_timesheet_leave l ON ap.Auth_ProcessID = l.Leave_ID
	LEFT JOIN hrm_payroll_overtime o ON ap.Auth_ProcessID = o.Overtime_ID
	LEFT JOIN hrm_timesheet_dayoff df ON ap.Auth_ProcessID = df.Dayoff_ID
	WHERE ap.Auth_ProcessID = SProID AND ap.Auth_ProcessName = SProName AND ap.Auth_ID = SAuthID AND ap.Auth_GroupID = SAuthGID AND ap.Auth_EmpID = SEmpID;
	
	-- Find EmpID
	SELECT u.var_empid INTO EmpID FROM ame_user u WHERE u.var_id = UserID;

	IF SEmpID = EmpID AND L <> 0 AND CheckStatus = 1 THEN
		UPDATE hrm_authorisation_approved SET Auth_Status = SAuthStatus WHERE Auth_Line = L;
		CALL spHRMAddLog(UserID, 'insert', 'Authorsation Approve', SProID);

		-- Check Auth When Amount is full	
		CALL spHRMGetCheckAuthorisationTranApproved(UserID, SProID, SProName, SAuthID, SAuthGID);
		
		SET Message = 'success';
		CALL hrm_message_param3('1101301', 'AuthApprove', 'update', SAuthStatus, SProName, SProID);

	ELSE

		SET Message = 'not allow';

		CALL hrm_message_param3('1101302', 'AuthApprove', 'notallowed', SAuthStatus, SProName, SProID);

	END IF;
	SELECT Message;
	
	
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateAuthorisationGroup`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateAuthorisationGroup`(userid varchar(255),AuthGroupID varchar(255),AuthGroupName varchar(255),AuthGroup text, AuthGroupDetail text)
    DETERMINISTIC
BEGIN
	DECLARE CheckExist VARCHAR(255) DEFAULT("");
	DECLARE Exist VARCHAR(7) DEFAULT("");
	DECLARE CheckUsed INT DEFAULT(0);
	IF AuthGroup != "" THEN
		-- 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
			SELECT DISTINCT(AuthGroup_ID) INTO CheckExist FROM hrm_authorisation_group WHERE LOWER(AuthGroup_Name) = AuthGroupName;

			IF CheckExist = "" OR CheckExist = AuthGroupID THEN
				SET @SQL1 = CONCAT("UPDATE hrm_authorisation_group SET ", AuthGroup, " WHERE AuthGroup_ID='" , AuthGroupID, "';");
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

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

				DELETE FROM hrm_authorisation_group_detail WHERE AuthGroup_ID = AuthGroupID;
				IF AuthGroupDetail != "" THEN
					SET @SQL1 = CONCAT("INSERT INTO hrm_authorisation_group_detail(AuthGroup_ID,AuthGroup_EmpID) VALUES ", AuthGroupDetail, ";");
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;
				END IF;
				CALL spHRMCheckAuthorisationGroupTemp(userid, AuthGroupID);
				SET Exist = "success";
				SELECT Exist;
				CALL hrm_message('1101502', 'AuthGroup', 'update', AuthGroupID);
			ELSE
				SET Exist = "exist";
				SELECT Exist;
				CALL hrm_message('1101504', 'AuthGroup', 'exist', AuthGroupName);
			END IF;
		-- ELSE
			-- SET Exist = "used";
			-- SELECT Exist;
			-- CALL hrm_message('1101505', 'AuthGroup', 'used', AuthGroupID);
		-- END IF;
		
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateAutoFP`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateAutoFP`(userid varchar(255),SID varchar(255), SName varchar(255),SValue text, SValueDetail text)
    DETERMINISTIC
BEGIN
	DECLARE CheckExist VARCHAR(255) DEFAULT("");
	DECLARE Exist VARCHAR(7) DEFAULT("");
	DECLARE CheckUsed INT DEFAULT(0);

	SELECT DISTINCT(AutoFP_ID) INTO CheckExist FROM hrm_timesheet_auto_fingerprint WHERE LOWER(AutoFP_ShiftID) = SName;

	IF SValue != "" AND (CheckExist = "" OR CheckExist = SID) THEN
		-- Not Check Used
		IF CheckUsed <= 0 THEN
					SET @SQL1 = CONCAT("UPDATE hrm_timesheet_auto_fingerprint SET ", SValue, " WHERE AutoFP_ID='" , SID, "';");
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;

					DELETE FROM hrm_timesheet_auto_finger_detail WHERE AutoFP_ID = SID;
		
					SET @SQL1 = CONCAT("INSERT INTO hrm_timesheet_auto_finger_detail(AutoFP_ID,AutoFP_Day,AutoFP_In1,AutoFP_Out1,AutoFP_In2,AutoFP_Out2,AutoFP_In3,AutoFP_Out3,AutoFP_In4,AutoFP_Out4,AutoFP_In5,AutoFP_Out5) VALUES ", SValueDetail, ";");
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;

					INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'AutoFP', SID);
			
					SET Exist = "success";
					SELECT Exist;
					CALL hrm_message('1102202', 'AutoFP', 'update', SID);
		ELSE
				SET Exist = "used";
				SELECT Exist;
				CALL hrm_message('1102205', 'AutoFP', 'used', SID);
		END IF;
	ELSE
			SET Exist = "exist";
			SELECT Exist;
			CALL hrm_message('112204', 'AutoFP', 'exist', SName);
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateBonus`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateBonus`(userid varchar(255),SID varchar(255),SValue text, SValueDetail text)
    DETERMINISTIC
BEGIN
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE Exist VARCHAR(7) DEFAULT("");
	DECLARE CheckUsed INT DEFAULT(0);
	IF SValue != "" THEN
		SELECT COUNT(*) INTO CheckUsed FROM hrm_payroll_bonus_detail WHERE Bonus_ID = SID AND Bonus_PayStatus <> 'Open';
		IF CheckUsed <= 0 THEN
					SET @SQL1 = CONCAT("UPDATE hrm_payroll_bonus SET ", SValue, " WHERE Bonus_ID='" , SID, "';");
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;

					DELETE FROM hrm_payroll_bonus_detail WHERE Bonus_ID = SID;
		
					SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_bonus_detail(Bonus_ID,Bonus_EmpID,Bonus_PayType,Bonus_PayAmount) VALUES ", SValueDetail, ";");
					SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', SID);
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;

					INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Bonus', SID);
			
					SET Exist = "success";
					SELECT Exist;
					CALL hrm_message('1100202', 'Bonus', 'update', SID);
		ELSE
				SET Exist = "used";
				SELECT Exist;
				CALL hrm_message('1100205', 'Bonus', 'used', SID);
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateCurrency`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateCurrency`(userid varchar(255),CID varchar(255),CName varchar(255),CValue text, CValue2 text, CreateDate varchar(255),SDefault int)
    DETERMINISTIC
BEGIN
	DECLARE CheckExist VARCHAR(255) DEFAULT("");
	DECLARE Exist VARCHAR(7) DEFAULT("");
	
	IF CValue != "" THEN
		-- SELECT Currency_Default INTO CheckExist FROM hrm_payroll_currency WHERE Currency_ID = CID;

		-- IF CheckExist = 0 THEN
			SELECT DISTINCT(Currency_ID) INTO CheckExist FROM hrm_payroll_currency WHERE LOWER(Currency_Name) = CName;
			IF CheckExist = "" OR CheckExist = CID THEN
		
				IF SDefault = 1 THEN
					UPDATE hrm_payroll_currency SET Currency_Default = 0;
				END IF;
	
				SET @SQL1 = CONCAT("UPDATE hrm_payroll_currency SET ", CValue, " WHERE Currency_ID='" , CID, "';");
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;
				IF CValue2 != "" THEN
					SET @SQL1 = CONCAT("UPDATE hrm_payroll_currency_history SET ", CValue2, " WHERE Currency_ID='" , CID, "' AND Currency_Date='" , CreateDate, "';");
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;
				END IF;

				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Currency', CID);
			
				SET Exist = "success";
				SELECT Exist;
				CALL hrm_message('1100002', 'Currency', 'update', CID);

			ELSE
				SET Exist = "exist";
				SELECT Exist;
				CALL hrm_message('1100004', 'Currency', 'exist', CName);
			END IF;
		-- ELSE
				-- SET Exist = "used";
				-- SELECT Exist;
		-- END IF;
		
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateDayoff`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateDayoff`(userid varchar(255),ID varchar(255),SEmpID varchar(255), SDate Date, SValue text)
    DETERMINISTIC
BEGIN
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE Exist VARCHAR(255) DEFAULT("");
	DECLARE CheckAuth VARCHAR(1) DEFAULT("1");
	DECLARE AuthType VARCHAR(255) DEFAULT("");
	DECLARE AuthID VARCHAR(255) DEFAULT("");
	DECLARE OldDate Date;
	DECLARE CheckAllowLimited TINYINT DEFAULT(0);
	DECLARE CheckAmount TINYINT DEFAULT(0);
	DECLARE ADMIN TINYINT DEFAULT(0);

	SELECT Setting_Value INTO CheckAllowLimited FROM hrm_setting WHERE Setting_Type = "Dayoff" AND Setting_Name = "Dayoff_Monthly_Amount";

	SELECT (COUNT(*)-1) INTO CheckAmount FROM hrm_timesheet_dayoff WHERE Dayoff_EmpID = SEmpID AND MONTH(Dayoff_Date) = MONTH(SDate) AND YEAR(Dayoff_Date) = YEAR(SDate) AND Dayoff_Status <> 'rejected';
	
	IF SValue != "" AND CheckAmount <= CheckAllowLimited THEN
		
		-- Check Auth Allow or not
		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;

			SELECT IF(LOWER(UType) = 'administrator', 1, 0) INTO ADMIN FROM tbluser WHERE UID = userid;

			IF CheckExist <= 0 OR ADMIN > 0 THEN

				SELECT Auth_ID INTO AuthID FROM hrm_authorisation_employee WHERE Emp_ID = SEmpID AND Auth_Process = 'Dayoff';

				IF AuthID = "" THEN
					SELECT Setting_Value INTO AuthID FROM hrm_setting WHERE Setting_Name = 'Dayoff' AND Setting_Type = 'Authorisation';
				END IF;

				IF AuthID != "" THEN

							SET @SQL1 = CONCAT("UPDATE hrm_timesheet_dayoff SET ", SValue, " WHERE Dayoff_ID='" , ID, "';");
							IF CheckExist <= 0 THEN
								SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'requested');
							ELSE
								SET @SQL1 = REPLACE(@SQL1, "Dayoff_Status='Temp_Status',", '');
							END IF;
							
							SET @SQL1 = REPLACE(@SQL1, 'Temp_AuthID', AuthID);
							PREPARE St FROM @SQL1;
							EXECUTE St;
							DEALLOCATE PREPARE St;

							IF CheckExist <= 0 THEN
								DELETE FROM hrm_authorisation_approved WHERE  Auth_ProcessID = ID AND Auth_ProcessName = "Dayoff";

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

								CALL spHRMAddAuthorisationTemp(AuthID,ID); 
							END IF;

							
							INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Dayoff', ID);
							SET Exist = "success";
							SELECT Exist;
							CALL hrm_message('1101702', 'Dayoff', 'update', ID);
				ELSE
					SET Exist = "no authorisation";
					SELECT Exist;
					CALL hrm_message('1101706', 'Dayoff', 'auth', SEmpID);
				END IF;

			ELSE
				SET Exist = "used";
				SELECT Exist;
				CALL hrm_message('1101705', 'Dayoff', 'used', ID);
			END IF;
		ELSE
					-- Check Attendance
					SELECT Dayoff_Date INTO OldDate FROM hrm_timesheet_dayoff WHERE Dayoff_ID = ID;

					SET @SQL1 = CONCAT("UPDATE hrm_timesheet_dayoff SET ", SValue, " WHERE Dayoff_ID='" , ID, "';");
					SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'approved');
					SET @SQL1 = REPLACE(@SQL1, 'Temp_AuthID', '');
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;

					-- Check Attendance
					CALL spHRMAttendanceLeaveDeleteFullDay(SEmpID, OldDate, OldDate);
					CALL spHRMAttendanceLeaveFullDay(SEmpID, SDate, SDate);
		
					DELETE FROM hrm_authorisation_approved WHERE  Auth_ProcessID = ID AND Auth_ProcessName = "Dayoff";

					INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Dayoff', ID);
					SET Exist = "success";
					SELECT Exist;
					CALL hrm_message('1101702', 'Dayoff', 'update', ID);
		END IF;

	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateDeduction`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateDeduction`(userid varchar(255),SID varchar(255),SEmpID varchar(255),SValue text,SValue2 text)
    DETERMINISTIC
BEGIN
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE Exist VARCHAR(255) DEFAULT("");
	DECLARE CheckAuth VARCHAR(1) DEFAULT("1");
	DECLARE AuthType VARCHAR(255) DEFAULT("");
	DECLARE AuthID VARCHAR(255) DEFAULT("");
	DECLARE ADMIN TINYINT DEFAULT(0);
	
	IF SValue != "" THEN
		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 = SID AND Auth_ProcessName = "Deduction" AND (Auth_Status = "approved" OR Auth_Status = "rejected");
			IF CheckExist <= 0 THEN
				SELECT COUNT(*) INTO CheckExist FROM hrm_payroll_deduction WHERE Deduction_ID = SID AND (Deduction_Status = "approved" OR Deduction_Status = "rejected" OR Deduction_Status = "approved & deducted");
			END IF;

			SELECT IF(LOWER(var_hrm_utype) = 'administrator', 1, 0) INTO ADMIN FROM ame_user WHERE var_id = userid;

			IF CheckExist <= 0 OR ADMIN > 0 THEN
				SELECT Auth_ID INTO AuthID FROM hrm_authorisation_employee WHERE Emp_ID = SEmpID AND Auth_Process = 'Deduction';

				IF AuthID = "" THEN
					SELECT Setting_Value INTO AuthID FROM hrm_setting WHERE Setting_Name = 'Deduction' AND Setting_Type = 'Authorisation';
				END IF;

				IF AuthID != "" THEN
					SET @SQL1 = CONCAT("UPDATE hrm_payroll_deduction SET ", SValue, " WHERE Deduction_ID='" , SID, "';");
					IF CheckExist <= 0 THEN
						SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'requested');
					ELSE
						SET @SQL1 = REPLACE(@SQL1, "Deduction_Status='Temp_Status',", '');
					END IF;
					
					SET @SQL1 = REPLACE(@SQL1, 'Temp_AuthID', AuthID);
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;

					DELETE FROM hrm_payroll_deduction_detail WHERE dd_id = SID AND LOWER(dd_status) = 'open'; 
					IF SValue2 != '' THEN
						SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_deduction_detail(dd_id,dd_empid,dd_date,dd_amount,dd_status,dd_line) VALUES ", SValue2, ";");
						SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', SID);
						SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'Open');
						PREPARE St FROM @SQL1;
						EXECUTE St;
						DEALLOCATE PREPARE St;
					END IF;

					IF CheckExist <= 0 THEN
							DELETE FROM hrm_authorisation_approved WHERE  Auth_ProcessID = SID AND Auth_ProcessName = "Deduction";

							SELECT Auth_Type INTO AuthType FROM hrm_authorisation WHERE Auth_ID = AuthID;
						
							IF AuthType = "Individual" THEN
								CALL spHRMAddIAuthorisationApproved(AuthID, SID, 'Deduction');
							ELSE
								CALL spHRMAddGAuthorisationApproved(AuthID, SID, 'Deduction');
							END IF;

							CALL spHRMAddAuthorisationTemp(AuthID,SID); 
					END IF;

					INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Deduction', SID);
			
					SET Exist = "success";
					SELECT Exist;
					CALL hrm_message('1100302', 'Deduction', 'update', SID);
				ELSE
					SET Exist = "no authorisation";
					SELECT Exist;
					CALL hrm_message('1100306', 'Deduction', 'auth', SEmpID);
				END IF;
			ELSE
				SET Exist = "used";
				SELECT Exist;
				CALL hrm_message('1100305', 'Deduction', 'used', SID);
			END IF;
		ELSE
			SET @SQL1 = CONCAT("UPDATE hrm_payroll_deduction SET ", SValue, " WHERE Deduction_ID='" , SID, "';");
			SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'approved');
			SET @SQL1 = REPLACE(@SQL1, 'Temp_AuthID', '');
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			DELETE FROM hrm_payroll_deduction_detail WHERE dd_id = SID AND LOWER(dd_status) = 'open'; 
			IF SValue2 != '' THEN
				SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_deduction_detail(dd_id,dd_empid,dd_date,dd_amount,dd_status,dd_line) VALUES ", SValue2, ";");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', SID);
				SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'Open');
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;
			END IF;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Deduction', SID);
			
			DELETE FROM hrm_authorisation_approved WHERE  Auth_ProcessID = SID AND Auth_ProcessName = "Deduction";

			SET Exist = "success";
			SELECT Exist;
			CALL hrm_message('1100302', 'Deduction', 'update', SID);
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateEmployee`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateEmployee`(userid varchar(255),SEmpID varchar(255),employee text,socialcommunicationID varchar(255),socialcommunication text,skillID varchar(255),skill text,languageID varchar(255),language text,educationID varchar(255),education text,experienceID varchar(255),experience text,familyID varchar(255),family text,contractID varchar(255), contract text,trainID varchar(255),training text,attachmentID varchar(255),attachment text,membershipID varchar(255),membership text,insuranceID varchar(255),insurance text,user1 text, user2 text, SUID varchar(255), SuserAssign varchar(255), CategoryName varchar(255), ContractTypeName text, LanguageName text, MembershipTypeName text, NationalityName varchar(255), NationalsName varchar(255), SchoolName text, SocialCommunicationName text, EmpStatus varchar(255), EmpType varchar(255), EmpCountry varchar(255), EmpPermanentCountry varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE UserName VARCHAR(255) DEFAULT('');
	DECLARE RoleESS VARCHAR(255) DEFAULT('');
	DECLARE TempEmpID VARCHAR(255) DEFAULT('');

	SET TempEmpID = SEmpID;
	IF employee != "" THEN
		SELECT COALESCE(var_img, '') AS EmpImg FROM ame_mt_emp e WHERE e.var_id = TempEmpID;

		SET @SQL1 = CONCAT("UPDATE ame_mt_emp SET ", employee, " WHERE var_id='" , TempEmpID, "';");
		PREPARE St FROM @SQL1;
		EXECUTE St;
		DEALLOCATE PREPARE St;

		INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Employee', TempEmpID);

	END IF;
		
		IF socialcommunicationID != "" THEN
			DELETE FROM hrm_employee_social_communication WHERE Emp_ID = socialcommunicationID;
			IF socialcommunication != "" THEN
				SET @SQL1 = CONCAT("INSERT INTO hrm_employee_social_communication(Emp_ID,SocialCommunication,SocialCommunication_Value) VALUES ", socialcommunication, ";");
				SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', socialcommunicationID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;
			END IF;
			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Employee Social Communication', socialcommunicationID);
		END IF;
		
		IF skillID != "" THEN
			DELETE FROM hrm_employee_skill WHERE Emp_ID = skillID;
			IF skill != "" THEN
				SET @SQL1 = CONCAT("INSERT INTO hrm_employee_skill(Emp_ID,Skill_Name,Skill_Level,Skill_Description) VALUES ", skill , ";");
				SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', skillID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;
			END IF;
			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Employee Skill', skillID);
		END IF;
		
		IF languageID != "" THEN
			DELETE FROM hrm_employee_language WHERE Emp_ID = languageID;
			IF language != "" THEN
				SET @SQL1 = CONCAT("INSERT INTO hrm_employee_language(Emp_ID,Language,Language_ReadLevel,Language_WriteLevel,Language_SpeakLevel,Language_UnderstandLevel,Language_Type) VALUES ", language , ";");
				SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', languageID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;
			END IF;
			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Employee Language', languageID);
		END IF;
		
		IF educationID != "" THEN
			DELETE FROM hrm_employee_education WHERE Emp_ID = educationID;
			IF education != "" THEN
				SET @SQL1 = CONCAT("INSERT INTO hrm_employee_education(Emp_ID,Edu_Name,Edu_StartDate,Edu_EndDate,Edu_Degree,Edu_School,Edu_Major,Edu_Description,Edu_Attachfile) VALUES ", education , ";");
				SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', educationID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;
			END IF;
			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Employee Education', educationID);
		END IF;
		
		IF experienceID != "" THEN
			DELETE FROM hrm_employee_experience WHERE Emp_ID = experienceID;
			IF experience != "" THEN
				SET @SQL1 = CONCAT("INSERT INTO hrm_employee_experience(Emp_ID,Ex_Position,Ex_Company,Ex_StartDate,Ex_EndDate,Ex_Description) VALUES ", experience , ";");
				SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', experienceID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;
			END IF;
			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Employee Experience', experienceID);
		END IF;
		
		IF familyID != "" THEN
			DELETE FROM hrm_employee_family WHERE Emp_ID = familyID;
			IF family != "" THEN
				SET @SQL1 = CONCAT("INSERT INTO hrm_employee_family(Emp_ID,Fam_Name,Fam_NameKh,Fam_DOB,Fam_Relative,Fam_Occupation,Fam_Tel,Fam_TaxDeduct) VALUES ", family , ";");
				SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', familyID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;
			END IF;
			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Employee Family', familyID);
		END IF;
		
		IF contractID != "" THEN
			DELETE FROM hrm_employee_contract WHERE Emp_ID = contractID;
			IF contract != "" THEN
				SET @SQL1 = CONCAT("INSERT INTO hrm_employee_contract(Emp_ID,Con_Name,Con_Type,Con_StartDate,Con_EndDate,Con_Description,Con_EmpPosition,Con_EmpType,Con_EmpCategory,Con_EmpGrade,Con_EmpBranchID,Con_EmpDepartmentID,Con_AttachFile) VALUES ", contract , ";");
				SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', contractID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
			END IF;
			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Employee Contract', contractID);
		END IF;
		
		IF trainID != "" THEN
			DELETE FROM hrm_employee_training WHERE Emp_ID = trainID;	
			IF training != "" THEN
				SET @SQL1 = CONCAT("INSERT INTO hrm_employee_training(Emp_ID,Train_InstituteName,Train_Certificate,Train_Course,Train_StartDate,Train_EndDate,Train_Description,Train_AttachFile) VALUES ", training , ";");
				SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', trainID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
			END IF;
			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Employee Training', trainID);
		END IF;
		
		IF attachmentID != "" THEN
			DELETE FROM hrm_employee_attachment WHERE Emp_ID = attachmentID;
			IF attachment != "" THEN
				SET @SQL1 = CONCAT("INSERT INTO hrm_employee_attachment(Emp_ID,Att_FileName,Att_FilePath) VALUES ", attachment , ";");
				SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', attachmentID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
			END IF;
			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Employee Attachment', attachmentID);
		END IF;
		
		IF membershipID != "" THEN
			DELETE FROM hrm_employee_membership WHERE Emp_ID = membershipID;
			IF membership != "" THEN
				SET @SQL1 = CONCAT("INSERT INTO hrm_employee_membership(Emp_ID,Mem_Name,Mem_Institute,Mem_GrantedOn,Mem_ValidThru,Mem_Type,Mem_Description,Mem_Attachfile) VALUES ", membership , ";");
				SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', membershipID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
			END IF;
			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Employee Membership', membershipID);
		END IF;
		
		IF insuranceID != "" THEN
			DELETE FROM hrm_employee_insurance WHERE Emp_ID = insuranceID;
			IF insurance != "" THEN
				SET @SQL1 = CONCAT("INSERT INTO hrm_employee_insurance(Emp_ID,Ins_InsuranceID,Ins_StartDate,Ins_ExpireDate,Ins_Description,Ins_SumInsured,Ins_Premium) VALUES ", insurance , ";");
				SET @SQL1 = REPLACE(@SQL1, 'TempEmp_ID', insuranceID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
			END IF;
			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Employee Insurance', insuranceID);
		END IF;

		IF user1 != "" AND user2 != ""  THEN
				SELECT u.var_id INTO UserName FROM ame_user u WHERE u.var_empid = TempEmpID;
				SELECT UserName;
				IF UserName != '' THEN
						SET @SQL1 = CONCAT("UPDATE ame_user SET ", user1 , " WHERE var_id='" , UserName, "';");
						PREPARE St FROM @SQL1;
						EXECUTE St;

						DELETE FROM ame_user_app WHERE var_id = UserName;
						INSERT INTO ame_user_app(var_id,var_appid) VALUES(SUID, 'HRM');
				ELSE
					SELECT Setting_Value INTO RoleESS FROM hrm_setting WHERE Setting_Name = 'ESS_Role' AND Setting_Type = 'User';
		
					SET @SQL1 = CONCAT("INSERT INTO ame_user(var_id,var_name,var_pwd,var_hrm_utype,var_hrm_role,var_empid) VALUES ", user2 , ";");
					SET @SQL1 = REPLACE(@SQL1, 'Temp_RoleESS', RoleESS);
					PREPARE St FROM @SQL1;
					EXECUTE St;
					
					INSERT INTO ame_user_app(var_id,var_appid) VALUES(SUID, 'HRM');
				END IF;
				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Employee User', TempEmpID);
		END IF;
		
		IF SuserAssign !="" THEN
			UPDATE ame_user SET var_empid = TempEmpID WHERE var_id = SuserAssign;
			DELETE FROM ame_user_app WHERE var_id = SuserAssign AND var_appid = 'HRM';
			INSERT INTO ame_user_app(var_id,var_appid) VALUES(SuserAssign, 'HRM');
		END IF;

		IF CategoryName != "" THEN
			CALL spHRMAddEmployeeCategory(userid, CategoryName, CONCAT("('",CategoryName,"')"), 0);
		END IF;
		IF ContractTypeName != "" THEN
			WHILE (LOCATE(',', ContractTypeName) > 0)
			DO
        SET @value = LEFT(ContractTypeName, LOCATE(',',ContractTypeName) - 1);    
        SET ContractTypeName = SUBSTRING(ContractTypeName, LOCATE(',',ContractTypeName) + 1);
				IF @value != "" THEN
					CALL spHRMAddEmployeeContractType(userid, @value, CONCAT("('",@value,"')"), 0);
				END IF;
			END WHILE;
		END IF;
		IF LanguageName != "" THEN
			WHILE (LOCATE(',', LanguageName) > 0)
			DO
        SET @value = LEFT(LanguageName, LOCATE(',',LanguageName) - 1);    
        SET LanguageName = SUBSTRING(LanguageName, LOCATE(',',LanguageName) + 1);
				IF @value != "" THEN
					CALL spHRMAddEmployeeLanguage(userid, @value, CONCAT("('",@value,"')"), 0);
				END IF;
			END WHILE;
		END IF;
		IF MembershipTypeName != "" THEN
			WHILE (LOCATE(',', MembershipTypeName) > 0)
			DO
        SET @value = LEFT(MembershipTypeName, LOCATE(',',MembershipTypeName) - 1);    
        SET MembershipTypeName = SUBSTRING(MembershipTypeName, LOCATE(',',MembershipTypeName) + 1);
				IF @value != "" THEN
					CALL spHRMAddEmployeeMembershipType(userid, @value, CONCAT("('",@value,"')"), 0);
				END IF;
			END WHILE;
		END IF;
		IF NationalityName != "" THEN
			CALL spHRMAddEmployeeNationality(userid, NationalityName, CONCAT("('",NationalityName,"')"), 0);
		END IF;
		IF NationalsName != "" THEN
			CALL spHRMAddEmployeeNationals(userid, NationalsName, CONCAT("('",NationalsName,"')"), 0);
		END IF;
		IF SchoolName != "" THEN
			WHILE (LOCATE(',', SchoolName) > 0)
			DO
        SET @value = LEFT(SchoolName, LOCATE(',',SchoolName) - 1);    
        SET SchoolName = SUBSTRING(SchoolName, LOCATE(',',SchoolName) + 1);
				IF @value != "" THEN
					CALL spHRMAddEmployeeSchool(userid, @value, CONCAT("('",@value,"')"), 0);
				END IF;
			END WHILE;
		END IF;
		IF SocialCommunicationName != "" THEN
			WHILE (LOCATE(',', SocialCommunicationName) > 0)
			DO
        SET @value = LEFT(SocialCommunicationName, LOCATE(',',SocialCommunicationName) - 1);    
        SET SocialCommunicationName = SUBSTRING(SocialCommunicationName, LOCATE(',',SocialCommunicationName) + 1);
				IF @value != "" THEN
					CALL spHRMAddEmployeeSocialCommunication(userid, @value, CONCAT("('",@value,"')"), 0);
				END IF;
			END WHILE;
		END IF;
		IF EmpStatus != "" THEN
			CALL spHRMAddEmployeeStatus(userid, EmpStatus, CONCAT("('", EmpStatus,"')"), 0);
		END IF;
		IF EmpType != "" THEN
			CALL spHRMAddEmployeeType(userid, EmpType, CONCAT("('", EmpType,"')"), 0);
		END IF;
		IF EmpCountry != "" THEN
			CALL spHRMAddEmployeeCountry(userid, EmpCountry, CONCAT("('", EmpCountry,"')"), 0);
		END IF;
		IF EmpPermanentCountry != "" THEN
			CALL spHRMAddEmployeeCountry(userid, EmpPermanentCountry, CONCAT("('", EmpPermanentCountry,"')"), 0);
		END IF;

		CALL hrm_message('1104502', 'Employee', 'update', TempEmpID);

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateEmployeeBank`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateEmployeeBank`(userid varchar(255),BankID varchar(255),BankName varchar(255),Bank text)
    DETERMINISTIC
BEGIN
	DECLARE CheckExist VARCHAR(255) DEFAULT('');
	DECLARE Exist VARCHAR(7) DEFAULT("");
	
	IF Bank != "" THEN
		SELECT DISTINCT(Bank_ID) INTO CheckExist FROM hrm_emp_bank WHERE LOWER(Bank_Name) = BankName;
		SELECT CheckExist;
		SELECT BankID;
		IF CheckExist = '' OR CheckExist = BankID THEN

			SET @SQL1 = CONCAT("UPDATE hrm_emp_bank SET ", Bank, " WHERE Bank_ID='" , BankID, "';");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'EmployeeBank', BankID);
			
			SET Exist = "success";
			SELECT Exist;
			CALL hrm_message('1102502', 'Bank', 'update', BankID);
		ELSE
			SET Exist = "exist";
			SELECT Exist;
			CALL hrm_message('1102504', 'Bank', 'exist', bankName);
		END IF;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateEmployeeBranch`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateEmployeeBranch`(userid varchar(255),BranchID varchar(255),BranchName varchar(255),Branch text)
    DETERMINISTIC
BEGIN
	DECLARE CheckExist VARCHAR(255) DEFAULT("");
	DECLARE Exist VARCHAR(7) DEFAULT("");
	
	IF Branch != "" THEN
		SELECT DISTINCT(Branch_ID) INTO CheckExist FROM hrm_emp_branch WHERE LOWER(Branch_Name) = BranchName;
		IF CheckExist = "" OR CheckExist = BranchID THEN
			SET @SQL1 = CONCAT("UPDATE hrm_emp_branch SET ", Branch, " WHERE Branch_ID='" , BranchID, "';");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'EmployeeBranch', BranchID);
			
			SET Exist = "success";
			SELECT Exist;
			CALL hrm_message('1102602', 'Branch', 'update', BranchID);
		ELSE
			SET Exist = "exist";
			SELECT Exist;
			CALL hrm_message('1102604', 'Branch', 'exist', BranchName);
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateEmployeeDepartment`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateEmployeeDepartment`(userid varchar(255),DepartmentID varchar(255),DepartmentName varchar(255),Department text)
    DETERMINISTIC
BEGIN
	DECLARE CheckExist VARCHAR(255) DEFAULT("");
	DECLARE Exist VARCHAR(7) DEFAULT("");

	IF Department != "" THEN
		SELECT DISTINCT(Department_ID) INTO CheckExist FROM hrm_emp_department WHERE LOWER(Department_Name) = DepartmentName;

		IF CheckExist = "" OR CheckExist = DepartmentID THEN

			SET @SQL1 = CONCAT("UPDATE hrm_emp_department SET ", Department, " WHERE Department_ID='" , DepartmentID, "';");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'EmployeeDepartment', DepartmentID);

			SET Exist = "success";
			SELECT Exist;
			CALL hrm_message('1103202', 'Department', 'update', DepartmentID);
		ELSE
			SET Exist = "exist";
			SELECT Exist;
			CALL hrm_message('1103204', 'Department', 'create', departmentName);
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateEmployeeInsurance`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateEmployeeInsurance`(userid varchar(255),InsuranceID varchar(255),InsuranceName varchar(255),Insurance text, InsuranceType varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE Exist VARCHAR(7) DEFAULT("");
	
	IF Insurance != "" THEN
			SET @SQL1 = CONCAT("UPDATE hrm_emp_insurance SET ", Insurance, " WHERE Insurance_ID='" , InsuranceID, "';");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'EmployeeInsurance', InsuranceID);

			IF InsuranceType != "" THEN
					CALL spHRMAddEmployeeInsuranceType(userid, InsuranceType, CONCAT("('", InsuranceType,"')"), 0);
			END IF;
			
			SET Exist = "success";
			SELECT Exist;
			CALL hrm_message('1103602', 'Insurance', 'update', InsuranceID);
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateEmployeePosition`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateEmployeePosition`(userid varchar(255), PositionID varchar(255), PositionName varchar(255), PositionLevel varchar(255), Position text)
    DETERMINISTIC
BEGIN

	DECLARE CheckExist VARCHAR(255) DEFAULT("");
	DECLARE Exist VARCHAR(7) DEFAULT("");

	IF Position != "" THEN

		SELECT DISTINCT(var_name) INTO CheckExist FROM ame_mt_pos p WHERE LOWER(p.var_id) <> PositionID AND LOWER(p.var_name) = PositionName AND LOWER(p.int_level) = PositionLevel LIMIT 1;

		IF CheckExist <> PositionName THEN

			SET @SQL1 = CONCAT("UPDATE ame_mt_pos SET ", Position, " WHERE var_id='" , PositionID , "';");
			PREPARE St FROM @SQL1;
			EXECUTE St;
			DEALLOCATE PREPARE St;

			INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'EmployeePosition', PositionID);

			SET Exist = "success";
			SELECT Exist;
			CALL hrm_message('1102902', 'Position', 'update', PositionID);
		ELSE
			SET Exist = "exist";
			SELECT Exist;
			CALL hrm_message_param3('1102904', 'Position', 'exist', PositionName, PositionLevel, '');
		END IF;

	END IF;

END |
DELIMITER ;

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

	UPDATE tblemployee SET EmpImg = FileName WHERE EmpID = ID;

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

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

DROP PROCEDURE IF EXISTS `spHRMUpdateHoliday`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateHoliday`(userid varchar(255),ID varchar(255),SName varchar(255), SType varchar(255), SStart Date,SEnd Date, SValue text, SValue2 text)
    DETERMINISTIC
BEGIN
	DECLARE CheckExist VARCHAR(255) DEFAULT("");
	DECLARE Exist VARCHAR(7) DEFAULT("");
	DECLARE CheckUsed INT DEFAULT 0;
	DECLARE CheckAllowed INT DEFAULT(0);
	DECLARE SNow DATE;
	DECLARE tz VARCHAR(20) DEFAULT('');

	DECLARE SOldStart Date;
	DECLARE SOldEnd 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);
	
	IF SValue != "" THEN

		IF CheckExist = "" THEN

			SELECT IF(Holiday_StartDate < SNow, 1, 0), Holiday_StartDate, Holiday_EndDate INTO CheckUsed,SOldStart,SOldEnd  FROM hrm_timesheet_holiday WHERE Holiday_ID = ID;

			IF CheckUsed <=0 THEN

				SET @SQL1 = CONCAT("UPDATE hrm_timesheet_holiday SET ", SValue, " WHERE Holiday_ID='" , ID, "';");
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				IF LOWER(SType) = 'all' THEN
					CALL spHRMAttendanceHolidayDeleteAll(SOldStart, SOldEnd);
				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 spHRMAttendanceHolidayDelete(SDType, SDBranch, SDDepartment, SOldStart, SOldEnd);
						END LOOP;
					END;
				END IF;	

				DELETE FROM hrm_timesheet_holiday_detail WHERE HolidayD_ID = ID;
				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;

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

					IF LOWER(SType) = 'all' THEN
						CALL spHRMAttendanceHolidayDeleteAll(SOldStart, SOldEnd);
						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;	
			
				SET Exist = "success";
				SELECT Exist;
				CALL hrm_message('1101802', 'Holiday', 'update', ID);
			ELSE
				SET Exist = "used";
				SELECT Exist;
				CALL hrm_message('1101805', 'Holiday', 'used', ID);
			END IF;
		ELSE
			SET Exist = "exist";
			SELECT Exist;
			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 `spHRMUpdateLeave`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateLeave`(userid varchar(255),SID varchar(255), SEmpID varchar(255), SValue text, SValue2 text)
    DETERMINISTIC
BEGIN
	DECLARE Exist VARCHAR(255);
	DECLARE CheckExist VARCHAR(255) DEFAULT("");
	DECLARE AuthType VARCHAR(255) DEFAULT("");
	DECLARE CheckAuth VARCHAR(1) DEFAULT("1");
	DECLARE Amt FLOAT DEFAULT(0);
	DECLARE AuthID VARCHAR(255) DEFAULT("");
	DECLARE ADMIN TINYINT 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

				SELECT COUNT(*) INTO CheckExist FROM hrm_authorisation_approved WHERE Auth_ProcessID = SID 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 = SID AND (Leave_Status = "approved" OR Leave_Status = "rejected");
				END IF;

				SELECT IF(LOWER(UType) = 'administrator', 1, 0) INTO ADMIN FROM tbluser WHERE UID = userid;

				IF CheckExist <= 0 OR ADMIN > 0 THEN
			
					-- find Auth ID
					SELECT Auth_ID INTO AuthID FROM hrm_authorisation_employee WHERE Emp_ID = SEmpID AND Auth_Process = 'Leave';
					IF AuthID = "" THEN
						SELECT Setting_Value INTO AuthID FROM hrm_setting WHERE Setting_Name = 'Leave' AND Setting_Type = 'Authorisation';
					END IF;

					IF AuthID != "" THEN

							SET @SQL1 = CONCAT("UPDATE hrm_timesheet_leave SET ", SValue, " WHERE Leave_ID='" , SID, "';");
							IF CheckExist <= 0 THEN
								SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'requested');
							ELSE
								SET @SQL1 = REPLACE(@SQL1, "Leave_Status='Temp_Status',", '');
							END IF;
							SET @SQL1 = REPLACE(@SQL1, 'Temp_AuthID', AuthID);
							PREPARE St FROM @SQL1;
							EXECUTE St;
							DEALLOCATE PREPARE St;

							DELETE FROM hrm_timesheet_leave_detail WHERE LeaveD_ID = SID;
							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', SID);
							PREPARE St FROM @SQL1;
							EXECUTE St;
							DEALLOCATE PREPARE St;

							INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Leave', SID);

							IF CheckExist <= 0 THEN

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

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

								CALL spHRMAddAuthorisationTemp(AuthID,SID); 

							END IF;
				
							SET Exist = "success";
							SELECT Exist;
							CALL hrm_message('1101602', 'Leave', 'update', SID);

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

				ELSE
					SET Exist = "used";
					SELECT Exist;
					CALL hrm_message('1101605', 'Leave', 'used', SID);
				END IF;

			ELSE
	
						SET @SQL1 = CONCAT("UPDATE hrm_timesheet_leave SET ", SValue, " WHERE Leave_ID='" , SID, "';");
						SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'approved');
						SET @SQL1 = REPLACE(@SQL1, 'Temp_AuthID', '');
						PREPARE St FROM @SQL1;
						EXECUTE St;
						DEALLOCATE PREPARE St;

						call spHRMCheckDeleteAttendanceLeave(SID, SEmpID); 

						DELETE FROM hrm_timesheet_leave_detail WHERE LeaveD_ID = SID;
						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', SID);
						PREPARE St FROM @SQL1;
						EXECUTE St;
						DEALLOCATE PREPARE St;

						call spHRMCheckAddAttendanceLeave(SID, SEmpID); 

						INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Leave', SID);
						
						SET Exist = "success";
						SELECT Exist;
						CALL hrm_message('1101602', 'Leave', 'update', SID);
									
			END IF;
	
	END IF;
	
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateNumberPrefix`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateNumberPrefix`(IN MID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Num LONG;
	SELECT LastID INTO Num FROM hrm_numberprefix WHERE ModuleID = MID;
	UPDATE hrm_numberprefix SET LastID = Num+1 WHERE ModuleID = MID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateOvertime`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateOvertime`(userid varchar(255),SID varchar(255),SValue text, SValue2 text, SValue3 text)
    DETERMINISTIC
BEGIN
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE Exist VARCHAR(30) DEFAULT("");
	DECLARE CheckAuth VARCHAR(1) DEFAULT("1");
	DECLARE AuthType VARCHAR(255) DEFAULT("");
	DECLARE AuthID VARCHAR(255) DEFAULT("");
	DECLARE CheckU VARCHAR(255) DEFAULT("");
	DECLARE Emp VARCHAR(255) DEFAULT("");
	DECLARE ADMIN TINYINT DEFAULT(0);
	DECLARE SEmpReq VARCHAR(255) DEFAULT("");

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

	SELECT Overtime_RequestBy INTO SEmpReq FROM hrm_payroll_overtime WHERE Overtime_ID = SID;
	
	IF (SValue != "" AND CheckU = "ESS") OR (SValue != "" AND (CheckU = "Normal" OR CheckU = "Administrator")) THEN
	
		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 = SID 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 = SID AND (Overtime_Status = "approved" OR Overtime_Status = "rejected" OR Overtime_Status = "approved & paid");
			END IF;

			SELECT IF(LOWER(var_hrm_utype) = 'administrator', 1, 0) INTO ADMIN FROM ame_user WHERE var_id = userid;

			IF CheckExist <= 0 OR ADMIN > 0 THEN

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

				IF AuthID != "" THEN
			
						SET @SQL1 = CONCAT("UPDATE hrm_payroll_overtime SET ", SValue, " WHERE Overtime_ID='" , SID, "';");
						IF CheckExist <= 0 THEN
							SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'requested');
						ELSE
							SET @SQL1 = REPLACE(@SQL1, "Overtime_Status='Temp_Status',", '');
						END IF;
						SET @SQL1 = REPLACE(@SQL1, 'Temp_AuthID', AuthID);
						PREPARE St FROM @SQL1;
						EXECUTE St;
						DEALLOCATE PREPARE St;

						DELETE FROM hrm_payroll_overtime_detail WHERE od_id = SID;
						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', SID);
						PREPARE St FROM @SQL1;
						EXECUTE St;
						DEALLOCATE PREPARE St;

						DELETE FROM hrm_payroll_overtime_detail_employee WHERE od_id = SID AND LOWER(od_status) = 'open';
						SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_overtime_detail_employee(od_id,od_empid,od_status) VALUES ", SValue3, ";");
						SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', SID);
						PREPARE St FROM @SQL1;
						EXECUTE St;
						DEALLOCATE PREPARE St;

						IF CheckExist <= 0 THEN
							DELETE FROM hrm_authorisation_approved WHERE  Auth_ProcessID = SID AND Auth_ProcessName = "Overtime";

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

						INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Overtime', SID);
						SET Exist = "success";
						SELECT Exist;
						CALL hrm_message('1100702', 'Overtime', 'update', SID);
				ELSE
					SET Exist = "no authorisation";
					SELECT Exist;
					CALL hrm_message('1100706', 'Overtime', 'auth', SEmpReq);
				END IF;

			ELSE
				SET Exist = "used";
				SELECT Exist;
				CALL hrm_message('1100705', 'Overtime', 'used', SID);
			END IF;
		ELSE
				SET @SQL1 = CONCAT("UPDATE hrm_payroll_overtime SET ", SValue, " WHERE Overtime_ID='" , SID, "';");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_Status', 'approved');
				SET @SQL1 = REPLACE(@SQL1, 'Temp_AuthID', '');
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				DELETE FROM hrm_payroll_overtime_detail WHERE od_id = SID;
				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', SID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

				DELETE FROM hrm_payroll_overtime_detail_employee WHERE od_id = SID AND LOWER(od_status) = 'open';
				SET @SQL1 = CONCAT("INSERT INTO hrm_payroll_overtime_detail_employee(od_id,od_empid,od_status) VALUES ", SValue3, ";");
				SET @SQL1 = REPLACE(@SQL1, 'Temp_ID', SID);
				PREPARE St FROM @SQL1;
				EXECUTE St;
				DEALLOCATE PREPARE St;

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

				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Overtime', SID);
				SET Exist = "success";
				SELECT Exist;
				CALL hrm_message('1100702', 'Overtime', 'update', SID);
		END IF;
	
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateRole`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateRole`(userid varchar(255),SID varchar(255),SValue text, SValueDetail text, SValueRDetail text)
    DETERMINISTIC
BEGIN
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE Exist VARCHAR(7) DEFAULT("");
	DECLARE CheckUsed INT DEFAULT(0);
	IF SValue != "" THEN
		-- SELECT COUNT(*) INTO CheckUsed FROM tbluser WHERE UHRMRoleID= SID;

		IF CheckUsed <= 0 AND SID <> 'ADMIN' AND SID <> 'ESS' THEN
					SET @SQL1 = CONCAT("UPDATE hrm_role SET ", SValue, " WHERE RM_ID='" , SID, "';");
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;

					DELETE FROM hrm_role_detail WHERE RM_RoleID = SID;
					DELETE FROM hrm_role_rpt_detail WHERE RMR_RoleID = SID;
		
					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', SID);
					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', SID);
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;

					INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Role', SID);
			
					SET Exist = "success";
					SELECT Exist;
					CALL hrm_message('1104302', 'Role', 'update', SID);
		ELSE
				SET Exist = "used";
				SELECT Exist;
				CALL hrm_message('1104305', 'Role', 'used', SID);
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateSetting`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateSetting`(userid varchar(255), Setting text, Conditions text, FilePath varchar(255), Absent text, Late text, Acc varchar(255), CashAcc varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Exist VARCHAR(7) DEFAULT("");
	SET @SQL1 = CONCAT("UPDATE hrm_setting SET Setting_Value = CASE ", Setting, "END WHERE " , Conditions, ";");
	PREPARE St FROM @SQL1;
	EXECUTE St;
	DEALLOCATE PREPARE St;

	SET @SQL1 = CONCAT("UPDATE tblconfiguration SET ImagePath='", FilePath ,"'");
	SET sql_mode = 'NO_BACKSLASH_ESCAPES';
	PREPARE St FROM @SQL1;
	EXECUTE St;
	DEALLOCATE PREPARE St;

	SET @SQL1 = CONCAT("UPDATE hrm_setting SET ", Absent, " WHERE Setting_Type='Attendance_Absent_PayAmount';");
	PREPARE St FROM @SQL1;
	EXECUTE St;
	DEALLOCATE PREPARE St;

	SET @SQL1 = CONCAT("UPDATE hrm_setting SET ", Late, " WHERE Setting_Type='Attendance_Late_PayAmount';");
	PREPARE St FROM @SQL1;
	EXECUTE St;
	DEALLOCATE PREPARE St;

	SET @SQL1 = CONCAT("UPDATE tblaccountset SET AccID='", Acc ,"' WHERE AccType='Payroll' AND GroupID='Acc'");
	PREPARE St FROM @SQL1;
	EXECUTE St;
	DEALLOCATE PREPARE St;

	SET @SQL1 = CONCAT("UPDATE tblaccountset SET AccID='", CashAcc ,"' WHERE AccType='Payroll' AND GroupID='CashAcc'");
	PREPARE St FROM @SQL1;
	EXECUTE St;
	DEALLOCATE PREPARE St;

	CALL spHRMAddLog(userid, "update", "Setting", "" );
	SET Exist = "success";
	SELECT Exist;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateTblNumberPrefix`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateTblNumberPrefix`(IN MID varchar(255))
    DETERMINISTIC
BEGIN
	DECLARE Num LONG;
	DECLARE N INT;
	SELECT LastID,Length INTO Num,N FROM tblnumberprefix WHERE ModuleID = MID;
	UPDATE tblnumberprefix SET LastID = LPAD(CONCAT(Num+1,''),N,'0') WHERE ModuleID = MID;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateTimesheetLeaveType`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateTimesheetLeaveType`(userid varchar(255),ID varchar(255),LeaveTypeName varchar(255),LeaveType text, CValue2 text)
    DETERMINISTIC
BEGIN
	DECLARE CheckExist VARCHAR(255) DEFAULT("");
	DECLARE Exist VARCHAR(7) DEFAULT("");
	DECLARE CheckUsed INT DEFAULT 0;
	DECLARE tz VARCHAR(20) DEFAULT('');
	
	IF LeaveType != "" THEN

		SELECT DISTINCT(LeaveType_ID) INTO CheckExist FROM hrm_timesheet_leave_type WHERE LOWER(LeaveType_Name) = LeaveTypeName;

		IF CheckExist = "" OR CheckExist = ID THEN
			SELECT COUNT(*) INTO CheckUsed FROM hrm_timesheet_leave_detail WHERE LeaveD_TypeID = ID;
			IF CheckUsed <= 0 THEN
				SELECT COUNT(*) INTO CheckUsed FROM hrm_timesheet_leave_type_employee WHERE Leave_TypeID = ID;
			END IF;
			IF CheckUsed <=0 THEN
				SET @SQL1 = CONCAT("UPDATE hrm_timesheet_leave_type SET ", LeaveType, " WHERE LeaveType_ID='" , ID, "';");
				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_Now',DATE_FORMAT(convert_tz(now(), @@session.time_zone, tz), '%Y-%m-%d'));
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;
				END IF;

				INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'Leave Type', ID);
			
				SET Exist = "success";
				SELECT Exist;
				CALL hrm_message('1101202', 'LeaveType', 'update', ID);
			ELSE
				SET Exist = "used";
				SELECT Exist;
				CALL hrm_message('1101205', 'LeaveType', 'used', ID);
			END IF;
		ELSE
			SET Exist = "exist";
			SELECT Exist;
			CALL hrm_message('1101204', 'LeaveType', 'exist', LeaveTypeName);
		END IF;
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateUser`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateUser`(userid varchar(255), SOldID varchar(255), SNewID varchar(255), SValue text, SValue1 text)
    DETERMINISTIC
BEGIN
	DECLARE CheckExist INT DEFAULT(0);
	DECLARE Exist VARCHAR(7) DEFAULT("");

	IF SValue != "" THEN

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

		IF CheckExist <= 0 OR SOldID = SNewID AND SOldID <> 'ADMIN' THEN

					SET @SQL1 = CONCAT("UPDATE ame_user SET ", SValue, " WHERE var_id='" , SOldID, "';");
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;				

					DELETE FROM ame_user_app WHERE var_id = SOldID;

					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, 'update', 'User', CONCAT(SOldID, ', ', SNewID));
			
					SET Exist = "success";
					SELECT Exist;
					CALL hrm_message('1104402', 'User', 'update', SNewID);
		ELSE
				SET Exist = "exist";
				SELECT Exist;
				CALL hrm_message('1104404', 'User', 'exist', SNewID);
		END IF;

	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spHRMUpdateWorkShift`;
DELIMITER |
CREATE PROCEDURE `spHRMUpdateWorkShift`(userid varchar(255),SID varchar(255), SName varchar(255),SValue text, SValueDetail text)
    DETERMINISTIC
BEGIN
	DECLARE CheckExist VARCHAR(255) DEFAULT("");
	DECLARE Exist VARCHAR(7) DEFAULT("");
	DECLARE CheckUsed INT DEFAULT(0);

	SELECT DISTINCT(Shift_ID) INTO CheckExist FROM hrm_timesheet_workshift WHERE LOWER(Shift_Name) = SName;
	IF SValue != "" AND (CheckExist = "" OR CheckExist = SID) THEN
		SELECT COUNT(*) INTO CheckUsed FROM ame_mt_emp e WHERE e.var_hrm_shift_id= SID;
		IF CheckUsed <= 0 THEN
					SET @SQL1 = CONCAT("UPDATE hrm_timesheet_workshift SET ", SValue, " WHERE Shift_ID='" , SID, "';");
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;

					DELETE FROM hrm_timesheet_workshift_detail WHERE Shift_ID = SID;
		
					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, ";");
					PREPARE St FROM @SQL1;
					EXECUTE St;
					DEALLOCATE PREPARE St;

					INSERT INTO hrm_log(UID,ActionType,FrmSysName,RecordID) VALUES(userid, 'update', 'WorkShift', SID);
			
					SET Exist = "success";
					SELECT Exist;
					CALL hrm_message('1101902', 'WorkShift', 'update', SID);
		ELSE
				SET Exist = "used";
				SELECT Exist;
				CALL hrm_message('1101905', 'WorkShift', 'used', SID);
		END IF;
	ELSE
			SET Exist = "exist";
			SELECT Exist;
			CALL hrm_message('1101904', 'WorkShift', 'exist', SName);
	END IF;

END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spLoad_hrm_computer_skill`;
DELIMITER |
CREATE PROCEDURE `spLoad_hrm_computer_skill`(in search varchar(255),in os int(11),in c tinyint(1))
    DETERMINISTIC
BEGIN
		IF c = 1 THEN
				IF os <> -1 THEN
						IF search <> "NULL" THEN
								SET @Cond = search;
								SET @SQL = CONCAT("SELECT COUNT(l.ComputerSkill) FROM hrm_computer_skill l "," WHERE (",@Cond,")");
						ELSE
								SET @SQL = CONCAT("SELECT COUNT(l.ComputerSkill) FROM hrm_computer_skill l");
						END IF;
				ELSE
						IF search <> "NULL" THEN
								SET @RowIndex = -1;
								SET @Cond = search;
								SET @SQL = CONCAT("SELECT RowIndex FROM (SELECT @RowIndex:=@RowIndex + 1 As RowIndex,l.ComputerSkill FROM hrm_computer_skill l ORDER BY l.ComputerSkill) AS l"," WHERE (",@Cond,")");
						END IF;
				END IF;					
		ELSE			
				SET @QrSelect = "SELECT l.ComputerSkill 'Computer Skill' FROM hrm_computer_skill l";
				SET @Oft = os;
				IF search <> "NULL" THEN
						SET @Cond = search;
						SET @SQL = CONCAT(@QrSelect," WHERE (",@Cond,") ORDER BY l.ComputerSkill ","LIMIT 100"," OFFSET ",@Oft);			
				ELSE
						SET @SQL = CONCAT(@QrSelect," ORDER BY l.ComputerSkill ","LIMIT 100"," OFFSET ",@Oft);
				END IF;
		END IF;	
		PREPARE St FROM @SQL;
		EXECUTE St;
		DEALLOCATE PREPARE St;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spLoad_hrm_efficiency`;
DELIMITER |
CREATE PROCEDURE `spLoad_hrm_efficiency`(in search varchar(255),in os int(11),in c tinyint(1))
    DETERMINISTIC
BEGIN
		IF c = 1 THEN
				IF os <> -1 THEN
						IF search <> "NULL" THEN
								SET @Cond = search;
								SET @SQL = CONCAT("SELECT COUNT(l.EfficiencyName) FROM hrm_efficiency l "," WHERE (",@Cond,")");
						ELSE
								SET @SQL = CONCAT("SELECT COUNT(l.EfficiencyName) FROM hrm_efficiency l");
						END IF;
				ELSE
						IF search <> "NULL" THEN
								SET @RowIndex = -1;
								SET @Cond = search;
								SET @SQL = CONCAT("SELECT RowIndex FROM (SELECT @RowIndex:=@RowIndex + 1 As RowIndex,l.EfficiencyName FROM hrm_efficiency l ORDER BY l.EfficiencyName) AS l"," WHERE (",@Cond,")");
						END IF;
				END IF;					
		ELSE			
				SET @QrSelect = "SELECT l.EfficiencyName 'Efficiency Name',COALESCE(l.EfficiencyInKhmer,'') 'Efficiency In Khmer' FROM hrm_efficiency l";
				SET @Oft = os;
				IF search <> "NULL" THEN
						SET @Cond = search;
						SET @SQL = CONCAT(@QrSelect," WHERE (",@Cond,") ORDER BY l.EfficiencyName ","LIMIT 100"," OFFSET ",@Oft);
				ELSE
						SET @SQL = CONCAT(@QrSelect," ORDER BY l.EfficiencyName ","LIMIT 100"," OFFSET ",@Oft);
				END IF;
		END IF;
		PREPARE St FROM @SQL;
		EXECUTE St;
		DEALLOCATE PREPARE St;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spLoad_hrm_langauge`;
DELIMITER |
CREATE PROCEDURE `spLoad_hrm_langauge`(in search varchar(255),in os int(11),in c tinyint(1))
    DETERMINISTIC
BEGIN
		IF c = 1 THEN
				IF os <> -1 THEN
						IF search <> "NULL" THEN
								SET @Cond = search;
								SET @SQL = CONCAT("SELECT COUNT(l.LanguageName) FROM hrm_language l "," WHERE (",@Cond,")");
						ELSE
								SET @SQL = CONCAT("SELECT COUNT(l.LanguageName) FROM hrm_language l");
						END IF;
				ELSE
						IF search <> "NULL" THEN
								SET @RowIndex = -1;
								SET @Cond = search;
								SET @SQL = CONCAT("SELECT RowIndex FROM (SELECT @RowIndex:=@RowIndex + 1 As RowIndex,l.LanguageName FROM hrm_language l ORDER BY l.LanguageName) AS l"," WHERE (",@Cond,")");
						END IF;
				END IF;					
		ELSE			
				SET @QrSelect = "SELECT l.LanguageName 'Language Name',COALESCE(l.LanguageInKhmer,'') 'Language In Khmer' FROM hrm_language l";
				SET @Oft = os;
				IF search <> "NULL" THEN
						SET @Cond = search;
						SET @SQL = CONCAT(@QrSelect," WHERE (",@Cond,") ORDER BY l.LanguageName ","LIMIT 100"," OFFSET ",@Oft);			
				ELSE
						SET @SQL = CONCAT(@QrSelect," ORDER BY l.LanguageName ","LIMIT 100"," OFFSET ",@Oft);
				END IF;
		END IF;	
		PREPARE St FROM @SQL;
		EXECUTE St;
		DEALLOCATE PREPARE St;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `spLoad_hrm_relative`;
DELIMITER |
CREATE PROCEDURE `spLoad_hrm_relative`(in search varchar(255),in os int(11),in c tinyint(1))
    DETERMINISTIC
BEGIN
		IF c = 1 THEN
				IF os <> -1 THEN
						IF search <> "NULL" THEN
								SET @Cond = search;
								SET @SQL = CONCAT("SELECT COUNT(l.Relative) FROM hrm_relative l "," WHERE (",@Cond,")");
						ELSE
								SET @SQL = CONCAT("SELECT COUNT(l.Relative) FROM hrm_relative l");
						END IF;
				ELSE
						IF search <> "NULL" THEN
								SET @RowIndex = -1;
								SET @Cond = search;
								SET @SQL = CONCAT("SELECT RowIndex FROM (SELECT @RowIndex:=@RowIndex + 1 As RowIndex,l.Relative FROM hrm_relative l ORDER BY l.Relative) AS l"," WHERE (",@Cond,")");
						END IF;
				END IF;					
		ELSE			
				SET @QrSelect = "SELECT l.Relative 'Relative',COALESCE(l.RelativeInKhmer,'') 'Relative In Khmer' FROM hrm_relative l";
				SET @Oft = os;
				IF search <> "NULL" THEN
						SET @Cond = search;
						SET @SQL = CONCAT(@QrSelect," WHERE (",@Cond,") ORDER BY l.Relative ","LIMIT 100"," OFFSET ",@Oft);
				ELSE
						SET @SQL = CONCAT(@QrSelect," ORDER BY l.Relative ","LIMIT 100"," OFFSET ",@Oft);
				END IF;
		END IF;
		PREPARE St FROM @SQL;
		EXECUTE St;
		DEALLOCATE PREPARE St;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `TM_COUNTRY_LIST_DEST`;
DELIMITER |
CREATE PROCEDURE `TM_COUNTRY_LIST_DEST`()
BEGIN
	SELECT country_id, country_name FROM tm_country WHERE country_inactive = 1;
	SELECT destination_id, destination_name, country_id FROM tm_destination WHERE destination_inactive = 1;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `tm_list_country`;
DELIMITER |
CREATE PROCEDURE `tm_list_country`(var_limit int(6), var_page int(6), var_search varchar(255))
BEGIN
	DECLARE var_off INT;
	SET var_off = ((var_page-1)*var_limit);
	IF var_search = '' THEN
		SELECT 
			country_id,
			country_name,
			country_description
		FROM tm_country
		WHERE country_inactive = 1
		LIMIT var_off, var_limit;
	ELSE
		SELECT 
			country_id,
			country_name,
			country_description
		FROM tm_country
		WHERE country_inactive = 1
		AND (country_name LIKE CONCAT('%', var_search, '%') 
		OR country_id LIKE CONCAT('%', var_search, '%'))
		LIMIT var_off, var_limit;
	END IF;

	SELECT COUNT(country_id) 'totalRecords' 
	FROM tm_country 
	WHERE country_inactive = 1 
	AND IF(var_search = '', TRUE, (country_name LIKE CONCAT('%', var_search, '%') 
	OR country_id LIKE CONCAT('%', var_search, '%'))); -- Total Shop
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `tm_list_status_tour`;
DELIMITER |
CREATE PROCEDURE `tm_list_status_tour`(type varchar(19))
BEGIN
	#Routine body goes here...
	IF type = 'status' THEN
		SELECT status_id, status_name FROM tm_tour_status ;
	ELSE
		SELECT tour_id, tour_code, tour_subject FROM tm_tour;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `tm_load_language`;
DELIMITER |
CREATE PROCEDURE `tm_load_language`()
BEGIN
	SET SESSION group_concat_max_len = 10000000;
	SELECT CONCAT("{",GROUP_CONCAT(CONCAT("\"",TRIM(COALESCE(LangCode,"")),"\":","[\"",TRIM(COALESCE(EN,"")),"\",\"",TRIM(COALESCE(KH,"")),"\",\"",COALESCE(CN,""),"\"]")),"}") as 'JSON'
	FROM tm_language_object;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `TM_PRO_BOOKING_LIST`;
DELIMITER |
CREATE PROCEDURE `TM_PRO_BOOKING_LIST`(booking_id varchar(100))
BEGIN
	#Routine body goes here...
	IF booking_id = '' THEN
			SELECT
					tb.booking_id 'bookId',
					DATE_FORMAT(booking_date,'%d/%M/%Y')'booking_Date',
					(SELECT status_name FROM tm_tour_status tts WHERE tts.status_id = tb.status_id)'status',
					CONCAT('[',tb.tour_id,'] ', (SELECT var_itemcode FROM ame_mt_ite WHERE var_id = (SELECT item FROM tm_tour tt WHERE tb.tour_id = tt.tour_id))) 'tourId',
					(SELECT DATE_FORMAT(start_date,'%d/%M/%Y') FROM tm_tour tt WHERE tb.tour_id = tt.tour_id)'start_date',
					(SELECT DATE_FORMAT(end_date,'%d/%M/%Y') FROM tm_tour tt WHERE tb.tour_id = tt.tour_id)'end_date',
					(SELECT GROUP_CONCAT(DISTINCT (SELECT country_name FROM tm_country WHERE tm_country.country_id = tm_tour_trip.country_id) SEPARATOR ', ') FROM tm_tour_trip WHERE tour_id = tb.tour_id) 'country',
					(SELECT var_name FROM ame_mt_emp WHERE var_id = (SELECT tour_leader FROM tm_tour tt WHERE tb.tour_id = tt.tour_id)) 'tour_leader'
			FROM tm_booking tb WHERE tb.booking_inactive = 1;
	ELSE
			SELECT
				tbd.var_id 'var_id',
				tbd.booking_id 'booking_id',
				tbd.mode_id 'mode_id',
				tbd.company_id 'company_id',
				tbd.flight_no 'flight_no',
				DATE_FORMAT(tbd.dep_date,'%d/%m/%Y')'dep_date',
				tbd.dep_time 'dep_time',
				DATE_FORMAT(tbd.arr_date,'%d/%m/%Y')'arr_date',
				tbd.arr_time 'arr_time',
				tbd.dep_location 'dep_location',
				tbd.arr_location 'arr_location',
				tbd.flight_duration 'flight_duration',
				tbd.transit,
				tbd.itemid,
				tbd.air_line,
				(SELECT mode_name FROM tm_mode_transport tmt WHERE mode_id=tbd.mode_id)'mode',
				(SELECT company_name FROM tm_company WHERE company_id=tbd.company_id)'company',
				(SELECT GROUP_CONCAT(var_uom_id) FROM tm_booking_detail_uom WHERE var_bd_id = tbd.var_id) 'group_uom',
				(SELECT GROUP_CONCAT(dou_qty) FROM tm_booking_detail_uom WHERE var_bd_id = tbd.var_id) 'group_qty',
				(SELECT GROUP_CONCAT(dou_price) FROM tm_booking_detail_uom WHERE var_bd_id = tbd.var_id) 'group_price',
				(SELECT GROUP_CONCAT(dou_tax) FROM tm_booking_detail_uom WHERE var_bd_id = tbd.var_id) 'group_tax',
				(SELECT GROUP_CONCAT(dou_amt) FROM tm_booking_detail_uom WHERE var_bd_id = tbd.var_id) 'group_amt'
      FROM tm_booking_detail tbd WHERE tbd.booking_id = booking_id;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `TM_PRO_BOOKING_LOAD`;
DELIMITER |
CREATE PROCEDURE `TM_PRO_BOOKING_LOAD`(tourId varchar(100))
BEGIN
	IF tourid = '' THEN
		#Load Status
		SELECT 
			status_id,
			status_name
		FROM 
			tm_tour_status 
		WHERE status_inactive = 1;
		#Load Tour	
		SELECT
			tt.tour_id 'tour_id',
			(SELECT var_itemcode FROM ame_mt_ite WHERE var_id = item) 'var_itemcode'
		FROM 
			tm_tour tt
		LEFT JOIN tm_booking USING(tour_id)
		WHERE tour_inactive = 1 AND tm_booking.tour_id IS NULL OR tm_booking.booking_inactive = 2;
		#Load MODE
		SELECT mode_name , mode_id FROM tm_mode_transport WHERE mode_inactive = 1;
		#Load Compay
		SELECT company_id,company_name FROM tm_company WHERE company_inactive = 1;
	ELSE
		#Load Tour
		SELECT 
			(SELECT tm_tour_category.category_name FROM tm_tour_category WHERE tm_tour_category.id = tt.category_id) 'category',
			(SELECT tm_tour_type.type_name FROM tm_tour_type WHERE tm_tour_type.type_id = tt.type_id) 'type',
			(SELECT ami.var_itemcode FROM ame_mt_ite ami WHERE tt.item = ami.var_id)'code',
			DATE_FORMAT(tt.start_date, '%d/%m/%Y') 'startdate',
			DATE_FORMAT(tt.end_date, '%d/%m/%Y') 'enddate',
			(SELECT var_name FROM ame_mt_emp WHERE ame_mt_emp.var_id = tt.tour_leader) 'emp',
			(SELECT tm_tour_season.season_name FROM tm_tour_season WHERE tm_tour_season.season_id = tt.season_id) 'season',
			tt.item 'itemId'
		FROM
			tm_tour tt
		WHERE tt.tour_id = tourId;
		#Load Country & Destination
		SELECT country_id, country_name FROM tm_country WHERE country_id IN (SELECT tm_tour_trip.country_id FROM tm_tour_trip WHERE tour_id = tourId);
		SELECT destination_id, destination_name, country_id FROM tm_destination WHERE destination_id IN (SELECT tm_tour_trip.destination FROM tm_tour_trip WHERE tour_id = tourId);
		SELECT var_uomid 'uom', (SELECT var_name FROM ame_mt_uom WHERE var_id = var_uomid) 'uomname', COALESCE(int_tm_amount, 0)'qty' FROM ame_mt_ite_uom WHERE var_id = (SELECT item FROM tm_tour WHERE tour_id = tourId);
		#Load Tour on Update
		SELECT
			tt.tour_id 'tour_id',
			(SELECT var_itemcode FROM ame_mt_ite WHERE var_id = item) 'var_itemcode'
		FROM 
			tm_tour tt
		LEFT JOIN tm_booking USING(tour_id)
		WHERE tour_inactive = 1 AND tm_booking.tour_id IS NULL OR tm_booking.booking_inactive = 2 OR tt.tour_id = tourId;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `TM_PRO_BOOKING_LOAD_UPDATE`;
DELIMITER |
CREATE PROCEDURE `TM_PRO_BOOKING_LOAD_UPDATE`(booking_id varchar(100))
BEGIN
		SELECT
						tb.booking_id 'bookId',
						DATE_FORMAT(booking_date,'%d/%m/%Y')'booking_Date',
						tb.tour_id 'tourId',
						tb.status_id 'statusId',
						(SELECT status_name FROM tm_tour_status tts WHERE tts.status_id = tb.status_id)'status',
					  (SELECT item FROM tm_tour tt WHERE tb.tour_id = tt.tour_id)'itemId',
						(SELECT DATE_FORMAT(start_date,'%d/%m/%Y') FROM tm_tour tt WHERE tt.tour_id = tb.tour_id)'start_date',
						(SELECT DATE_FORMAT(end_date,'%d/%m/%Y') FROM tm_tour tt WHERE tt.tour_id = tb.tour_id)'end_date',
						(SELECT GROUP_CONCAT(DISTINCT (SELECT country_name FROM tm_country WHERE tm_country.country_id = tm_tour_trip.country_id) SEPARATOR ', ') FROM tm_tour_trip WHERE tour_id = tb.tour_id) 'country',
						(SELECT var_name FROM ame_mt_emp WHERE var_id = (SELECT tour_leader FROM tm_tour tt WHERE tb.tour_id = tt.tour_id)) 'tour_leader',
						tb.booking_description 'description'
		FROM tm_booking tb WHERE tb.booking_id = booking_id;
		SELECT 
					tbd.var_id 'var_id',
					tbd.booking_id 'booking_id',
					tbd.mode_id 'mode_id',
					tbd.company_id 'company_id',
					tbd.flight_no 'flight_no',
					DATE_FORMAT(tbd.dep_date,'%d/%m/%Y')'dep_date',
					tbd.dep_time 'dep_time',
					DATE_FORMAT(tbd.arr_date,'%d/%m/%Y')'arr_date',
					tbd.arr_time 'arr_time',
					tbd.dep_location 'dep_location',
					tbd.arr_location 'arr_location',
					tbd.flight_duration 'flight_duration',
					tbd.transit,
					tbd.itemid,
					tbd.air_line,
					(SELECT mode_name FROM tm_mode_transport tmt WHERE mode_id=tbd.mode_id)'mode',
					(SELECT company_name FROM tm_company WHERE company_id=tbd.company_id)'company',
					(SELECT GROUP_CONCAT(var_uom_id) FROM tm_booking_detail_uom WHERE var_bd_id = tbd.var_id) 'group_uom',
					(SELECT GROUP_CONCAT(dou_qty) FROM tm_booking_detail_uom WHERE var_bd_id = tbd.var_id) 'group_qty',
					(SELECT GROUP_CONCAT(dou_price) FROM tm_booking_detail_uom WHERE var_bd_id = tbd.var_id) 'group_price',
					(SELECT GROUP_CONCAT(dou_tax) FROM tm_booking_detail_uom WHERE var_bd_id = tbd.var_id) 'group_tax',
					(SELECT GROUP_CONCAT(dou_amt) FROM tm_booking_detail_uom WHERE var_bd_id = tbd.var_id) 'group_amt'
				FROM tm_booking_detail tbd WHERE tbd.booking_id = booking_id;
		#CALL TM_PRO_BOOKING_LOAD('');
			#Load Status
		SELECT 
			status_id,
			status_name
		FROM 
			tm_tour_status 
		WHERE status_inactive = 1;
		#Load MODE
		SELECT mode_name , mode_id FROM tm_mode_transport WHERE mode_inactive = 1;
		#Load Compay
		SELECT company_id,company_name FROM tm_company WHERE company_inactive = 1;
		CALL TM_PRO_BOOKING_LOAD((SELECT tm_booking.tour_id FROM tm_booking WHERE tm_booking.booking_id = booking_id));
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `TM_PRO_DESTINATION_LIST`;
DELIMITER |
CREATE PROCEDURE `TM_PRO_DESTINATION_LIST`(IN var_limit int(3), IN var_page int(3), IN var_country varchar(255), IN var_desti varchar(255))
BEGIN
	#Routine body goes here...
	DECLARE var_offset int(3);
	SET var_offset = ((var_page-1)*var_limit);
	
	#SELECT ALL
	IF var_country = '' AND var_desti = '' THEN
		SELECT 
			destination_id,
			destination_name,
			destination_description,
			country_name,tc.country_id 
		FROM 
			tm_destination td 
		INNER JOIN tm_country tc ON td.country_id = tc.country_id 
		WHERE destination_inactive=1 LIMIT var_offset,var_limit;
	#FILTER
	ELSE
		#IF COUNTRY NOT EXISTS
		IF var_country = '' THEN
			SELECT 
				destination_id,
				destination_name,
				destination_description,
				country_name,tc.country_id 
			FROM 
				tm_destination td 
			INNER JOIN tm_country tc ON td.country_id = tc.country_id 
			WHERE destination_inactive = 1 AND td.destination_name LIKE CONCAT('%', var_desti, '%')
			LIMIT var_offset,var_limit;
		#IF COUNTRY EXITS
		ELSE
			#IF DESTINATION NOT EXISTS
			IF var_desti = '' THEN
				SELECT 
					destination_id,
					destination_name,
					destination_description,
					country_name,tc.country_id 
				FROM 
					tm_destination td 
				INNER JOIN tm_country tc ON td.country_id = tc.country_id 
				WHERE destination_inactive=1 AND td.country_id = var_country
				LIMIT var_offset,var_limit;#
			#IF DESTINATION EXISTS
			ELSE
				SELECT 
					destination_id,
					destination_name,
					destination_description,
					country_name,tc.country_id 
				FROM 
					tm_destination td 
				INNER JOIN tm_country tc ON td.country_id = tc.country_id 
				WHERE destination_inactive = 1 AND td.country_id = var_country AND td.destination_name LIKE CONCAT('%', var_desti, '%')
				LIMIT var_offset,var_limit;
			END IF;
		END IF;
	END IF;


	#GET TOTAL RECORD
	IF var_country = '' AND var_desti = '' THEN
		SELECT 
			COUNT(destination_id) 'totalRecords'
		FROM tm_destination td 
		INNER JOIN tm_country tc ON td.country_id = tc.country_id 
		WHERE destination_inactive=1 LIMIT var_offset,var_limit;
	#FILTER
	ELSE
		#IF COUNTRY NOT EXISTS
		IF var_country = '' THEN
			SELECT 
				COUNT(destination_id) 'totalRecords'
			FROM 
				tm_destination td 
			INNER JOIN tm_country tc ON td.country_id = tc.country_id 
			WHERE destination_inactive = 1 AND td.destination_name LIKE CONCAT('%', var_desti, '%')
			LIMIT var_offset,var_limit;
		#IF COUNTRY EXITS
		ELSE
			#IF DESTINATION NOT EXISTS
			IF var_desti = '' THEN
				SELECT 
					COUNT(destination_id) 'totalRecords'
				FROM 
					tm_destination td 
				INNER JOIN tm_country tc ON td.country_id = tc.country_id 
				WHERE destination_inactive=1 AND td.country_id = var_country
				LIMIT var_offset,var_limit;
			#IF DESTINATION EXISTS
			ELSE
				SELECT 
					COUNT(destination_id) 'totalRecords'
				FROM 
					tm_destination td 
				INNER JOIN tm_country tc ON td.country_id = tc.country_id 
				WHERE destination_inactive = 1 AND td.country_id = var_country AND td.destination_name LIKE CONCAT('%', var_desti, '%')
				LIMIT var_offset,var_limit;
			END IF;
		END IF;
	END IF;
		
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `TM_PRO_NUMBERPREFIX_LOAD`;
DELIMITER |
CREATE PROCEDURE `TM_PRO_NUMBERPREFIX_LOAD`(IN par_limit INT(6), IN par_page INT(6), IN  startup TINYINT(1))
BEGIN
	DECLARE var_off INT;
	SET var_off = ((par_page-1)*par_limit);
	SELECT
		var_modid 'module_id',
		var_type 'type',
		var_id 'prefix',
		COALESCE(int_length, 0) 'length',
		COALESCE(int_lastid, 0) 'lastid',
		(SELECT remark FROM tm_numberprefix WHERE module_id = var_modid) 'remark'
	FROM
		tm_numberprefix_custom
	WHERE
		int_IsUsed = 1
	LIMIT var_off, par_limit;
		
	SELECT COUNT(var_modid) 'totalrecords' FROM tm_numberprefix_custom WHERE int_IsUsed = 1; #TotalRecord

	IF startup = true THEN
		SELECT module_id FROM tm_numberprefix WHERE hide = 0;
	END IF;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `TM_PRO_OP_LOAD`;
DELIMITER |
CREATE PROCEDURE `TM_PRO_OP_LOAD`()
BEGIN
	#Routine body goes here...
	SELECT status_id,status_name FROM tm_op_status WHERE status_inactive = 1;
	SELECT progress_id,progress_name FROM tm_progress WHERE progress_inactive = 1;
	#Load Tour	
	SELECT
		tt.tour_id 'tour_id',
		(SELECT var_itemcode FROM ame_mt_ite WHERE var_id = item) 'var_itemcode'
	FROM 
		tm_tour tt
	LEFT JOIN tm_op_progress_tour tp ON tt.tour_id = tp.var_tour_id
	WHERE tt.tour_inactive = 1 AND tp.var_tour_id IS NULL ;
	#Template
	SELECT var_name,
				 var_id,
				(SELECT GROUP_CONCAT(topd.var_progress) FROM tm_op_template_detail topd WHERE top.var_id = topd.var_id) 'item',
				(SELECT GROUP_CONCAT(CONCAT('<span style="background-color: #398bf7;color: white;padding: 5px;border-radius: 5px;">',topd.var_progress,'</span>')) 
				FROM tm_op_template_detail topd WHERE top.var_id = topd.var_id)'progress' 
	FROM tm_op_template top WHERE tin_inactive = 1;
END |
DELIMITER ;

DROP PROCEDURE IF EXISTS `TM_PRO_OP_TEMPLATE_LIST`;
DELIMITER |
CREATE PROCEDURE `TM_PRO_OP_TEMPLATE_LIST`()
