<?php
/**********************************************************************
    Copyright (C) FrontAccounting, LLC.
	Released under the terms of the GNU General Public License, GPL, 
	as published by the Free Software Foundation, either version 3 
	of the License, or (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
    See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
***********************************************************************/
$page_security = 'SA_USERS';
$path_to_root = "../../..";
include_once($path_to_root . "/includes/db_pager.inc");
include_once($path_to_root . "/includes/session.inc");

add_access_extensions();
page(_($help_context = "Users"));

include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/ui.inc");

include_once($path_to_root . "/admin/db/users_db.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/crm.inc" );

simple_page_mode(true);
//-------------------------------------------------------------------------------------------------
$kv_user_location = get_company_pref('kv_user_location');
function can_process($new) {

	if (strlen($_POST['user_id']) < 4)
	{
		display_error( _("The user login entered must be at least 4 characters long."));
		set_focus('user_id');
		return false;
	}

	if (!isset($_POST['selected_id']) && strlen($_POST['email']) < 5)
	{
		display_error( _("The user email entered must be right one."));
		set_focus('email');
		return false;
	}elseif (!isset($_POST['selected_id']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
	{
		display_error( _("The user email entered is invalid."));
		set_focus('email');
		return false;
	}elseif(!isset($_POST['selected_id']) && GetSingleValue('users', 'id', array('email' => $_POST['email']))){
		display_error( _("The user email Already Exists."));
		set_focus('email');
		return false;
	}
	if($new && strlen($_POST['password']) < 4){
		display_error( _("The password entered must be at least 4 characters long."));
		set_focus('password');
		return false;
	}
	if (!$new && ($_POST['password'] != ""))
	{
    	if (strlen($_POST['password']) < 4)
    	{
    		display_error( _("The password entered must be at least 4 characters long."));
			set_focus('password');
    		return false;
    	}

    	if (strstr($_POST['password'], $_POST['user_id']) != false)
    	{
    		display_error( _("The password cannot contain the user login."));
			set_focus('password');
    		return false;
    	}
	}

	return true;
}

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

if (($Mode=='ADD_ITEM' || $Mode=='UPDATE_ITEM') && check_csrf_token())
{

	if (can_process($Mode == 'ADD_ITEM'))
	{
    	if ($selected_id != -1) 
    	{
    		update_user_prefs($selected_id,
    			get_post(array('user_id', 'real_name', 'phone', 'email', 'role_id', 'language',
					'print_profile', 'rep_popup' => 0, 'pos')));

    		if ($_POST['password'] != ""){
    			update_user_password($selected_id, $_POST['user_id'], md5($_POST['password']));
    			$to =  array('name' => $_POST['real_name'], 'email' => $_POST['email']);
				$contact = array('real_name' => $_POST['real_name'], 'password' => $_POST['password'], 'email' => $_POST['email']);
				$template = array('slug' => 'staff-password-reseted',  'details' => $contact );
				kv_mail($to, '', '', "html", array(), null, false, $template);
    		}

    		display_notification_centered(_("The selected user has been updated."));
    	} 
    	else 
    	{
    		add_user($_POST['user_id'], $_POST['real_name'], md5($_POST['password']),
				$_POST['phone'], $_POST['email'], $_POST['role_id'], $_POST['language'],
				$_POST['print_profile'], check_value('rep_popup'), $_POST['pos']);
			$id = db_insert_id();
			// use current user display preferences as start point for new user
			$prefs = $_SESSION['wa_current_user']->prefs->get_all();
			
			update_user_prefs($id, array_merge($prefs, get_post(array('print_profile',
				'rep_popup' => 0, 'language'))));
			$to =  array('name' => $_POST['real_name'], 'email' => $_POST['email']);
			$contact = array('real_name' => $_POST['real_name'], 'password' => $_POST['password'], 'phone' => $_POST['phone'], 'email' => $_POST['email']);
			$template = array('slug' => 'new-staff-created',  'details' => $contact );
			kv_mail($to, '', '', "html", array(), null, false, $template);
			display_notification_centered(_("A new user has been added."));
    	}
		$Mode = 'RESET';
	}
}

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

if ($Mode == 'Delete' && check_csrf_token())
{
	$cancel_delete = 0;
    if (key_in_foreign_table($selected_id, 'audit_trail', 'user'))
    {
        $cancel_delete = 1;
        display_error(_("Cannot delete this user because entries are associated with this user."));
    }
    if ($cancel_delete == 0) 
    {
    	delete_user($selected_id);
    	display_notification_centered(_("User has been deleted."));
    } //end if Delete group
    $Mode = 'RESET';
}

//-------------------------------------------------------------------------------------------------
if ($Mode == 'RESET')
{
 	$selected_id = -1;
	$sav = get_post('show_inactive', null);
	$role_id = $_POST['access_level'];
	unset($_POST);	// clean all input fields
	$_POST['access_level'] = $role_id;
	$_POST['show_inactive'] = $sav;
}
function is_inactive($row){
	return $row["inactive"] == 1 ? true : false;
}
// inactive colm function----------------------
function status_($row){
	return ($row["inactive"] == 1 ? 'Inactive' : ($row['inactive'] == 0 ? 'Active' : ($row['inactive'] == 2 ? 'Yet To Activate' : 'Hold' )));
}

function edit_link($row){
  	return button("Edit".$row["id"],_("Edit"), '', ICON_EDIT);
}

function companies_or_pack($row){
  	return ($row['companies'] == 0 ? $row['role'] : $row['companies']);
}

function del_link($row) {
	
	if($row['user_id'] != 'kvcodes')
		return button("Delete".$row["id"],_("Delete"), '', ICON_DELETE);
	else
		return '';
}
function last_visit_date_($row){
	return sql2date($row["last_visit_date"]);
}

if(!isset($_POST['access_level'])){
	$_POST['access_level']=2;
}
if(list_updated('access_level')){
	$Ajax->activate('user_table');
}
$result = get_users(check_value('show_inactive'));
start_form();
div_start('user_table');
start_table(TABLESTYLE2);
security_roles_list_row(_("Select a Access Level:"), 'access_level', $_POST['access_level'],_("Select A Role"),true);
end_table(1);
$sql = "SELECT u.id,u.user_id,u.real_name,u.phone,u.email,u.last_visit_date,r.role,u.location, u.inactive FROM ".TB_PREF."users u INNER JOIN ".TB_PREF."security_roles r ON
		u.role_id=r.id WHERE 1=1";
if (isset($_POST['access_level']) && get_post('access_level') > 0) {
	$sql .= " AND u.role_id =".$_POST['access_level'];
}
if (!check_value('show_inactive')) {
	$sql .= " AND !u.inactive";
}

	$cols = array(
		_("id") => 'skip',
		_("User login") => array('name'=>'user_id'),
		_("Full Name") => array('name'=>'real_name'),
	    _("Phone") => array('name'=>'phone'),
	   	_("E-mail") => array('name'=>'email'),
	    _("Last Visit") => array('name' => 'last_visit_date', 'fun' => 'last_visit_date_'),
		_("Access Level") => array('name' => 'role'));

	if($kv_user_location)
		$cols[_("Location")] = array('name' => 'location');
		// $not_me = strcasecmp($myrow["user_id"], $_SESSION["wa_current_user"]->username);
	    $cols[_("Status")] = array('name'=>'inactive', 'fun' => 'status_');
	      // if ($not_me)
	   		$cols[_("Inactive")] = 'inactive';
	   	  // else
		$cols[] = array('insert'=>true, 'fun'=>'edit_link');
		$cols[] = array('insert'=>true, 'fun'=>'del_link');
	$table =& new_db_pager('info', $sql, $cols, 'users' );
	// display_error(json_encode($table));
	$table->set_inactive_ctrl('users', 'id');
	$table->width = "80%";
	display_db_pager($table);
	br();
//-------------------------------------------------------------------------------------------------
start_table(TABLESTYLE2);

$_POST['email'] = "";
if ($selected_id != -1) 
{
  	if ($Mode == 'Edit') {
		//editing an existing User
		$myrow = get_user($selected_id);

		$_POST['id'] = $myrow["id"];
		$_POST['user_id'] = $myrow["user_id"];
		$_POST['real_name'] = $myrow["real_name"];
		$_POST['phone'] = $myrow["phone"];
		$_POST['email'] = $myrow["email"];
		$_POST['role_id'] = $myrow["role_id"];
		$_POST['language'] = $myrow["language"];
		$_POST['print_profile'] = $myrow["print_profile"];
		$_POST['rep_popup'] = $myrow["rep_popup"];
		$_POST['pos'] = $myrow["pos"];
		if($kv_user_location)
			$_POST['location'] = (isset($myrow["location"]) ? $myrow["location"] : '');
	}
	hidden('selected_id', $selected_id);
	hidden('user_id');

	start_row();
	label_row(_("User login:"), $_POST['user_id']);
} 
else 
{ //end of if $selected_id only do the else when a new record is being entered
	text_row(_("User Login:"), "user_id",  null, 22, 20);
	$_POST['language'] = user_language();
	$_POST['print_profile'] = user_print_profile();
	$_POST['rep_popup'] = user_rep_popup();
	$_POST['pos'] = user_pos();
}
$_POST['password'] = "";
password_row(_("Password:"), 'password', $_POST['password']);

if ($selected_id != -1) 
{
	table_section_title(_("Enter a new password to change, leave empty to keep current."));
}

text_row_ex(_("Full Name").":", 'real_name',  50);

text_row_ex(_("Telephone No.:"), 'phone', 30);

email_row_ex(_("Email Address:"), 'email', 50);

security_roles_list_row(_("Access Level:"), 'role_id', null); 

languages_list_row(_("Language:"), 'language', null);

pos_list_row(_("User's POS"). ':', 'pos', null);

print_profiles_list_row(_("Printing profile"). ':', 'print_profile', null,	_('Browser printing support'));
if($kv_user_location)
	locations_list_cells(_("Location:"), 'location', null, true, true);
else 
	hidden('kv_user_location', '');
check_row(_("Use popup window for reports:"), 'rep_popup', $_POST['rep_popup'],	false, _('Set this option to on if your browser directly supports pdf files'));

end_table(1);

submit_add_or_update_center($selected_id == -1, '', 'both');
div_end();
end_form();
end_page();
