<?php
require_once(dirname(__FILE__) . '/../includes/base.inc.php');

route_request();
function route_request() {

    $pageopt = get_pageopt();

    if ($pageopt == 'update') {
        
        $reload = update_preferences();

        if ($reload)
            reload_page('/account/');
    }

    edit_preferences();
}

function update_preferences()
{

    // no changes in demo
    demo_error('edit_preferences');
    
    $reload = false;

    check_nagios_session_protector();

    $cancel = grab_request_var('cancel', false);
    if ($cancel !== false)
        return;

    $password1 = encode_html(grab_request_var('password1', ''));
    $password2 = encode_html(grab_request_var('password2', ''));

    $current_name = get_user_attr('name');
    $name = encode_html(grab_request_var('name', $current_name));

    $current_email = get_user_attr('email');
    $email = encode_html(grab_request_var('email', $current_email));

    $language = get_option('default_language', 'en_US');
    $current_language = get_user_meta('language', $language);
    $language = encode_html(grab_request_var('language', $language));

    $date_format = get_option('default_date_format', DF_ISO8601);
    $current_date_format = get_user_meta('date_format', $date_format);
    $date_format = encode_html(grab_request_var('date_format', $date_format));

    $number_format = get_option('default_number_format', NF_2);
    $current_number_format = get_user_meta('number_format', $number_format);
    $number_format = encode_html(grab_request_var('number_format', $number_format));

    $timezone = get_current_timezone();
    $current_timezone = get_user_meta('timezone', $timezone);
    $timezone = grab_request_var('timezone', $timezone);
    
    $theme = grab_request_var("theme", get_theme());
    $current_theme = get_user_meta('theme', $theme);

    $auto_login_username = grab_request_var('auto_login_username');
    $auto_login_password = grab_request_var('auto_login_password');
    $auto_login_enabled = grab_request_var('auto_login_enabled');

    $errmsg = '';
    if ($password1 != $password2)
        $errmsg .= _('Password fields must match.') . '<br>';
    if (empty($name))
        $errmsg .= _('Username cannot be left blank.') . '<br>';
    if (empty($email))
        $errmsg .= _('Email address cannot be left blank.') . '<br>';

    if (!empty($errmsg)) {
        flash_message($errmsg, 'error');
        return $reload;
    }

    if (!empty($password1) && $password1 == $password2) {
        set_user_attr('password', hash('sha256', $password1));
        set_user_attr('password_set_time', date("Y-m-d H:i:s", time()), $user_id);
    }

    if ($current_name != $name)
        set_user_attr('name', $name);

    if ($current_email != $email)
        set_user_attr('email', $email);

    unset($_SESSION['session_lang']);
    set_user_meta('language', $language, false);
    set_language($language);
    $reload = true;

    if ($current_date_format != $date_format)
        set_user_meta('date_format', $date_format, false);

    if ($current_number_format != $number_format)
        set_user_meta('number_format', $number_format, false);

    if ($current_timezone != $timezone && is_valid_timezone($timezone)) 
        set_user_meta('timezone', $timezone, false);
    
    
    $old_theme = get_user_meta('theme', NULL, $_SESSION["user_id"]);
    if ($current_theme != $theme) 
        set_user_meta('theme', $theme, false);
    
    if ($old_theme != $theme) {
        $_SESSION['reset_frame'] = 1;
        flash_message(_('Account settings updated. (Screen may flash once while UI theme changes)'));
    }
    
    // update any auto login info
    if (is_array($auto_login_username)) {
        foreach ($auto_login_username as $server_id => $username) {

            if (!empty($username)) {

                $enabled = !empty($auto_login_enabled[$server_id]);
                if (get_auto_login_enabled($server_id) != $enabled) {
                    $reload = true;
                }

                set_auto_login_enabled($server_id, $enabled);

                $password = null;

                if (isset($auto_login_password[$server_id]))
                    $password = $auto_login_password[$server_id];

                if ($password == 'password_set')
                    continue;

                if ($password !== null)
                    set_auto_login($server_id, $username, $password, 0, $enabled);

                $reload = true;

            } else {

                // if they submit an empty one, remove it
                delete_auto_login($server_id);
                set_auto_login_enabled($server_id, $enabled = false);
                $reload = true;

            }
        }
    }

    flash_message(_('Account Updated!'));
    return $reload;
}

function edit_preferences() {
    $reset = 0;
    if (array_key_exists('reset_frame', $_SESSION)) {
        $reset = $_SESSION['reset_frame'];
        unset($_SESSION['reset_frame']);
    }
    
    $page_title = _('Account Information');
    child_page($page_title);

    $name = get_user_attr('name');
    $email = get_user_attr('email');
    $api_key = get_user_attr('api_key');

    $language = get_option('default_language', 'en_US');
    $language = get_user_meta('language', $language);

    $date_format = get_option('default_date_format', DF_ISO8601);
    $date_format = get_user_meta('date_format', $date_format);

    $number_format = get_option('default_number_format', NF_2);
    $number_format = get_user_meta('number_format', $number_format);

    get_timezones_and_selected($timezones, $timezone);
    $timezone = get_user_meta('timezone', $timezone);
    
    get_themes_and_selected($themes, $theme);
    $theme = get_user_meta('theme', $theme);

    echo well_top_page_header($page_title);
    
    if ($reset) {
        // Flash the next flash message
        flash_message(_('Account settings updated.'));
    }
    ?>
<script>
    <?php if ($reset) { ?>
        window.parent.location.href="<?php echo get_base_url(); ?>account/";
    <?php } ?>
</script>
<form method="post"  action="?update"  class="formbuilder" >
    <div class="formbuilder-div formbuilder" >
        <h5 class="ul" >
            <?php echo _('General Account Settings'); ?>
        </h5>
        <table class="formbuilder-table formbuilder" >
            <tr>
                <td>
                    <label for="password1" >
                        <?php echo _('New Password'); ?>:
                    </label>
                </td>
                <td>
                    <input name="password1"  type="password"  id="password1"  class="form-control textfield"  />
                </td>
            </tr>
            <tr>
                <td>
                    <label for="password2" >
                        <?php echo _('Repeat New Password'); ?>:
                    </label>
                </td>
                <td>
                    <input name="password2"  type="password"  id="password2"  class="form-control textfield"  />
                </td>
            </tr>
            <tr>
                <td>
                    <label for="name" >
                        <?php echo _('Name'); ?>:
                    </label>
                </td>
                <td>
                    <input name="name"  value="<?php echo $name; ?>"  type="text"  id="name"  class="form-control textfield" required="true" />
                </td>
            </tr>
            <tr>
                <td>
                    <label for="email" >
                        <?php echo _('Email Address'); ?>:
                    </label>
                </td>
                <td>
                    <input name="email"  value="<?php echo $email; ?>"  type="email"  id="email"  class="form-control textfield" required="true" />
                </td>
            </tr>

            <?php if(get_user_attr('api_enabled') || is_admin()): ?>
            <tr>
                <td>
                    <label for="api_key" >
                        <?php echo _('API Key'); ?>:
                    </label>
                </td>
                <td>
                    <input name="api_key" style="cursor: pointer;" onclick="this.select();" value="<?php echo $api_key; ?>"  type="text"  id="api_key"  class="form-control textfield" readonly />
                </td>
            </tr>
                <?php if (is_admin()): ?>
                <tr>    
                    <td></td>
                    <td>
                        <button type="button" onclick="generate_new_api_key();" class="btn btn-xs btn-default"><?php echo _('Generate new API key'); ?></button>
                    </td>
                </tr>
                <?php endif;?>
            <?php endif; ?>
        </table>
    </div>

    <script type="text/javascript">
        function generate_new_api_key() {
            var nsp = $('input[name="nsp"]').val();

            var user_id = <?php echo $_SESSION['user_id']?>;

            if (user_id === 'undefined') {
                user_id = $('input[name="user_id"]').val();
            }

            $.ajax({
                url: '<?php echo get_base_url(false); ?>admin/users.php',
                dataType: 'text',
                data: {
                    pageopt: 'new_api',
                    user_id: user_id,
                    nsp: nsp
                },
                success: function(data) {
                    $('#api_key').val(data);
                }
            });
        }
    </script>

    <div class="formbuilder-div formbuilder" >
        <h5 class="ul" >
            <?php echo _('Account Preferences'); ?>
        </h5>
        <table class="formbuilder-table formbuilder" >
            <tr>
                <td>
                    <label for="language" >
                        <?php echo _('Language'); ?>:
                    </label>
                </td>
                <td>
                    <select name="language"  id="language"  class="dropdown form-control" >
                        <?php echo get_options_from_array(get_languages_as_array(), $language); ?>
                    </select>
                </td>
            </tr>
            <tr>
                <td>
                    <label for="date_format" >
                        <?php echo _('Date Format'); ?>:
                    </label>
                </td>
                <td>
                    <select name="date_format"  id="date_format"  class="dropdown form-control" >
                        <?php echo get_options_from_array(get_date_formats_as_array(), $date_format); ?>
                    </select>
                </td>
            </tr>
            <tr>
                <td>
                    <label for="timezone" >
                        <?php echo _('Timezone'); ?>:
                    </label>
                </td>
                <td>
                    <select name="timezone"  id="timezone"  class="dropdown form-control" >
                        <?php echo get_options_from_array($timezones, $timezone); ?>
                    </select>
                </td>
            </tr>
            <tr>
                <td>
                    <label for="theme" >
                        <?php echo _('Theme'); ?>:
                    </label>
                </td>
                <td>
                    <select name="theme"  id="theme"  class="dropdown form-control" >
                        <option value=""<?php if ($theme == '') { echo " selected"; } ?>><?php echo _("Default"); ?></option>
                        <?php echo get_options_from_array($themes, $theme); ?>
                    </select>
                </td>
            </tr>
            <tr>
                <td>
                    <label for="number_format" >
                        <?php echo _('Number Format'); ?>:
                    </label>
                </td>
                <td>
                    <select name="number_format"  id="number_format"  class="dropdown form-control" >
                        <?php echo get_options_from_array(get_number_formats_as_array(), $number_format); ?>
                    </select>
                </td>
            </tr>
        </table>
    </div>

    <?php
    // build the auto login section
    if (count_servers() !== false) {

        $servers = get_servers();
        $auto_logins = get_auto_logins(0, null);

        // convert to array so we don't break the foreach
        if (!is_array($auto_logins))
            $auto_logins = array();

        $count = 0;

        if (count($servers) > 0) {


    ?>
    <div class="formbuilder-div formbuilder" >
        <h5 class="ul" >
            <?php echo _('Manage Automatic Logins'); ?>
        </h5>
        <table class="formbuilder-table formbuilder" >

        <?php
        foreach ($servers as $server) {

            // If authentication type corresponds to NLS/NNA, remove from automatic login list - as this is not yet supported for those products
            if ($server['authentication_type'] == AUTH_TYPE_API) {
                continue;
            }

            if ($server['auto_login']) {

                $username_id = random_string(10);
                $password_id = random_string(10);
                $enabled_id = random_string(10);

                $username = '';
                $password = '';
                $enabled = 0;

                // see if we have existing login info for this server
                foreach ($auto_logins as $auto_login) {

                    if ($auto_login['server_id'] == $server['server_id']) {

                        $username = $auto_login['username'];
                        $password = 'password_set';
                        $enabled = $auto_login['enabled'];
                    }
                }
                ?>
            <tr>
                <td>
                    <label for="<?php echo $username_id; ?>" >
                        <?php echo $server['name'] . _(' Username'); ?>:
                    </label>
                </td>
                <td>
                    <input name="auto_login_username[<?php echo $server['server_id']; ?>]" type="text" id="<?php echo $username_id; ?>" class="form-control textfield" 
                        value="<?php echo $username; ?>" />
                </td>
            </tr>
            <tr>
                <td>
                    <label for="<?php echo $password_id; ?>" >
                        <?php echo $server['name'] . _(' Password'); ?>:
                    </label>
                </td>
                <td>
                    <input name="auto_login_password[<?php echo $server['server_id']; ?>]" type="password" id="<?php echo $password_id; ?>" class="form-control textfield"  
                        value="<?php echo $password; ?>" />
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td>
                    <input id="<?php echo $enabled_id; ?>"  value="1"  name="auto_login_enabled[<?php echo $server['server_id']; ?>]" 
                        style="float: left; margin-top: 3px"  type="checkbox" <?php is_checked($enabled); ?> class="checkbox"  />
                    <label for="<?php echo $enabled_id; ?>" style="font-weight: normal; display: inline-block; margin-top: 1px;">
                        &nbsp;<?php echo _('Enable automatic login'); ?>
                    </label>
                </td>
            </tr>
            <tr>
                <td colspan="2"></td>
            </tr>
                <?php

                $count++;
            } // if server[auto_login]
        } // foreach servers
        ?>
    </table>
    </div>
    <?php
        } // if count($servers) > 0
    } // if count_servers() !== false
    ?>

    <div class="clear"></div>
    <div class="formbuilder-buttons">
        <input name="submit"  value="<?php echo _('Update Information'); ?>"  class="btn btn-primary btn-sm"  type="submit"  />
        <input name="cancel"  value="<?php echo _('Cancel'); ?>"  class="btn btn-default btn-sm cancel-validator"  type="submit"  />
    </div>
</form>

    <?php
}
