<?php
ob_start();ob_flush();
ini_set('session.name', 'ADMPHPSESSID');
ini_set('session.g".TPLPrefix."maxlifetime',20*60*60);

session_set_cookie_params(20*60*60);
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;
$created=date('Y-m-d H:i:s');
define("SPC",mysql_real_escape_string);

//define('public1_url','http://'.$_SERVER['SERVER_NAME'].'/qhealth/');
//define('admin_public1_url', public1_url.'qhadmin/'); 

define('public1_url','http://'.$_SERVER['SERVER_NAME'].'/spacematrix/');
define('image_public1_url','http://'.$_SERVER['SERVER_NAME'].'/spacematrix/');
define('admin_public1_url', public1_url.'');
define('BASE_URL','http://'.$_SERVER['SERVER_NAME'].'/spacematrix/');
define('BASE_URL_ADMIN','http://'.$_SERVER['SERVER_NAME'].'/spacematrix/');
define('CAAROOTADMIN_DIR',realpath('./'));
define('CAAROOT_DIR','./');

$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 ".TPLPrefix."users where lower(user_email)='".strtolower($funame)."'";
 		$urslt=$db->get_a_line($mysqlfst);
	//print_r($db); die();
	
 		
		$pname=$urslt['user_pwd'];
	 	$mysqlsec="select * from ".TPLPrefix."users where lower(user_email)='".strtolower($funame)."' and user_pwd='".md5($fPass)."'";
		$prslt=$db->get_a_line($mysqlsec);
			
		$uname=trim($prslt['user_email']);
		
		
		
		if($pname=="" && $uname=="" )
		{
			//if(!isset($_REQUEST['frontlog']))
				header("Location:".admin_public1_url."index.php?err=invup");			
			/*else
			    echo '{"err":"1","msg":"Invalid Username or Password"}';			
			exit;*/
		} 
		elseif($pname=="" && $uname!="")
		{
			//if(!isset($_REQUEST['frontlog']))
			header("Location:".admin_public1_url."index.php?err=invu");
			/*else
			       echo '{"err":"1","msg":"Invalid Username"}'; 
			exit;*/
		}
		elseif($pname!="" && $uname=="")
		{
			
			//if(!isset($_REQUEST['frontlog']))
			header("Location:".admin_public1_url."index.php?err=invp");
			/*else
			  echo '{"err":"2","msg":"Invalid Password"}'; 
			exit;*/
		}
		
		elseif($pname!=$fPass && strtolower($uname)!=strtolower($funame))
		{
		//	if(!isset($_REQUEST['frontlog']))
			header("Location:".admin_public1_url."index.php?err=invp");
			/*else
			      echo '{"err":"3","msg":"Invalid Username or Password"}'; 	
			exit;*/
		}
		

		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 ".TPLPrefix."users s 			
			 inner join ".TPLPrefix."roles r on r.RoleId=s.RoleId and r.IsActive=1   where lower(s.user_email)='".strtolower($funame)."' and  s.user_pwd='".md5($fPass)."' and s.IsActive = '1' ";			 			 
			
		
			$rslt=$db->get_a_line($mysql);

	
			if($rslt[0]=="")
			{
				//if(!isset($_REQUEST['frontlog']))
			header("Location:".admin_public1_url."index.php?err=ac");
			
			/*else
			       echo '{"err":"4","msg":"Account Inactive"}'; 
			exit;	*/		
			
			}
			if($rslt[0]!="")
			{
				
				$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["StoreId"]=$rslt["StoreId"];
				
				
				

                $_SESSION["UserId"]=$userid;
				$_SESSION["IsActive"]=$rslt["IsActive"];
                                
				$id=$userid;
				
				$admin_id=$_SESSION["UserId"];							 				
				
				$_SESSION['TempRoleId'] = $rslt["RoleId"];
				$q="select * from ".TPLPrefix."user_session where user_id='$userid'";
				$r=$db->get_a_line($q);
				$last_export = $r[last_export];
				$hash=$this->hashgenwithsessionid();
				setcookie("admin",$hash,0,"/");
				$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 ".TPLPrefix."user_session where user_id='$userid'";
				
				$res=$db->get_a_line($str);
				
				
				$db->insert("insert into ".TPLPrefix."loginstatus (UsrId) VALUES('".$_SESSION['UserId']."')");
			 	$_SESSION['login_id'] = $db->insert_id;
					
					
				if($res['user_id']!="")
				{
				  
					$mysql="update ".TPLPrefix."user_session set hash='$hash',timestamp='$time',last_export='$last_export' where user_id='$userid'";
					$db->insert($mysql);
			
				
				} else {
				
					$mysql="insert into ".TPLPrefix."user_session (user_id, hash, timestamp, last_export) values('$userid','$hash','$time','$last_export')";
				
					$db->insert($mysql);
							
				}
			
				return $userid;	
			} else if($urslt=="" && $prslt=="") {
				header("Location:".admin_public1_url."index.php?err=invup");
				exit;
		    }
		}
		
	}
}

$obj=new Session;

if(isset( $_REQUEST['mn'] ) &&  $_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']);	
   $_SESSION['storeall'] = array("1","0");
  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 || $_SESSION["UserId"]=="" )
				{
				
				header("Location:".admin_public1_url."index.php?err=ses");
				exit;
				}
				else
				setcookie("admin",$hash,0,"/");
		$_SESSION['storeall'] = array("1","0");	
			
 	 }
	  else
	  {	 
	
			header("Location:".admin_public1_url."index.php?err=ses");
			exit;  
	  }

	
}

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

function getlogouturl($db){
	//$geturls = $db->get_a_line("select logouturl,StoreName from ".TPLPrefix."store where StoreId = '".$_SESSION["StoreId"]."'");	
	//return $geturls;
}

function getRealescape($data)
{	
	$escape = 	str_replace("'","\'",$data);
	return $escape;
}

function getMdme($db,$tabl=null,$col=null)
{
	 $str_mdl = "SELECT mmu.ModuleMenuId FROM `".TPLPrefix."modules` mdl inner join ".TPLPrefix."modulemenus mmu on mdl.ModuleId = mmu.ModuleId and  mmu.IsActive = 1 where mdl.ModulePath = '".$col."'  and mdl.IsActive = 1";
	
	return $db->get_a_line($str_mdl);
}

function getdynamicimage($db,$name){
			
	$getsiz = $db->get_rsltset("select concat(imageconfigWidth,'-',imageconfigHeight) as imagesize,foldername from ".TPLPrefix."imageconfig where IsActive = 1 and imageconfigModule = '$name'");
	
	foreach($getsiz as $sizval) {
		$sizes[] = $sizval['imagesize'];
		$associativeArray[$sizval['imagesize']] = $sizval['foldername'];
	}
	
	foreach($associativeArray as $k => $id){
		$aMemberships[$k] = $id;
	}
	
	return $aMemberships;
			
}

function getimagesize_large($db,$name,$fname){
			
	$getsiz = $db->get_a_line("select concat(imageconfigWidth,'-',imageconfigHeight) as imagesize,foldername from ".TPLPrefix."imageconfig where IsActive = 1 and foldername = '$fname' and imageconfigModule = '$name'");
	return $getsiz['imagesize'];
			
}
function searchkeyvalue($searchtext,$arrays,$fieldname="key",$returnvalue="value")
{
	
	 foreach ($arrays as $arr) {
		 
		   if (strtolower($arr[$fieldname])==strtolower($searchtext)) { 
				 return $arr[$returnvalue];
		}
		//die();
	 }
   return '';	
}

function searchkeyArray($searchtext,$arrays,$fieldname="key")
{
	 foreach ($arrays as $arr) {
		   if (strtolower($arr[$fieldname])==strtolower($searchtext)) { 
				 return $arr;
		}
		//die();
	 }
   return '';	
}
	
			
?>