<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_USERS';
$path_to_root = "..";
include_once($path_to_root . "/includes/session.inc");

$js = "";
if ($SysPrefs->use_popup_windows)
	$js .= get_js_open_window(800, 500);
if (user_use_date_picker())
	$js .= get_js_date_picker();

page(_($help_context = "Users"), @$_REQUEST['popup'], false, "", $js);

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 . "/includes/ui/ui_lists_group_companies.inc");
include_once($path_to_root . "/includes/db/group_companies_db.inc");

//simple_page_mode(true);

if (isset($_GET['id'])) 
{
	$_POST['id'] = $_GET['id'];
}
$user_id = get_post('id'); 

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

function can_process() 
{

	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;
	}
        
        $user = get_user_by_login($_POST['user_id']);
        if(isset($user['id']) && $user['id'] > 0 && !($_POST['id'] > 0))
	{
		display_error( _("Entered user login already exisits."));
		set_focus('user_id');
		return false;
	}
        
        if(isset($_POST['company_code']) && strlen($_POST['company_code']) > 0)
	{
            if(!(isset($_POST['employee_code']) && strlen($_POST['employee_code']) > 2))
            {
                    display_error( _("Please select an employee."));
                    set_focus('employee_code');
                    return false;
            }
        }
        else{
            $_POST['employee_code'] = '';
        }

        
	if ($_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;
}


function display_edit_controls($selected_id)
{
//return;
//    $selected_id = get_post('user_id');
    
    start_table(TABLESTYLE2);

    $_POST['email'] = "";
    if ($selected_id > 0) 
    {

                    //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"];
                    $_POST['inactive'] = $myrow["inactive"];
                    $_POST['ot_approver'] = $myrow["ot_approver"];
                    $_POST['available_budget'] = $myrow["available_budget"];
                    
                    if (list_updated('id')) {
                        $_POST['company_code'] = $myrow["company_code"];
                    }
                    
                    if(!isset($_POST['company_code'])){
                        $_POST['company_code'] = $myrow["company_code"];
                    }
                    $_POST['employee_code'] = $myrow["employee_code"];
                    $_POST['last_visit_date'] = $myrow["last_visit_date"];             
            
            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 > 0) 
    {
            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'));

    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'));

//    amount_row('PO Approval Limit:', 'po_approval_limit');

    group_companies_list_row("Company:", 'company_code', null, 'Select a company', true);
    if(!(strlen($_POST['company_code']) > 0)){
        $_POST['company_code'] = '';
    }
    group_company_employees_simple_list_row("Employee", 'employee_code', $_POST['company_code'], null, "Select an employee");
    
    yesno_list_row("Over Time Approver:", 'ot_approver', null, "Yes", "No");
    check_row(_("View Budget Available Value:"), 'available_budget');

    if ($selected_id > 0){
	record_status_list_row(_("Inactive:"), 'inactive');
        label_row("Last Login Time:", $_POST['last_visit_date']);
    }
    end_table(1);

}


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

if ((isset($_POST['ADD_ITEM']) || isset($_POST['UPDATE_ITEM'])) && check_csrf_token())
{

	if (can_process())
	{
            $_POST['po_approval_limit'] = input_num('po_approval_limit');
            $_POST['available_budget'] = input_num('available_budget');
            $_POST['def_print_orientation'] = input_num('def_print_orientation');
            $_POST['ot_approver'] = input_num('ot_approver');
            
            $selected_id = $_POST['id'];
            
            if ($selected_id > 0) 
            {
                update_user_prefs($selected_id,
                        get_post(array('user_id', 'real_name', 'phone', 'email', 'role_id', 'language',
                                        'print_profile', 'rep_popup' => 0, 'pos',
                                        'company_code', 'employee_code',
                                        'inactive' , 'ot_approver', 'available_budget')));

                if ($_POST['password'] != ""){
                        update_user_password($selected_id, $_POST['user_id'], md5($_POST['password']));
                }

                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', 
                        'company_code', 'employee_code','ot_approver', 'available_budget'))));

                display_notification_centered(_("A new user has been added."));
            }
	}
}

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

//if ($Mode == 'Delete' && check_csrf_token())
//{
//	delete_user($selected_id);
//	display_notification_centered(_("User has been deleted."));
//	$Mode = 'RESET';
//}

//-------------------------------------------------------------------------------------------------
//if ($Mode == 'RESET')
//{
// 	$selected_id = -1;
//	$sav = get_post('show_inactive');
//	unset($_POST);	// clean all input fields
//	$_POST['show_inactive'] = $sav;
//}


start_form();
/**
$result = get_users(check_value('show_inactive'));

start_table(TABLESTYLE);

$th = array(_("User login"), _("Full Name"), _("Phone"),
                _("E-mail"), _("Last Visit"), _("Access Level"),
                _("PO Approval Limit"), _("OT Approver"),"", "");

inactive_control_column($th);
table_header($th);	

$k = 0; //row colour counter

while ($myrow = db_fetch($result)) 
{

	alt_table_row_color($k);

	$last_visit_date = sql2date($myrow["last_visit_date"]);

	//The security_headings array is defined in config.php 
	$not_me = strcasecmp($myrow["user_id"], $_SESSION["wa_current_user"]->username);

	label_cell($myrow["user_id"]);
	label_cell($myrow["real_name"]);
	label_cell($myrow["phone"]);
	email_cell($myrow["email"]);
	label_cell($last_visit_date, "nowrap");
	label_cell($myrow["role"]);
        qty_cell($myrow["po_approval_limit"]);
        label_cell(($myrow["ot_approver"] == "1" ? "Yes" : "No"), "align=center");	
	
    if ($not_me)
		inactive_control_cell($myrow["id"], $myrow["inactive"], 'users', 'id');
	elseif (check_value('show_inactive'))
		label_cell('');

	edit_button_cell("Edit".$myrow["id"], _("Edit"));
    if ($not_me)
 		delete_button_cell("Delete".$myrow["id"], _("Delete"));
	else
		label_cell('');
	end_row();

} //END WHILE LIST LOOP

inactive_control_row($th);
end_table(1);
 * */
 
//-------------------------------------------------------------------------------------------------

//if (!(isset($_POST['user_id']) && $_POST['user_id'] > 0)){
//	$_POST['user_id'] = get_global_user_id();
//}

global $Ajax;
$Ajax->activate('user_list_id');

div_start('user_list_id');
start_table(false, "", 3);
//	start_table(TABLESTYLE_NOBORDER);
    start_row();
    user_list_cells(_("Select a user: "), 'id', null,
              _('New User'), true, check_value('show_inactive'));

    check_cells(_("Show inactive:"), 'show_inactive', null, true);
    end_row();
end_table();
div_end();


if (list_updated('company_code')) {
        $Ajax->activate('employee_code');
}


display_edit_controls($_POST['id']);

submit_add_or_update_center(!($_POST['id'] > 0), '', 'both');

end_form();
end_page();
?>
