<?php 
include_once ("includes/setup_pemohon.inc.php");
$dateTimeNow = dateTimeNow();

$username = fetch_postget_val('username',$_POST, $_GET);
$password = fetch_postget_val('password',$_POST, $_GET);

$status = 0;
$errorMsg = "";
$redirect = "";

$Query = "SELECT id_pemohon AS id, id_pemohonsys AS id_sys, id_peranan AS role, login, nama AS user_name, emel, temp_pwd, aktif, status_blok, masaakhiraktif, masaakhirlogout
			  FROM $MY_TB_NAME
			  WHERE login = ? AND katalaluan = ?";

$PDO_stmt = $PDO->prepare($Query);
$PDO_stmt->bindValue(1, $username, PDO::PARAM_STR);
$PDO_stmt->bindValue(2, md5($password), PDO::PARAM_STR);
$rstUser = $PDO_stmt->execute();
if (!$rstUser) {
	$status = -1;
	$errorMsg = $PDO_stmt->errorInfo();
}
$detail_list = $PDO_stmt->fetch(PDO::FETCH_ASSOC);
$Num = $PDO_stmt->rowCount();


if($Num > 0)
{
	if($detail_list['status_block'] == 1) //telah diblok
	{
		$status = -1;
		$errorMsg = 'Akaun anda telah disekat, sila hubungi pihak pentadbir untuk membuka semula akaun anda.';
	}
	else if($detail_list['aktif'] == 2 || $detail_list['aktif'] == 3) //tak aktif
	{
		$status = -1;
		$errorMsg = 'Akaun anda tidak aktif/dibatalkan, sila hubungi pihak pentadbir untuk aktifkan semula akaun anda.';
	}
	else if($detail_list['aktif'] == 4)
	{
		$status = -1;
		$errorMsg = 'Akaun anda sedang menunggu pengesahan.';
	}
	else //allow login
	{
		$auth->new_session(14400, $_SERVER['REMOTE_ADDR']);
		$authen_usr = new SYSUser();
		$detail_list['index'] = 'index_pemohon.php';
		$detail_list['logout'] = 'logout_pemohon.php';
		$detail_list['profile'] = 'profile_pemohon.php';
		$detail_list['password'] = 'profile_pemohon.php';
		$detail_list['profile_img'] = file_exists("profile_photo/".$detail_list['id']."/profile.jpg")?("profile_photo/".$detail_list['id']."/profile.jpg"):("profile_photo/profile-default.jpg");
		
		$authen_usr->setVars($detail_list);	
		$_SESSION[$MY_SESSION_NAME] = $authen_usr;

		try
		{
			$PDO->beginTransaction();
			
			$PASS_VALUE = 0;
			$pengguna_Array = array();
			$pengguna_Array[] = array('masaakhirlogin', $dateTimeNow, PDO::PARAM_STR);
			$pengguna_Array[] = array('bil_percubaan', 0, PDO::PARAM_INT);
			$whereCondition = "WHERE id_pemohon = ".$detail_list['id'];
			$PASS_VALUE += 1;
			$PASS_COUNTER += PDO_UPDATE($PDO, $MY_TB_NAME, $pengguna_Array, $whereCondition);
		
			$loginLog_Array = array();
			$loginLog_Array[] = array('id_pengguna', $detail_list['id'], PDO::PARAM_INT);
			$loginLog_Array[] = array('id_peranan', $detail_list['role'], PDO::PARAM_INT);
			$loginLog_Array[] = array('status_login', 'B', PDO::PARAM_STR);
			$loginLog_Array[] = array('jenis_log', 'I', PDO::PARAM_STR);
			$loginLog_Array[] = array('bil_percubaan', 0, PDO::PARAM_INT);
			$loginLog_Array[] = array('tkh_log', $dateTimeNow, PDO::PARAM_STR);
			$loginLog_Array[] = array('ip_address', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
			$PASS_VALUE += 1;
			$PASS_COUNTER += PDO_INSERT($PDO, 's_loginlog', $loginLog_Array);
				
			//*****************************************
			//COMMIT if PASS_COUNTER == PASS_VALUE 
			//*****************************************
			if ($PASS_COUNTER == $PASS_VALUE)
			{
				$PDO->commit();
				if($detail_list['temp_pwd'] == 1) //force reset password
				{
					$status = 1;
					$redirect = "profile_pemohon.php";
				}
				else
				{
					$status = 1;
					$redirect = "index_pemohon.php";
				}
				
			}
			else
			{
				$PDO->rollBack();
				$status = -1;
				$errorMsg = 'Gagal untuk login, sila semak talian internet anda';
			}
		}
		catch (Exception $e) 
		{
			$PDO->rollBack();
			$status = -1;
			$errorMsg = "Failed: " . $e->getMessage();
		}
	}
}
else
{
	$Query = "SELECT id_pemohon, bil_percubaan, id_peranan
			  FROM $MY_TB_NAME
			  WHERE login = ?";
	
	$PDO_stmt = $PDO->prepare($Query);
	$PDO_stmt->bindValue(1, $username, PDO::PARAM_STR);
	$rstUser = $PDO_stmt->execute();
	if (!$rstUser) {
		$status = -1;
		$errorMsg = $PDO_stmt->errorInfo();
	}
	$detail_list2 = $PDO_stmt->fetch(PDO::FETCH_ASSOC);
	
	if($detail_list2['id_pemohon']) //user exist
	{
		if($detail_list2['bil_percubaan'] + 1 >= 3)
		{
			$status = -1;
			$errorMsg = 'Akaun anda telah disekat, sila hubungi pihak pentadbir untuk membuka semula akaun anda.';
		}
		else
		{
			//update cubaan
			try
			{
				$PDO->beginTransaction();
				
				$Query = "UPDATE $MY_TB_NAME SET bil_percubaan = ?, status_blok = ?
					  WHERE id_pemohon = ? ";
		
				$PDO_stmt = $PDO->prepare($Query);
				$PDO_stmt->bindValue(1, $detail_list2['bil_percubaan'] + 1, PDO::PARAM_INT);
				$PDO_stmt->bindValue(2, ($detail_list2['bil_percubaan'] + 1 >= 3)?1:0, PDO::PARAM_INT);
				$PDO_stmt->bindValue(3, $detail_list2['id_pemohon'], PDO::PARAM_INT);
				$PASS_COUNTER = $PDO_stmt->execute();
				
				$loginLog_Array = array();
				$loginLog_Array[] = array('id_pengguna', $detail_list2['id_pemohon'], PDO::PARAM_INT);
				$loginLog_Array[] = array('id_peranan', $detail_list2['id_peranan'], PDO::PARAM_INT);
				$loginLog_Array[] = array('status_login', 'G', PDO::PARAM_STR);
				$loginLog_Array[] = array('jenis_log', 'I', PDO::PARAM_STR);
				$loginLog_Array[] = array('bil_percubaan', $detail_list2['bil_percubaan'] + 1, PDO::PARAM_INT);
				$loginLog_Array[] = array('tkh_log', $dateTimeNow, PDO::PARAM_STR);
				$loginLog_Array[] = array('ip_address', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
				
				$PASS_COUNTER += PDO_INSERT($PDO, 's_loginlog', $loginLog_Array);
				
				//*****************************************
				//COMMIT if PASS_COUNTER == PASS_VALUE
				//*****************************************
				if ($PASS_COUNTER == 2)
				{
					$PDO->commit();
					$status = -1;
					if($detail_list2['bil_percubaan'] + 1 >= 3)
					{
						$errorMsg = 'Kata laluan tidak tepat dan akaun telah disekat. Sila hubungi pihak pentadbir untuk membuka semula akaun anda.';
					}
					else
					{
						$errorMsg = 'Kata laluan tidak tepat, sila cuba sekali lagi. '.(3 - ($detail_list2['bil_percubaan'] + 1)).' cubaan lagi sebelum akaun disekat';
					}
				}
				else
				{
					$PDO->rollBack();
					$status = -1;
					$errorMsg = 'Gagal untuk login, sila semak talian internet anda';
				}
			}
			catch (Exception $e) 
			{
				$PDO->rollBack();
				$status = -1;
				$errorMsg = "Failed: " . $e->getMessage();
			}
		}
	}
	else
	{
		$status = -1;
		$errorMsg = 'Pengguna tidak wujud, sila cuba sekali lagi';
	}
}

$return_result = [];
$return_result['status'] = $status;
$return_result['errorMsg'] = $errorMsg;
$return_result['redirect'] = $redirect;

echo json_encode($return_result);
?>
