<?php
include '../connect/cms-config.php' ;
include '../requires/function.php' ;

// using this link https://www.devglan.com/online-tools/rsa-encryption-decryption
// RSA Encryption 
//	-- Enter Plain Text to Encrypt ( 1234567890030188 )
//  -- Enter Public/Private key ( MFswDQYJKoZIhvcNAQEBBQADSgAwRwJAY5pTsXQKlatdfq/W4BDSBcOk5lyDfwtK3elJnCKeA6v5mwSVAqk17XLJ8zXRus1tk0dtNULH02WDRXOI6SBcIwIDAQAB )
//  -- Select Cipher Type ( RSA )
// will get result ( ASp8qEBeQpu/Y3FfoagKElhJgvi4A1hH0aTwcvIko1jPsHYm2x1rdEW+rqwZ/QY4YpBmmZhgvLiOZrx73yuQoQ== )

// URL : https://malhrmsgateway.azurewebsites.net
// Client ID : dceb24cd-9965-404c-9988-8b8da4f6bd19
// Secret Key : WoXOHQfBAsUR3gTBu91uh5tcWxqR6e
// PGP Key for Encryption : MFswDQYJKoZIhvcNAQEBBQADSgAwRwJAY5pTsXQKlatdfq/W4BDSBcOk5lyDfwtK3elJnCKeA6v5mwSVAqk17XLJ8zXRus1tk0dtNULH02WDRXOI6SBcIwIDAQAB

$companys = [
    [
        "CompanyID" 	=> 2,
        "CompanyCode" 	=> null,
        "CompanyName" 	=> "M&R MANUFACTURING SDN BHD"
    ],
    [
        "CompanyID" 	=> 4,
        "CompanyCode" 	=> null,
        "CompanyName" 	=> "M&R MANUFACTURING SDN BHD (ISKANDAR)"
    ],
    [
        "CompanyID" 	=> 5,
        "CompanyCode" 	=> null,
        "CompanyName" 	=> "M&R INTEGRATED SOLUTION SDN BHD"
    ],
    [
        "CompanyID" 	=> 6,
        "CompanyCode" 	=> null,
        "CompanyName" 	=> "ASA MULTIPLATE (M) SDN BHD"
    ],
    [
        "CompanyID" 	=> 7,
        "CompanyCode" 	=> null,
        "CompanyName" 	=> "M & R INTEGRATED SYNERGY SDN BHD"
    ]
] ;


$infotech_authorization = 'ASp8qEBeQpu/Y3FfoagKElhJgvi4A1hH0aTwcvIko1jPsHYm2x1rdEW+rqwZ/QY4YpBmmZhgvLiOZrx73yuQoQ==' ;
$infotech_api 		    = 'https://malhrmsgateway.azurewebsites.net' ;
$infotech_clientid      = 'dceb24cd-9965-404c-9988-8b8da4f6bd19' ;
$infotech_secretkey     = 'WoXOHQfBAsUR3gTBu91uh5tcWxqR6e' ;
$infotech_key           = '1234567890030188';
$infotech_iv            = 'Info-TechGateWay' ;


foreach ( $companys as $kcompany => $vcompany ){

	$infotech_companyid     = $vcompany['CompanyID'] ;

	$call_token             = call(  'curl',  $infotech_api.'/Authenticate', 'POST', [ "Authorization:".$infotech_clientid.':'.$infotech_secretkey, "customkey:".$infotech_authorization ], [ "Grant_type" => "password" ]
				) ;

	if ( $call_token['access_token'] != null ){

		// get all current staff
		$staffs 		    = [] ;
		$select_staff       = $mysqli->query("SELECT staff_id, staff_idno, group_id FROM staff 
											  WHERE deleted_at IS NULL AND staff_idno != '' ORDER BY group_id") ;
		if ( $select_staff->num_rows > 0 ){
			while ( $row_staff = $select_staff->fetch_assoc() ){
				$staffs[$row_staff['staff_idno']] = $row_staff ;
			}
		}

		// get all working code
		$workingids 		= [] ;
		$workingnames 		= [] ;
		$select_working     = $mysqli->query("SELECT group_id, group_name FROM setting_working_group 
											  WHERE deleted_at IS NULL ORDER BY group_id") ;
		if ( $select_working->num_rows > 0 ){
			while ( $row_working = $select_working->fetch_assoc() ){
				$workingids[$row_working['group_id']]   = $row_working['group_name'] ;
				$workingnames[$row_working['group_name']] = $row_working['group_id'] ;
			}
		}


		// get staff details
		$call_parameter     = [
			"CompanyID"     => $infotech_companyid,
			"IsActive"      => "1"
		] ;
		$plaintext 		    = json_encode( $call_parameter ) ;
		$ciphertext 	    = openssl_encrypt( $plaintext, 'aes-128-cbc', $infotech_key, OPENSSL_RAW_DATA, $infotech_iv ) ;
		$get_str 	        = base64_encode( $ciphertext ) ;
		$call_staff         = call(  'curl-json',  $infotech_api.'/Api/GetEmployeeDetails', 'GET', [ "Authorization:Bearer ".$call_token['access_token'] ], [ "str" => $get_str ]
					) ;

		// check staff shiftcode same with system or not
		$update_staffs      = [] ;
		if ( count($call_staff) > 0 ){
			foreach ( $call_staff as $k => $v ){
				$get_staff    = $staffs[$v['EmployeeCode']] ;
				$get_group_id = $get_staff['group_id'] ;

				if ( $v['ShiftCode'] != '' && $v['ShiftCode'] != $workingids[$get_group_id] ){
					$update_staffs[$get_staff['staff_id']] = $workingnames[$v['ShiftCode']] ;
				}
			}
		}

		// update all staff latest shift
		if ( count($update_staffs) > 0 ){

			$staff_ids       = [] ;
			$case_ids        = [] ;
			foreach ( $update_staffs as $k => $v ){
				$case_ids[]  = " WHEN staff_id = '".$k."' THEN '".$v."'" ;
				$staff_ids[] = $k ;
			}

			$update_query = "
			    UPDATE staff
			    SET group_id = CASE
			        ".implode( '', $case_ids )."
			        ELSE group_id
			    END
			    WHERE staff_id IN ( ".implode( ', ', $staff_ids )." )
			" ;
			$mysqli->query( $update_query  ) ;
		}







		// get leave details
		$call_parameter    = [
			"CompanyID" => $infotech_companyid,
			"EmpCode"   => "",
			// "FromDate"  => '22/07/2023',
			// "ToDate"	=> '22/07/2023',
			"FromDate"  => date( "d/m/Y", time() ),
			"ToDate"	=> date( "d/m/Y", time() )
		] ;
		$plaintext 		   = json_encode( $call_parameter ) ;
		$ciphertext 	   = openssl_encrypt( $plaintext, 'aes-128-cbc', $infotech_key, OPENSSL_RAW_DATA, $infotech_iv ) ;
		$get_str 	       = base64_encode( $ciphertext ) ;
		$call_leave        = call(  'curl-json',  $infotech_api.'/Api/GetLeaveDetails', 'GET', [ "Authorization:Bearer ".$call_token['access_token'] ], [ "str" => $get_str ]
					) ;

		$leaves 		   = [] ;
		if ( count($call_leave) > 0 ){
			foreach ( $call_leave as $k => $v ){
				if ( $v['LeaveStatus'] == 'APPROVED' ){
					$get_staff     = $staffs[$v['EmpCodeC']] ;

					$v['staff_id'] = $get_staff['staff_id'] ;
					$leaves[]      = $v ;
					$kkk[$v['LeaveType']] = $v['LeaveType'] ;
 				}
			}
		}

		foreach ( $leaves as $kleave => $vleave ){

			$leave_type_mode        = 'working' ;
			$leave_date  	        = date( 'Y-m-d', strtotime( $vleave['LvDateD'] ) ) ;
			$leave_work_day         = '0' ;
			$leave_type             = 'unpaid' ;
			$leave_work_direct 		= 'yes' ;
			switch ( $vleave['LeaveType'] ){
				case 'HOURLY LEAVE UNPAID' :
					$leave_type     = 'unpaid' ;
					$leave_work_day = 'hourly' ;
				break ;
				case 'UNPAID LEAVE' :
					$leave_type     = 'unpaid' ;
					$leave_work_day = 'full' ;
				break ;
				case 'UNPAID LEAVE FIRST HALF' :
					$leave_type     = 'unpaid' ;
					$leave_work_day = 'firsthalf' ;
				break ;
				case 'UNPAID LEAVE SECOND HALF' :
					$leave_type     = 'unpaid' ;
					$leave_work_day = 'secondhalf' ;
				break ;
				case 'ANNUAL LEAVE' :
				case 'REPLACEMENT LEAVE' :
				case 'MATRIMONIAL LEAVE' :
				case 'COMPASSIONATE LEAVE' :
				case 'EMERGENCY LEAVE' :
					$leave_type     = 'annual' ;
					$leave_work_day = 'full' ;
				break ;
				case 'ANNUAL LEAVE FIRST HALF' :
				case 'EMERGENCY LEAVE FIRST HALF' :
					$leave_type     = 'annual' ;
					$leave_work_day = 'firsthalf' ;
				break ;
				case 'ANNUAL LEAVE SECOND HALF' :
				case 'EMERGENCY LEAVE SECOND HALF' :
					$leave_type     = 'annual' ;
					$leave_work_day = 'secondhalf' ;
				break ;
				case 'MEDICAL LEAVE' :
				case 'HOSPITALIZATION LEAVE' :
				case 'MATERNITY LEAVE' :
				case 'PATERNITY LEAVE' :
					$leave_type     = 'sick' ;
					$leave_work_day = 'full' ;
				break ;
			}

			$select_leave = $mysqli->query( "SELECT * FROM staff_leave_date
											 WHERE deleted_at IS NULL AND staff_id = '".$vleave['staff_id']."' AND leave_type = '".$leave_type."' AND leave_type_mode = '".$leave_type_mode."' AND leave_date = '".$leave_date."'" ) ;
			if ( $select_leave->num_rows == 0 ){
				$mysqli->query( "INSERT INTO staff_leave_date
								 ( staff_id, leave_type, leave_type_mode, leave_date, leave_work_direct, leave_work_day ) VALUES
								 ( '".$vleave['staff_id']."', '".$leave_type."', '".$leave_type_mode."', '".$leave_date."', '".$leave_work_direct."', '".$leave_work_day."' )" ) ;
			}
		}

		// print_r($leaves) ;
		// print_r("<br />") ;
		// print_r("<br />") ;
		// print_r("<br />") ;

	}

}

?>