<?php
require_once('config.php');
$valid = true;


/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
     die( print_r( sqlsrv_errors(), true ));
}

$json = file_get_contents('php://input');

$data = json_decode($json, true);

$site_cd 		= $data['site_cd'];
$new_site_cd 	= $data['new_site_cd'];
$login_id 		= $data['login_id'];
$Emp_ID 		= $data['Emp_ID'];
$device_ID 		= $data['dvc_id'];
$brand 			= $data['brand'];
$model 			= $data['model'];
$online 		= $data['online'];
$token 			= $data['token'];
$version 		= $data['version'];


	//Checking existing license(uninstall before logout)
	$sql_tkn_mst= "SELECT 	existing_count = count(*)  
			FROM  	tkn_mst (NOLOCK)
			WHERE	tkn_dvc_id='".$device_ID."' 
			AND		tkn_site = '".$new_site_cd."'
			AND 	tkn_logout is NULL";

	$stmt_tkn_mst = sqlsrv_query( $conn, $sql_tkn_mst);

	if( !$stmt_tkn_mst ) {
		 $error_message = "Error selecting table (tkn_mst)";
		 returnError($error_message);
		 die( print_r( sqlsrv_errors(), true));
	}

	do {
		 while ($row = sqlsrv_fetch_array($stmt_tkn_mst, SQLSRV_FETCH_ASSOC)) {
			 
			$existing_count = $row['existing_count'];
		}
	} while ( sqlsrv_next_result($stmt_tkn_mst) );

	if($existing_count > 0){
		
	}else{
		
		
		//Checking User license
		$sql_tkn_mst= "SELECT 	tkn_count = count(*)  
				FROM  	tkn_mst (NOLOCK)
				WHERE	tkn_site = '".$new_site_cd."'
				AND 	tkn_logout is NULL";

		$stmt_tkn_mst = sqlsrv_query( $conn, $sql_tkn_mst);

		if( !$stmt_tkn_mst ) {
			 $error_message = "Error selecting table (tkn_mst)";
			 returnError($error_message);
			 die( print_r( sqlsrv_errors(), true));
		}
	
	
		do {
			 while ($row = sqlsrv_fetch_array($stmt_tkn_mst, SQLSRV_FETCH_ASSOC)) {
				 
				$tkn_count = $row['tkn_count'];
			 }
		} while ( sqlsrv_next_result($stmt_tkn_mst) );
	
	
	
		//Step 1: Get sys_ver_mobile_license
		$sql_sys_ver = "SELECT 	sys_ver_mobile_license  FROM  sys_ver (NOLOCK)";

		$stmt_sys_ver = sqlsrv_query( $conn, $sql_sys_ver);

		if( !$stmt_sys_ver ) {
			 $error_message = "Error selecting table (sys_ver)";
			 returnError($error_message);
			 die( print_r( sqlsrv_errors(), true));
		}
	
	
		do {
			 while ($row = sqlsrv_fetch_array($stmt_sys_ver, SQLSRV_FETCH_ASSOC)) {
				 
				$sys_ver_mobile_license = $row['sys_ver_mobile_license'];
			 }
		} while ( sqlsrv_next_result($stmt_sys_ver) );
	
	
		if ($sys_ver_mobile_license > 0) {
			
			// ✅ Case 1: sys_ver_mobile_license is NOT 0
			if ($tkn_count >= $sys_ver_mobile_license) {
				
				
				returnError("License exceeded, please contact system administrator.");
			}
			
		}else{
			
			//Checking User license on cf_site
			$sql_sys_ver = "SELECT 	mobile_license  FROM  cf_site (NOLOCK) where site_cd = '".$site_cd."'";

			$stmt_sys_ver = sqlsrv_query( $conn, $sql_sys_ver);

			if( !$stmt_sys_ver ) {
				 $error_message = "Error selecting table (cf_site)";
				 returnError($error_message);
				 die( print_r( sqlsrv_errors(), true));
			}
		
		
			do {
				 while ($row = sqlsrv_fetch_array($stmt_sys_ver, SQLSRV_FETCH_ASSOC)) {
					 
					$mobile_license = $row['mobile_license'];
				 }
			} while ( sqlsrv_next_result($stmt_sys_ver) );
		
		
			if( $tkn_count >= $mobile_license ){
				returnError("License exceed, please contact system administrator.");
			}
				
		}
		
	}
	
	
	//Checking User exits are not 
	$sql= "select user_exits = count(*)  from cf_user (NOLOCK)  WHERE	cf_user.empl_id ='".$login_id."'";

	$stmt_cf_user = sqlsrv_query( $conn, $sql);

	if( !$stmt_cf_user ) {
		 $error_message = "Error selecting table (cf_user)";
		 returnError($error_message);
		 die( print_r( sqlsrv_errors(), true));
	}
	do {
		 while ($row = sqlsrv_fetch_array($stmt_cf_user, SQLSRV_FETCH_ASSOC)) {
			 
			$user_exits = $row['user_exits'];
		 }
	} while ( sqlsrv_next_result($stmt_cf_user) );
		
	if($user_exits == 1){
		
		//Checking User is Locked are not 
		$sql= "SELECT 	cf_user_locked FROM  cf_user (NOLOCK) WHERE	cf_user.empl_id ='".$login_id."'";
		$stmt_cf_user = sqlsrv_query( $conn, $sql);

		if( !$stmt_cf_user ) {
			 $error_message = "Error selecting table (cf_user)";
			 returnError($error_message);
			 die( print_r( sqlsrv_errors(), true));
		}
		
		
		do {
			 while ($row = sqlsrv_fetch_array($stmt_cf_user, SQLSRV_FETCH_ASSOC)) {
				 
				$cf_user_locked = $row['cf_user_locked'];
			 }
		} while ( sqlsrv_next_result($stmt_cf_user) );
		
	
		if($cf_user_locked == 0){
		
			//Checking User is site code login are not 
			$sql= "	SELECT 	COUNT = COUNT(*) 
					FROM 	cf_site_user (NOLOCK)
					WHERE 	site_cd = '".$new_site_cd."' 					
					AND 	empl_id = '".$login_id."'";

			$stmt_cf_site_user = sqlsrv_query( $conn, $sql);

			if( !$stmt_cf_site_user ) {
				 $error_message = "Error selecting table (cf_site_user)";
				 returnError($error_message);
				 die( print_r( sqlsrv_errors(), true));
			}
			
			
			do {
				 while ($row = sqlsrv_fetch_array($stmt_cf_site_user, SQLSRV_FETCH_ASSOC)) {
					 
					$COUNT = $row['COUNT'];
				 }
			} while ( sqlsrv_next_result($stmt_cf_site_user) );
				
			
			if($COUNT == 1){
					//Checking User is employee profile in this site 
					$sql= "SELECT 	COUNT(*) as li_cnt,
									Max(emp_mst_status) as emp_mst_status
							FROM 	emp_mst (NOLOCK) 
							WHERE 	site_cd = '".$new_site_cd."' 
							AND 	emp_mst_login_id = '".$login_id."'";


					$stmt_emp_mst = sqlsrv_query( $conn, $sql);

					if( !$stmt_emp_mst ) {
						 $error_message = "Error selecting table (emp_mst)";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
					}
					
					
					do {
						 while ($row = sqlsrv_fetch_array($stmt_emp_mst, SQLSRV_FETCH_ASSOC)) {
							 
							$li_cnt = $row['li_cnt'];
							$emp_mst_status = $row['emp_mst_status'];
						 }
					} while ( sqlsrv_next_result($stmt_emp_mst) );
						
					
					if($li_cnt == 1){
						
							//Checking Employee assigned to the User Login ID had deactivated
							$sql= "SELECT 	COUNT(*) as li_cnt
									FROM 	emp_sts (NOLOCK) 
									WHERE 	site_cd = '".$new_site_cd."' 
									AND 	emp_sts_cat_cd = 'EMPLOYEE' 
									AND 	emp_sts_typ_cd = 'DEACTIVATE' 
									AND 	emp_sts_status = '".$emp_mst_status."'";


							$stmt_emp_sts = sqlsrv_query( $conn, $sql);

							if( !$stmt_emp_sts ) {
								 $error_message = "Error selecting table (emp_sts)";
								 returnError($error_message);
								 die( print_r( sqlsrv_errors(), true));
							}
							
							
							do {
								 while ($row = sqlsrv_fetch_array($stmt_emp_sts, SQLSRV_FETCH_ASSOC)) {
									 
									$li_cnt = $row['li_cnt'];									
								 }
							} while ( sqlsrv_next_result($stmt_emp_sts) );
								
							
							if($li_cnt == 0){
								
								
								
									//Checking Employee mobile access
									$sql= "SELECT 		emp_det_mobile = COALESCE(emp_det_mobile, '0')
											FROM 		emp_mst (NOLOCK)  											
											INNER JOIN 	emp_det (NOLOCK) ON emp_mst.site_cd = emp_det.site_cd And	emp_mst.rowid = emp_det.mst_rowid		
											And  		emp_mst.site_cd = '".$new_site_cd."'							
											And 		emp_mst_login_id = '".$login_id."'";


									$stmt_emp_sts = sqlsrv_query( $conn, $sql);

									if( !$stmt_emp_sts ) {
										 $error_message = "Error selecting table (emp_sts)";
										 returnError($error_message);
										 die( print_r( sqlsrv_errors(), true));
									}
									
									
									do {
										 while ($row = sqlsrv_fetch_array($stmt_emp_sts, SQLSRV_FETCH_ASSOC)) {
											 
											$emp_det_mobile = $row['emp_det_mobile'];									
										 }
									} while ( sqlsrv_next_result($stmt_emp_sts) );
									
									
									if($emp_det_mobile == '1' ){
										
										
										// Logout old site 
										$sql_tkn_mst = "UPDATE tkn_mst 
														SET 	tkn_logout = GetDate(),
																tkn_online = '0'							
														WHERE 	tkn_site =?
														AND 	tkn_dvc_id = ? 
														AND 	tkn_user =?
														AND 	tkn_online = '1'";
												
											
											$params_tkn_mst = array($site_cd,$device_ID,$Emp_ID);
											$stmt_tkn_mst = sqlsrv_query( $conn, $sql_tkn_mst,$params_tkn_mst);	
												
										if( !$stmt_tkn_mst ) {
											$error_message = "Error update table (tkn_mst)";
											returnError($error_message);
											die( print_r( sqlsrv_errors(), true));
										}sqlsrv_free_stmt( $stmt_tkn_mst);
										
										
										// Get Defauit Value
										$sql = "SELECT 
													dft_mst_wko_sts = COALESCE(dft_mst_wko_sts + ' : ' + wrk_sts_desc,''), 
													dft_mst_lab_act = COALESCE(dft_mst_lab_act,''), 
													dft_mst_mat_act = COALESCE(dft_mst_mat_act,''), 
													dft_mst_con_act = COALESCE(dft_mst_con_act,''), 
													dft_mst_wko_pri = COALESCE(dft_mst_wko_pri + ' : ' + wrk_pri_desc + ' - ' + cast(wrk_pri_due_date_count as varchar),''), 
													dft_mst_temp_ast , 
													dft_mst_wko_asset_no = COALESCE(dft_mst_wko_asset_no,''), 
													dft_mst_wkr_asset_no = COALESCE(dft_mst_wkr_asset_no,'') ,
													dft_mst_wo_default_cc , 
													dft_mst_time_card_by , 
													dft_mst_itm_resv, 
													dft_mst_po_auto_close,
													dft_mst_mr_approval , 
													dft_mst_mtr_email_approver , 
													dft_mst_tim_act = COALESCE(dft_mst_tim_act,''),
													dft_mst_gen_inv,
													dft_mst_mbl_chk_cmp,
													dft_mst_mbl_chk_scan,
													dft_mst_pur_email_approver,
													dft_mst_pur_email_requestor,
													dft_mst_generate_po,
													dft_mst_edit_wo_date,
													dft_mst_edit_wr_date,
													dft_mst_mbl_single_login,
													dft_mst_cm_req_cmp,
													dft_mst_pm_req_cmp,
													dft_mst_openai,
													dft_mst_wo_camera_act,
													dft_mst_dft_wo_appr_status = COALESCE(dft_mst_dft_wo_appr_status,''),
													cf_site.site_name
													
												FROM dft_mst (NOLOCK) 
												
												LEFT OUTER JOIN wrk_pri (NOLOCK) 
												ON dft_mst.site_cd = wrk_pri.site_cd 
												AND dft_mst.dft_mst_wko_pri = wrk_pri.wrk_pri_pri_cd 
												
												LEFT OUTER JOIN wrk_sts (NOLOCK) 
												ON dft_mst.site_cd = wrk_sts.site_cd 
												AND dft_mst.dft_mst_wko_sts = wrk_sts.wrk_sts_status 
												
												LEFT OUTER JOIN cf_site (NOLOCK) 
												ON dft_mst.site_cd = cf_site.site_cd
												WHERE dft_mst.site_cd = ?";

										
										if (!$conn) {
											$error_message = "Database connection failed: " . print_r(sqlsrv_errors(), true);
											returnError('Error', $error_message);
										}

										$params = array($new_site_cd);
										$stmt = sqlsrv_query($conn, $sql, $params);

										if (!$stmt) {
											$error_message = "Error executing query: " . print_r(sqlsrv_errors(), true);
											returnError('Error', $error_message);
										}

										$Defaultvalue = array();

										// Fetch data
										while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
											$Defaultvalue[] = $row;
										}

										// Free statement and close connection
										sqlsrv_free_stmt($stmt);
										
										$sql= "	Select 	emp_mst_empl_id, 
														emp_mst_name,
														emp_mst_title= COALESCE(emp_mst_title,''),
														emp_mst_homephone= COALESCE(emp_mst_homephone,''),
														emp_mst_login_id,
														emp_det_wr_approver,
														emp_det_mr_approver,
														emp_det_mr_limit,
														emp_det_pr_approver,
														emp_det_pr_approval_limit,
														emp_det_work_grp= COALESCE(emp_det_work_grp,''),
														emp_det_work_grp_des= COALESCE(emp_det_work_grp+':'+wrk_grp_desc,''),
														emp_det_craft = COALESCE(emp_det_craft+':'+crf_mst_desc,''),
														emp_ls1_charge_rate = COALESCE(emp_ls1.emp_ls1_charge_rate,0),
														cf_site.require_offline
												
												From 	emp_mst (NOLOCK)

												LEFT 
												OUTER JOIN	emp_det (NOLOCK) 
												ON 			emp_mst.site_cd = emp_det.site_cd		
												And			emp_mst.rowid = emp_det.mst_rowid
												
												LEFT 
												OUTER JOIN	emp_ls1 (NOLOCK) 
												ON			emp_det.mst_rowid = emp_ls1.mst_rowid	
												And			emp_det.site_cd = emp_ls1.site_cd	
												AND			emp_det.emp_det_craft = emp_ls1.emp_ls1_craft
												
												LEFT 
												OUTER JOIN	wrk_grp (NOLOCK) 
												ON 			emp_det.site_cd = wrk_grp.site_cd		
												AND			emp_det.emp_det_work_grp = wrk_grp.wrk_grp_grp_cd
												
												LEFT 
												OUTER JOIN	crf_mst (NOLOCK) 
												ON 			emp_det.site_cd = crf_mst.site_cd		
												AND			emp_det.emp_det_craft = crf_mst.crf_mst_crf_cd
												
												LEFT 
												OUTER JOIN	cf_site (NOLOCK)
												ON			emp_mst.site_cd = cf_site.site_cd
												and 		cf_site.disable_flag = '0'
												
												Where 		emp_mst.site_cd = emp_det.site_cd
												And			emp_mst.rowid = emp_det.mst_rowid
												And 		emp_mst_login_id = '".$login_id."' 
												And 		emp_mst.site_cd = '".$new_site_cd."'";

										$stmt_emp_det = sqlsrv_query( $conn, $sql);

										if( !$stmt_emp_det ) {
											 $error_message = "Error selecting table (emp_mst)";
											 returnError($error_message);
											 die( print_r( sqlsrv_errors(), true));
										}
										
										$json =array();
										do {
											 while ($row = sqlsrv_fetch_array($stmt_emp_det, SQLSRV_FETCH_ASSOC)) {
												 
												$emp_mst_empl_id = $row['emp_mst_empl_id'];
												 
												$cleanRow = array_map(function($val) {
													if (is_string($val)) {
														// Normalize non-breaking space
														$val = str_replace("\xC2\xA0", ' ', $val);
														// Ensure UTF-8 (compatible in PHP 7.x and 8.x)
														$val = mb_convert_encoding($val, 'UTF-8', 'UTF-8');
													}
													return $val;
												}, $row);

												$json[] = $cleanRow;
											}
										} while ( sqlsrv_next_result($stmt_emp_det) );
										
										
										//tkn_mst to logout the previous session
										$sql_dft_mst = "SELECT dft_mst_mbl_single_login FROM dft_mst (NOLOCK) WHERE site_cd =?";
										$params_dft_mst = array($new_site_cd);
										$stmt_dft_mst = sqlsrv_query( $conn, $sql_dft_mst,$params_dft_mst);

										if( !$stmt_dft_mst ) {
											 $error_message = "Error selecting (sys_ver) ";
											 returnError($error_message);
											 die( print_r( sqlsrv_errors(), true));
											 
										}
										$dft_mst_mbl_single_login;
										do 	{
											 while ($row = sqlsrv_fetch_array($stmt_dft_mst, SQLSRV_FETCH_ASSOC)) {	
											 $dft_mst_mbl_single_login = $row['dft_mst_mbl_single_login'];
											
											}
										} while ( sqlsrv_next_result($stmt_dft_mst) );
										
										
										// Update tkn_mst to logout the previous session
										$sql_tkn_mst = "UPDATE 	tkn_mst 
														SET 	tkn_logout = GetDate(),
																tkn_online = '0'							
														WHERE 	tkn_site =?
														AND 	tkn_dvc_id = ? 
														AND 	tkn_user =?
														AND 	tkn_online = '1'";

										$params_tkn_mst = array($new_site_cd,$device_ID,$emp_mst_empl_id);
										$stmt_tkn_mst = sqlsrv_query($conn, $sql_tkn_mst, $params_tkn_mst);

										if (!$stmt_tkn_mst) {
											$error_message = "Error updating tkn_mst table: " . print_r(sqlsrv_errors(), true);
											sqlsrv_rollback($conn);
											returnError($error_message);
										}

										sqlsrv_free_stmt($stmt_tkn_mst);
										
										if($dft_mst_mbl_single_login === '1'){
	
											// Update tkn_mst to logout the previous session
											$sql_tkn_mst = "UPDATE 	tkn_mst 
															SET 	tkn_logout = GetDate(),
																	tkn_online = '0'							
															WHERE 	tkn_site =?
															AND		tkn_user =?";

											$params_tkn_mst = array($new_site_cd,$emp_mst_empl_id);
											$stmt_tkn_mst = sqlsrv_query($conn, $sql_tkn_mst, $params_tkn_mst);

											if (!$stmt_tkn_mst) {
												$error_message = "Error updating tkn_mst table: " . print_r(sqlsrv_errors(), true);
												sqlsrv_rollback($conn);
												returnError($error_message);
											}

											sqlsrv_free_stmt($stmt_tkn_mst);

										}
										
										
										// Insert new record into tkn_mst
										$sql_insert_tkn_mst = "INSERT INTO tkn_mst (	tkn_dvc_id, 	tkn_brand, 	tkn_model, 	tkn_token, 	tkn_user, 	tkn_site, 	tkn_login, 	tkn_logout, 	tkn_online,	tkn_mst_mobile_ver	) 
																			VALUES (	?, 				?, 			?, 			?, 			?, 			?, 			GetDate(), 	NULL, 			?,			?	)";

										$params_insert_tkn_mst = array($device_ID, $brand, $model, $token, $emp_mst_empl_id, $new_site_cd, $online,$version);
										$stmt_insert_tkn_mst = sqlsrv_query($conn, $sql_insert_tkn_mst, $params_insert_tkn_mst);

										if (!$stmt_insert_tkn_mst) {
											$error_message = "Error inserting into tkn_mst table: " . print_r(sqlsrv_errors(), true);
											sqlsrv_rollback($conn);
											returnError($error_message);
										}
										
										
									}else{
										returnError("You do not have permission to mobile access. \r\nPlease contact system administrator.");
									}
											
							}else{
								
								returnError("The Employee assigned to the User Login ID had deactivated.\r\nPlease contact the system administrator.");
							}
						
					}else{
						
						returnError("The User Login ID is not assign to any employee profile in this site.\r\nPlease contact the system administrator.");	
					}				
				
			}else{
				
				returnError("The User Login ID is not authorized to access into this site.\r\nPlease contact the system administrator.");					
			}
		
		}else{		
			
			returnError("Your login account has been locked for security reason\r\n(e.g you may have too many failed login attempts).\r\n\r\nPlease contact the system administrator.");		
		}
		
	}else{
		
		returnError("The User Login ID is not found .\r\nPlease contact the system administrator.");
		
	}	
	


if( $stmt_cf_user && $stmt_cf_site_user && $stmt_emp_mst && $stmt_emp_sts && $stmt_emp_det) {
		 sqlsrv_commit( $conn );
		 sqlsrv_close( $conn);	
		 returnData($json,$Defaultvalue);
	} else {
		 sqlsrv_rollback( $conn );
		 $error_message = "Transaction rolled back.<br />";
		 returnError($error_message);
	}

  

function returnData($json,$Defaultvalue){
	
	$returnData = array(
	'status' => 'SUCCESS',
	'message' => 'Login Successfully',
	'data' => $json,
	'Defaultvalue' => $Defaultvalue);	
	
	//echo file_put_contents("test.txt",$json);
	echo json_encode($returnData);	
}

function returnError($error_message){
	$json = array();
	
	$returnData = array(
	'status' => 'Error',
	'message' => $error_message,
	'data' => '');
	
	echo json_encode($returnData);	
	
	exit();
		
}

?>
