<?php
ob_start();ob_flush();
error_reporting(0);
session_start();
include_once("include/config_db.php");
include_once("include/database.class.php");
include_once("include/common.class.php");

//include_once("QuerysContainer.php");
 
$db=new database;
$common=new common;
$path=$common->path;

define('SPC',mysql_real_escape_string);

if($_SERVER['HTTP_HOST']=="localhost:8080")
{
define('public_url','http://'.$_SERVER['SERVER_NAME'].':8080/hmsilks/');
define('admin_public_url', public_url.'hmadmin/');
define('BASE_URL','http://'.$_SERVER['SERVER_NAME'].':8080/hmsilks/');
}
else
{
define('public_url','http://'.$_SERVER['SERVER_NAME'].'/');
define('admin_public_url', public_url.'hmadmin/'); 
define('BASE_URL','http://'.$_SERVER['SERVER_NAME'].'/');
}

//common configuration - START
define('CAAROOT_DIR',realpath('../'));
define('CAAROOTADMIN_DIR',realpath('../hmadmin/'));

define('ROOT_DIR',realpath('../'));

//common configuration - END

$allow_role_ids = array("1","2");
$allow_user_ids = array();


class Session
{

	function hashgenwithsessionid()
	{
 		$hash = md5(session_id());
 		return $hash;
 	}

    function verifylogin($db,$common,$funame,$fPass)
	{		
		 
		$funame=addslashes($funame);		
		$fPass=addslashes($fPass);
		
        if(!empty($funame))
		$funame = str_replace("'", "", $funame);
		$funame = strtolower($funame);
		
		 $mysqlfst="select * from a_users where user_email='".strtolower($funame)."'";
	
		$urslt=$db->get_a_line($mysqlfst);
		$pname=$urslt['user_pwd'];
	 	$mysqlsec="select * from a_users where user_email='".strtolower($funame)."' and user_pwd='".md5($fPass)."'";

		$prslt=$db->get_a_line($mysqlsec);
		
			
		
		$uname=trim($prslt['user_email']);
		
		
		if($pname=="" && $uname=="" )
		{
			header("Location:".admin_public_url."index.php?err=invup");	
		} 
		elseif($pname=="" && $uname!="")
		{
			header("Location:".admin_public_url."index.php?err=invu");
		}
		elseif($pname!="" && $uname=="")
		{
			header("Location:".admin_public_url."index.php?err=invp");
		}
		
		elseif($pname!=$fPass && $uname!=$funame)
		{
		   header("Location:".admin_public_url."index.php?err=invp");
		}
		
		

		if($pname!="" && $uname!="")
		{
		 	$mysql="select distinct s.user_ID, s.user_firstname, s.user_name, s.user_pwd, s.user_email, s.RoleId, s.user_photo,  r.RoleName, s.IsActive from a_users s 			
			 inner join a_roles r on r.RoleId=s.RoleId where s.user_email='".strtolower($funame)."' and  s.user_pwd='".md5($fPass)."' and s.IsActive = '1' ";			 			 
			
			$rslt=$db->get_a_line($mysql);
		
			if($rslt=="")
			{
			  header("Location:".admin_public_url."index.php?err=ac");			
			}
			if($rslt!="")
			{
				
				$username=$rslt["user_email"];
				$password=$rslt["user_pwd"];
				$userid=$rslt["user_ID"];
				$_SESSION["RoleId"]=$rslt["RoleId"];
				$_SESSION["userPhoto"]=$rslt["user_photo"];
				$_SESSION["RoleName"]=$rslt["RoleName"];
				$_SESSION["UName"]=$rslt["user_firstname"];
				$_SESSION["UEmail"]=$rslt["user_email"];
				
                $_SESSION["UserId"]=$userid;
				$_SESSION["IsActive"]=$rslt["IsActive"];				
                                
				$id=$userid;
				
				$admin_id=$_SESSION["UserId"];							 				
				
				$_SESSION['TempRoleId'] = $rslt["RoleId"];
				$q="select * from a_user_session where user_id='$userid'";
				$r=$db->get_a_line($q);
				$last_export = $r[last_export];
				$hash=$this->hashgenwithsessionid();
				setcookie("admin",$hash,0,"/");
				
				//financial id set to session
				$get_fin_id = $db->get_a_line("select * from m_financial_year where IsActive=1 ");
				$_SESSION["Financial_id"]=$get_fin_id['financial_id'];

				$time=time();
				$str="select * from a_user_session where user_id='$userid'";
				$res=$db->get_a_line($str);
				if($res!="")
				{
				  
					$mysql="update a_user_session set hash='$hash',timestamp='$time',last_export='$last_export' where user_id='$userid'";
					$db->insert($mysql);
					$db= mysql_query("insert a_loginstatus set  UsrId='$userid'");
					$_SESSION['login_id'] = mysql_insert_id();
				
				} else {
				
					$mysql="insert into a_user_session values('$userid','$hash','$time','$last_export')";
					$db->insert($mysql);
					$db=mysql_query("insert a_loginstatus set  UsrId='$userid'");
					$_SESSION['login_id'] = mysql_insert_id();
					
				
				}
			
				return $userid;	
			} else if($urslt=="" && $prslt=="") {
				header("Location:".admin_public_url."index.php?err=invup");
				exit;
		    }
		}
		
	}
}

$obj=new Session;

if($_REQUEST['mn'] == 'fnt') {
	$_REQUEST['username'] = base64_decode($_REQUEST['username']);
	$_REQUEST['password'] = base64_decode($_REQUEST['password']);
}


if(trim($_REQUEST['submt']) == "login")
{

  $admin_id=$obj->verifylogin($db,$common,$_REQUEST['username'],$_REQUEST['password']);	
   
  if(isset($_REQUEST['frontlog']))
  {
 
	    echo '{"err":"0","msg":"sucess"}';   
       exit;
  }   
}
else
{
  $hash=$_COOKIE["admin"];
  $temphash=md5(session_id());

	if($temphash==$hash && count($_SESSION)>0)
	{
			 $admin_id=$common->check_user_session($hash,$db);
				if($admin_id=="" || $admin_id==0)
				{
				header("Location:".admin_public_url."index.php?err=ses");
				exit;
				}
				else
				setcookie("admin",$hash,0,"/");
 	 }
	  else
	  {	 
	 
			header("Location:".admin_public_url."index.php?err=ses");
			exit;  
	  }

	
}

function Logoutadmin($db)
{	
	$db->insert("update a_loginstatus  set Logout_time= CURRENT_TIMESTAMP() where UsrId ='".$_SESSION['UserId']."' and Id='".$_SESSION['login_id']."'");
		$mysql="delete from a_user_session where user_id='".$_SESSION['UserId']."'";
		$db->insert($mysql);
		return true;
}

function getRealescape($data)
{	
	$escape = 	mysql_real_escape_string($data);
	return $escape;
}

function getMdme($db,$tabl=null,$col=null)
{
	$str_mdl = "SELECT mmu.ModuleMenuId FROM `a_modules` mdl inner join a_modulemenus mmu on mdl.ModuleId = mmu.ModuleId where mdl.ModulePath = '".$col."' ";
	
	return $db->get_a_line($str_mdl);
}
        
//=====================================================================================			
?>