<?php
/**********************************************************************
***********************************************************************/

function add_user($user_id, $real_name, $password, $phone, $email, $role_id, 
	$language, $profile, $rep_popup, $pos)
{
	$id_user = $_SESSION['wa_current_user']->user;
	$datetime = date('Y-m-d H:i:s');
        
        $sql = "INSERT INTO ".TB_PREF."users (user_id, real_name, password"
		.", phone, email, role_id, language, pos, print_profile, rep_popup,created_by,created_on)
		VALUES (".db_escape($user_id).", 
		".db_escape($real_name).", ".db_escape($password) .",".db_escape($phone)
		.",".db_escape($email).", ".db_escape($role_id).", ".db_escape($language)
		.", ".db_escape($pos).",".db_escape($profile).",".db_escape($rep_popup)
		.", ".db_escape($id_user).", ".db_escape($datetime)." )";

	return db_query($sql, "could not add user for $user_id");
}

//-----------------------------------------------------------------------------------------------

function update_user_password($id, $user_id, $password)
{
	$id_user = $_SESSION['wa_current_user']->user;
	$datetime = date('Y-m-d H:i:s');

	$sql = "UPDATE ".TB_PREF."users SET password=".db_escape($password) . ",
		user_id = ".db_escape($user_id)
                .", updated_by=".db_escape($id_user)
                .", updated_on=".db_escape($datetime)
                . " WHERE id=".db_escape($id);

	return db_query($sql, "could not update user password for $user_id");
}

//-----------------------------------------------------------------------------------------------

function update_user($id, $user_id, $real_name, $phone, $email, $role_id, 
	$language, $profile, $rep_popup, $pos)
{
	$id_user = $_SESSION['wa_current_user']->user;
	$datetime = date('Y-m-d H:i:s');

	$sql = "UPDATE ".TB_PREF."users SET real_name=".db_escape($real_name).
	", phone=".db_escape($phone).",
		email=".db_escape($email).",
		role_id=".db_escape($role_id).",
		language=".db_escape($language).",
		print_profile=".db_escape($profile).",
		rep_popup=".db_escape($rep_popup).",
		pos=".db_escape($pos).",
		user_id = " . db_escape($user_id).",
                updated_by=".db_escape($id_user).",
                updated_on=".db_escape($datetime)
		. " WHERE id=" . db_escape($id);

	return db_query($sql, "could not update user for $user_id");
}

//-----------------------------------------------------------------------------------------------

function update_user_prefs($id, $prefs)
{
	$id_user = $_SESSION['wa_current_user']->user;
	$datetime = date('Y-m-d H:i:s');
        
        $sql = "UPDATE ".TB_PREF."users SET ";
	foreach($prefs as $name => $value) {
		$prefs[$name] = $name.'='. db_escape($value);
	}
        $prefs['updated_by'] = 'updated_by'.'='. db_escape($id_user);
	$prefs['updated_on'] = 'updated_on'.'='. db_escape($datetime);
        
	$sql .= implode(',', $prefs);
        
        $sql .=" WHERE id=".db_escape($id);

	return db_query($sql, "could not update user display prefs for $id");
}

//-----------------------------------------------------------------------------------------------


function get_users($all=false, $user_id=0, $name='', $role_id=-1, $employee_code=0, $id=0) {
    $sql = "SELECT u.*, r.role 
            FROM ".TB_PREF."users u, ".TB_PREF."security_roles r
            WHERE u.role_id = r.id";
	if (!$all){
            $sql .= " AND !u.inactive";
        }
	if ($user_id > 0){
            $sql .= " AND user_id = ".db_escape($user_id);
        }
	if (strlen($name) > 0) {
            $name = "%".$name."%";
            $sql .= " AND real_name LIKE ".db_escape($name);
        }
	if ($role_id > 0){
            $sql .= " AND role_id = ".db_escape($role_id);
        }
        if ($employee_code != 0 && $employee_code != '') {
            $sql .= " AND u.employee_code = ".db_escape($employee_code);
        }
        if ($id > 0) {
            $sql .= " AND u.id = ".db_escape($id);
        }
	
	return db_query($sql, "get_users");
}

//-----------------------------------------------------------------------------------------------

function get_user($id)
{
	$sql = "SELECT * FROM ".TB_PREF."users WHERE id=".db_escape($id);

	$result = db_query($sql, "could not get user $id");

	return db_fetch($result);
}

//-----------------------------------------------------------------------------------------------

function get_user_by_login($user_id)
{
	$sql = "SELECT * FROM ".TB_PREF."users WHERE user_id=".db_escape($user_id);

	$result = db_query($sql, "could not get user $user_id");

	return db_fetch($result);
}

//-----------------------------------------------------------------------------------------------

function get_user_by_email($email)
{
	$sql = "SELECT * FROM ".TB_PREF."users WHERE email=".db_escape($email);

	$result = db_query($sql, "could not get user for email $email");

	return db_fetch($result);
}

//-----------------------------------------------------------------------------------------------

function delete_user($id)
{
	$sql="DELETE FROM ".TB_PREF."users WHERE id=".db_escape($id);

	db_query($sql, "could not delete user $id");
}

//-----------------------------------------------------------------------------------------------
//
//	Obsolete, to be removed in 2.4. This function as been spleet into get_user_auth/get_user_by_login
//	in FA 2.3.6
//
function get_user_for_login($user_id, $password)
{
	set_global_connection();

// do not exclude inactive records or you lost access after source upgrade
// on sites using pre 2.2 database
	$sql = "SELECT * FROM ".TB_PREF."users WHERE user_id = ".db_escape($user_id)." AND"
		." password=".db_escape($password);

	return db_query($sql, "could not get validate user login for $user_id");
}

//-----------------------------------------------------------------------------------------------

function get_user_auth($user_id, $password)
{

	$sql = "SELECT * FROM ".TB_PREF."users WHERE user_id = ".db_escape($user_id)." AND"
		." password=".db_escape($password);

	return db_num_rows(db_query($sql, "could not get validate user login for $user_id")) != 0;
}

//-----------------------------------------------------------------------------------------------

function update_user_visitdate($user_id)
{
	$last_visit_date = date("Y-m-d H:i:s");
        
        $sql = "UPDATE ".TB_PREF."users SET last_visit_date='".$last_visit_date."'
        WHERE user_id=".db_escape($user_id);

	db_query($sql, "could not update last visit date for user $user_id");
        
        return $last_visit_date;
}

//-----------------------------------------------------------------------------------------------
function check_user_activity($id) 
{
	$sql = "SELECT COUNT(*) FROM ".TB_PREF."audit_trail WHERE audit_trail.user="
		. db_escape($id);
	$result = db_query($sql,"Cant check user activity");
	$ret = db_fetch($result);

	return $ret[0];
}

//-----------------------------------------------------------------------------------------------
function show_users_online()
{
//	global $show_users_online, $db, $GetText;
//	
//	if (!isset($show_users_online) || $show_users_online == 0 || !defined('TB_PREF') || 
    
        global $db, $GetText, $SysPrefs;

	if (!isset($SysPrefs->show_users_online) || $SysPrefs->show_users_online == 0 || !defined('TB_PREF') || 
		!isset($GetText) || !isset($db))
		return "";
	$result = db_query("SHOW TABLES LIKE '".TB_PREF."useronline'");	
	if (db_num_rows($result) == 1)
	{
		$timeoutseconds = 120;

		$timestamp=time();
		$timeout=$timestamp-$timeoutseconds;
		/*
		This will find out if user is from behind proxy server. 
		In that case, the script would count them all as 1 user.
		This function tryes to get real IP address.
		*/
		if (isset($_SERVER['HTTP_CLIENT_IP'])) {
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		}
		elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
			$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		}
		elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
			$ip = $_SERVER['HTTP_X_FORWARDED'];
		}
		elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
			$ip = $_SERVER['HTTP_FORWARDED_FOR'];
		}
		elseif (isset($_SERVER['HTTP_FORWARDED'])) {
			$ip = $_SERVER['HTTP_FORWARDED'];
		}
		else {
			$ip = $_SERVER['REMOTE_ADDR'];
		}

		// Add user to database
		db_query("INSERT INTO ".TB_PREF."useronline (timestamp, ip, file) VALUES ('". $timestamp ."',". db_escape($ip) .",". db_escape($_SERVER['PHP_SELF']) .")");
		//Remove users that were not online within $timeoutseconds.
		db_query("DELETE FROM ".TB_PREF."useronline WHERE timestamp<". $timeout);

		// Select online users
		$result = db_query("SELECT DISTINCT ip FROM ".TB_PREF."useronline");
		$users = db_num_rows($result);
	}
	else
		$users = 1;
	return "$users ".($users == 1 ? _("user online") : _("users online"));

}

function write_to_login_log($user_id, $remote_ip){
    
//    $id_user = $_SESSION['wa_current_user']->user;
    $date = date('Y-m-d');
    $time = date('H:i:s');
    
    $sql = "INSERT INTO ".TB_PREF."user_login_log (user_id, remote_ip, login_date, login_time )
            VALUES (".db_escape($user_id).", ".db_escape($remote_ip).", ".db_escape($date).", ".db_escape($time)." )";

    return db_query($sql, "write_to_login_log");
}

// can add more filters
function get_users_by_filters($id=0, $user_id=0, $employee_code=0, $fetch=false) {
    $sql = "SELECT * 
            FROM ".TB_PREF."users  
            WHERE 1 = 1 ";
    
        if ($id > 0) {
            $sql .= " AND id = ".db_escape($id);
        }
        if ($user_id > 0) {
            $sql .= " AND user_id = ".db_escape($user_id);
        }
        if ($employee_code != 0 || $employee_code == '') {
            $sql .= " AND employee_code = ".db_escape($employee_code);
        }
        
        $result = db_query($sql, "get_users_by_filters");
            if ($fetch === false) {
                return $result;
            } else {
                return db_fetch($result);
            }
}

function check_user_employee_duplication($id, $employee_code) {
    $sql = "SELECT * 
            FROM ".TB_PREF."users  
            WHERE employee_code = ".db_escape($employee_code)." 
                AND id <> ".db_escape($id);
    
        $result = db_query($sql, "check_user_employee_duplication");
        return db_fetch($result);
}

?>