<?php
if(!isset($_SESSION)){
	session_start();
}


// preprint($_SESSION);
$USER_ID=!empty($_SESSION) && isset($_SESSION['user_id']) ? $_SESSION['user_id'] : '';
$STAFF_ID=!empty($_SESSION) && isset($_SESSION['staff_id']) ? $_SESSION['staff_id'] : '';
$CADRE_ID=!empty($_SESSION) && isset($_SESSION['cadre_id']) ? $_SESSION['cadre_id'] : '';
$PRIVILEGE=!empty($_SESSION) && isset($_SESSION['privilege']) ? $_SESSION['privilege'] : '';


$USERNAME=!empty($_SESSION['username']) ? $_SESSION['username'] : '';
$USER=!empty($_SESSION['fullname']) ? $_SESSION['fullname'] : '';

$V_ARR_TRIM = array_column($_SESSION['V_ARR'] ?? [], 'vendee_name', 'vendee_id');
// preprint($V_ARR_TRIM);

// preprint($S_ARR_TRIM);



function doLogin($usr, $pass, $switchSession=false, $change_pass=false){//user_parameters contains location_id, branch_id, etc)
	global $LINK, $PDO;
	mysqli_autocommit($LINK, FALSE);
	
	// echo 'branch in fnx:'.$branch_id;
	
		
		$hashlogin = doPDOQ(
			"SELECT *, login.auth AS auth
			FROM login 
			INNER JOIN (system_privileges, staff) ON (system_privileges.priv_id=login.priv_id AND staff.staff_id=login.staff_id) 
			WHERE username = :usr AND password = :pass AND status_id = 1", 
			array('usr'=>$usr, 'pass'=>sha1($pass))
		);
		
		$found = count($hashlogin);
	
		$hashlogin = $hashlogin[0] ?? [];
		// preprint($hashlogin);
		// exit;
		
		$super = ($hashlogin['priv_name']??'') == 'boss'  || ($hashlogin['priv_name']??'') == 'techno' || ($hashlogin['cadre_id']??'') == 1; 
		$out='';	
		if($found && empty($hashlogin['cadre_id'])){
			$out .= 'Error: Missing staff cadre information!';
			
		}elseif($found && empty($hashlogin['auth'])){
			$out .= 'Error: Your access is currently revoked!';
		
		}else{//theres cadre

			if(!$found){//no match
				$out .= 'No matching record<br />Please check your entry and the caps-lock, then try again';
			
			}elseif( SW('COUNT(*)', 'userlog', "login_id = {$hashlogin['login_id']} AND logoff IS NULL") ){//user logged in ...
				$out .= doForcedLogout($hashlogin['login_id'], 'Your previous session was not properly logged out.<br>Now, try again!');		
				
			}elseif($hashlogin['online_status'] && isset($_SESSION['user_id']) && $_SESSION['user_id'] == $hashlogin['login_id']){//user record reads 'ONLINE'
				$out = 1; 

			}else{//successful authentication, normal login OR switching session
			
				
				if(!$switchSession){
					doForcedLogout($hashlogin['login_id']);
				}					
				
				$rslogin=$hashlogin;
				if(!isset($_SESSION)){
					session_start();
				}elseif($switchSession){
					$session_id = session_id();
					session_write_close();
					session_id( md5( mt_rand() ) );
					session_start();
					$_SESSION['old_session_id'] = $session_id;
				}
				
								
				setcookie('doc_user',$rslogin['username'], time() + (3600*24*30) );
				
				
				$ip = REMOTE_ADDR;
				
				$qstatus=doQuery("UPDATE login SET online_status=1 WHERE login_id=".$rslogin['login_id']);
				$datalogs = [
					'log_id'=>NULL,
					'login_id'=>$rslogin['login_id'],
					'ip'=>$ip
				];
				
				
				// preprint($datalogs);
				$reslog = submitList($datalogs, 'userlog', '', ['log_id'], true);
                // preprint($reslog);
                // EXIT;
				
				if(!$reslog){
					$out .= 'Error loggin operation';
				}else{
					$newlog = mysqli_insert_id($LINK);
					mysqli_commit($LINK);
					
					$_SESSION['username']=$rslogin['username'];
					$_SESSION['priv_id']=$rslogin['priv_id'];
					$_SESSION['priv_rank']=$rslogin['priv_rank'];
					$_SESSION['privilege']=$rslogin['priv_name'];
					$_SESSION['fullname']=strtoupper($rslogin['lastname']).' '.$rslogin['firstname'];
					$_SESSION['user_id']=$rslogin['login_id'];
					$_SESSION['staff_id']=$rslogin['staff_id'];		
					$_SESSION['cadre_id']=$rslogin['cadre_id'];
					$_SESSION['staff_designation']=nl2br($rslogin['staff_designation']);

					$_SESSION['logon']=REQDATETIME;
					$_SESSION['client_addr']=$ip;
					$_SESSION['log_id']=$newlog;
					$_SESSION['welcome']=1;					
					$_SESSION['time'] = (SESSION_DURATION) ? time() : 0;

					$_SESSION['V_ARR'] = doPDOQ("SELECT * FROM survey_vendee WHERE vendee_id IN(SELECT vendee_id FROM staff_vendee_bridge WHERE staff_id = :sid)", ['sid'=>$rslogin['staff_id']]);

				}

			if($change_pass) {//successful authentication, change password
				$out .= 'change_pass';

			} else {	
				$out = 1;
			}
		}
	}
	
	if($out=='1') $newstaff=$hashlogin['staff_id'];
	else $newstaff='';
	
	$res = array('res'=>$out,'staff'=>$newstaff);
	
	return $switchSession ? $res : json_encode($res);
}


function LockOut($param=1){
	$color = $param == 1 ? 'green' : 'red';
	$l=SW('*','lock_info','_rowid='.$param, 1);
	// preprint($l);
	

	buildMsgPage(APP_NAME.' :: Temporarily Closed!', '<span class="'.$color.' underlined">'.APP_NAME.'<br /><span class="'.$color.'">'.$l['title'].'</span></span>', $l['msg'], 
	doLink('','','<strong class="smallcaps">Click here to try now</strong>',true).'<br />');
}

function denyAccess($msg="Your privileges do not permit access to the resource.", $return=false){
	$out = buildMsgPage2(	
		$msg, 
		APP_NAME.' :: Access denied!', 
		$msg, 
		doLink('faq.php','','See the FAQ',true).'<br />'.doLink(BACK,'','Go back',''),
		$return
	);
	if($return) return $out;
}


function restrictAccess($restrict=true){
	global $restrarr;
	if($restrict){
		denyAccess("Access restricted on account of {$restrarr['lock_reason']}");
	}
}


if(isset($_GET['doLogout'])){
	if(!empty($_GET['fdologout'])){
		
		$theid=sanitizeData($_GET['theid']);
	//	echo $theid;exit;
		//update logs
		$qlog=doQuery('UPDATE userlog SET logoff=\''.date('Y-m-d H:i:s').'\' WHERE login_id='.$theid.' AND logoff IS NULL');
		//update online status
		$qstatus=doQuery('UPDATE login SET online_status = 0 WHERE login_id='.$theid);
		if(isset($_GET['force'])){
			header('Location:'.PAGE_THIS);
			if($qlog['affected'] && $qstatus['affected']){
				$userarr = SW('staff_id, username', 'login', 'login_id='.$theid, 1);
				$msg = doMessage('The user <b>'.$userarr['username'].'</b> was successfully foreced out.');
				$msg .= doAlert('You may need to also '.doLink(APP_ROOT.'staff_reg_page.php', 'getPagenum&loc_fld=staff_id&loc_val='.$userarr['staff_id'].'&openstatus=1', 'UPDATE BIODATA', '').' and/or '.doLink(APP_ROOT.'staff_process.php', 'revoke='.$theid, 'REVOKE RIGHTS', '').' now, if required');
				loadMsg('done', $msg);
			}
		}else{
			header('Location: '.APP_ROOT.PAGE_LOGIN);
		}

		exit;

	}elseif(!empty($STAFF_ID)){
		
		doLogout(0);
	}else{
        echo 'NO SESSION';
        EXIT;
		header('Location: '.APP_ROOT.PAGE_LOGIN);
		exit;
	}
}else{
	//refresh latency time
	//doQuery("UPDATE login SET last_act = NOW() WHERE login_id = {$USER_ID}");
}

function accessCheck($validarray=''){
//preprint($_SESSION);
	if(!empty($_GET['pdf']) && !isEmptyArray($_SESSION)) return true;

	global $STAFF_ID;
	
	$validlogins=SAW('priv_name','system_privileges',1);
	if(!empty($_SESSION)){
		
		// preprint($_SESSION);

		if(!$validarray) $validarray=$validlogins;
		// $online = !empty($_SESSION['log_id']) ? ($_SESSION['privilege']=='guest' ? 1 : SW('COUNT(*)','userlog','log_id='.$_SESSION['log_id'].' AND logoff IS NULL')) : false;

		// $online = !empty($_SESSION['log_id']) ? (1 ? 1 : SW('COUNT(*)','userlog','log_id='.$_SESSION['log_id'].' AND logoff IS NULL')) : false;
		$online = !empty($_SESSION['log_id']) && (SW('COUNT(*)','userlog','log_id='.$_SESSION['log_id'].' AND logoff IS NULL') || true);
							
		if($online){
			if(!in_array($_SESSION['privilege'],$validarray)){
				include(URL_PREF.'includes/topbar.php');
				denyAccess();
			}
			//We have access
		}else{//must have logged out from another browser instance
	
		//preprint($_SESSION);
			buildMsgPage(
			APP_NAME.' :: Improper Session End!',
			'<span class="red">'.APP_NAME.' :: Forced Logout!</span>', 
			'Your system session was interrupted from another location',
			doLink(APP_ROOT.'display/login.php','clearsession=1','Click here to log in again',array(true,'class="bold smallcaps"')).'
			<p class="smaller faint">(Still cannot log in? Try closing, then reopening the entire browser window)</p>' 
			);

		}
	} else {//no session
        header("Location: ".APP_ROOT."display/login.php");
	}
}

function accessCheck2($validarray=array('boss','user','sys_admin')){
	if(!empty($_SESSION)){
		if(!in_array($_SESSION['privilege'],$validarray)){
			denyAccess();
		}
	} else {//no session
		// buildMsgPage(' :: Login required!', ' :: Login required!', 'A login is required to view the page.', doLink(APP_ROOT.'display/login.php','','Click here to log in',true));
	}
}

function doLogout($return){
	global $STAFF_ID;
	//removeDir(URL_PREF.'tempo/_'.$STAFF_ID, '');
	
	if(!empty($_SESSION['user_id'])){
		$qlog=doQuery('UPDATE userlog SET logoff=\''.date('Y-m-d H:i:s').'\' WHERE login_id='.$_SESSION['user_id']);
		//update online status
		$qstatus=doQuery('UPDATE login SET online_status = 0 WHERE login_id='.$_SESSION['user_id']);
	}
	
	
	session_destroy();
	//preprint($_SESSION);
	//echo 'Just destorryed';
	//exit;
	
	header('Location: '.APP_ROOT.'display/login.php');
	exit;
}


//DEPR
function doForcedLogout($login_id,$reason=''){//login.login id is unique, login.staff_id isn't
	//the below 2 lines transferred from above
	global $LINK;
	
	mysqli_autocommit($LINK, FALSE);
	$qlog=doQuery('UPDATE userlog SET logoff=\''.REQDATETIME.'\' WHERE login_id='.$login_id.' AND logoff IS NULL');
	$qstatus=doQuery('UPDATE login SET online_status = 0 WHERE login_id='.$login_id);
	mysqli_commit($LINK);
	return $reason;//this should stop execution right here
	
}	



?>