<?php

$authenticated = is_authenticated();
$admin = is_admin();
$base_url = get_base_url();

$servers_link = $admin ? "<a href=\"{$base_url}admin/?fusionwindow=servers.php\">" : '<a class="servers-nolink">';
$servers = get_servers();
$auto_logins = get_auto_logins(0, null);
$page = get_current_page();

$show_license = false;
if (@isset($_SESSION['agreelicense']) && $_SESSION['agreelicense'])
    $show_license = true;

?>
    <script>
        
        <?php if ($page === "login.php") { ?>
            $("#header").addClass("no-show");
        <?php } ?>
        // Capture any click back into the inner frame from the outer window and close the profile dropdown
        $(function() {
            window.addEventListener('blur', (event) => {
                // Wrap in setTimeout() to push execution to the next event cycle after initial page load
                setTimeout(() => {
                    if (document.activeElement.tagName === "IFRAME") {
                        $("#profile-button-div").removeClass("open");
                        $("#profile-button").attr("aria-expanded", "false");
                        $("#topalert-popover-servers").popover('hide');
                        $("#topalert-popover").popover('hide');
                    }
                });
            })
        });
    </script>


<!-- PARENT HEADER START -->
<div id="toplogo">
    <?php echo get_nagios_logo(); ?>
</div>

<div id="topmenu">
    <?php if ($authenticated && !$show_license) { ?>
        <div class="mainmenu">
            <div><a href="<?php echo $base_url; ?>views/" id="views-topbar"><?php echo _('Views'); ?></a></div>
            <div><a href="<?php echo $base_url; ?>dashboards/" id="dashboards-topbar"><?php echo _('Dashboards'); ?></a></div>
            <?php if (count($servers) > 0) { ?>
                <div id="config-menulink">
                    <span>
                        <?php echo $servers_link . _('Servers') . '</a>'; ?>
                        <ul class="config-dropdown">
                            <?php 
                                foreach ($servers as $server) {
                                    $auto = '<span class="auto-login">&nbsp;</span>';

                                    $url = $server['url'];

                                    // Search logins and find matching server login... or not
                                    foreach ($auto_logins as $al) {
                                        if ($al['server_id'] == $server['server_id']) {
                                            if ($al['enabled']) {
                                                $auto = '<span class="auto-login tt-bind" title="'._('Auto logged in').'" data-placement="right"><i class="fa fa-14 fa-check"></i></span>';

                                                // if its basic auth we need to pass THIS auto_login username and password to the url
                                                // instead of using the server's url
                                                if ($server['authentication_type'] == AUTH_TYPE_BASIC) {

                                                    $user = $al['username'];
                                                    $pass = _decrypt($al['password']);

                                                    $url = get_server_base_url($server, false, $user, $pass);
                                                }
                                            } else {

                                                $saved_creds_url = '';
                                                if ($server['server_type'] == SERVER_TYPE_XI) {

                                                    $saved_creds_url = $base_url . 'login.php?external&server_id=' . $al['server_id'];

                                                } else if ($server['server_type'] == SERVER_TYPE_CORE) {

                                                    $user = $al['username'];
                                                    $pass = _decrypt($al['password']);

                                                    $saved_creds_url = get_server_base_url($server, false, $user, $pass);
                                                }

                                                $auto = '
                                                    <span class="auto-login tt-bind" title="' . _('Login with saved credentials') . '" data-placement="right">
                                                        <a class="external-login" href="' . $saved_creds_url . '" target="_blank">
                                                            <i class="fa fa-14 fa-sign-in"></i>
                                                        </a>
                                                    </span>';
                                            }
                                        }
                                    }


                                    echo '<li id="server-al-'.$server['server_id'].'"><a href="' . $url . '" target="_blank">' . encode_html($server['name']) . '</a> '.$auto.'</li>';
                                }
                            ?>
                        </ul>
                    </span>
                </div>
            <?php } // servers > 0 ?>

            <div><a href="<?php echo $base_url; ?>help/" id="help-topbar"><?php echo _('Help'); ?></a></div>

            <?php if ($admin) { ?>

                <div><a href="<?php echo $base_url; ?>admin/" id="admin-topbar"><?php echo _('Admin'); ?></a></div>

            <?php } // $admin ?>

        </div><!-- mainmenu -->

        <div class="hiddenmenu">
            <div id="mdropdown">
                <span>
                    <span class="nav-head"><i class="fa fa-chevron-down l"></i>&nbsp;<?php echo _('Navigation'); ?></span>
                    <ul class="dropdown-items">
                        <li><a href="<?php echo $base_url; ?>views/"><?php echo _('Views'); ?></a></li>
                        <li><a href="<?php echo $base_url; ?>dashboards/"><?php echo _('Dashboards'); ?></a></li>

                        <?php if ($admin) { ?>
                            <li><a href="<?php echo $base_url; ?>admin/?fusionwindow=servers.php"><?php echo _('Servers'); ?></a></li>
                        <?php } // $admin ?>

                        <li><a href="<?php echo $base_url; ?>help/"><?php echo _('Help'); ?></a></li>

                        <?php if ($admin) { ?>
                            <li><a href="<?php echo $base_url; ?>admin/"><?php echo _('Admin'); ?></a></li>
                        <?php } // $admin ?>

                    </ul>
                </span>
            </div><!-- mdropdown -->
        </div><!-- hiddenmenu -->

    <?php } else { // $authenticated && $show_license
        
        if (!$show_license) { ?>
            <div class="mainmenu">
                <?php if (install_needed()) { ?>
                <div><a href="<?php echo $base_url; ?>install.php"><?php echo _('Install'); ?></a></div>
                <?php } else { ?>
                <div><a href="<?php echo $base_url; ?>login.php"><?php echo _('Login'); ?></a></div>
                <?php } ?>
            </div><!-- mainmenu -->
        <?php } // !show_license ?>

    <?php } // $authenticated ?>
</div><!-- topmenu -->

    <?php if ($authenticated && !$show_license) { ?>

        <div class="header-right ext">
            <span class="ext-menu">
                <i class="fa fa-bars"></i>
                <ul>
                    <li id="popout" class="tt-bind" data-placement="left" title="<?php echo _('Popout'); ?>"><a href="#"><i class="fa fa-share-square-o"></i></a></li>
                    <li id="addtomyviews" class="tt-bind" data-placement="left" title="<?php echo _('Add to my views'); ?>"><a href="#"><i class="fa fa-plus-circle"></i></a></li>
                    <li id="permalink" class="tt-bind" data-placement="left" title="<?php echo _('Get permalink'); ?>"><a href="#"><i class="fa fa-chain"></i></a></li>
                    <li id="feedback" class="tt-bind" data-placement="left" title="<?php echo _('Send us feedback'); ?>"><a href="#"><i class="fa fa-comment-o"></i></a></li>
                </ul>
            </span>
        </div>

        <div class="header-right profile">
            <div id="profile-button-div" class="btn-group">
                <button type="button" id="profile-button" title="<?php echo _('Profile'); ?>"class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                    <i class="fa fa-user-circle fa-lg"></i>
                    <i class="fa fa-caret-down" aria-hidden="true"></i>
                </button>
                <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel" style="left: initial; right: 0;">
                    <li>
                        <a href="<?php echo get_base_url(); ?>account/">
                            <i class="fa fa-user fa-lg"></i>
                            <span><?php echo $_SESSION["username"]; ?></span>
                        </a>
                    </li>
                    <li role="presentation" class="divider"></li>
                    <li>
                        <?php if (!is_http_basic_authenticated()) { ?>
                            <a href="<?php echo $base_url; ?>login.php?logout&amp;nsp=<?php echo get_nagios_session_protector_id(); ?>" id="logout-href">
                                <i class="fa fa-power-off fa-lg"></i>
                                <span><?php echo _('Logout'); ?></span>
                            </a>
                        <?php } ?>
                    </li>
                </ul>
            </div>
        </div>

        <div class="header-right system-alerts">
            <div id="pagetopalertcontent"></div>
            <script type="text/javascript">
                $(function() {
                    $('#profile-button').on('click', function() {
                        $("#topalert-popover").popover('hide');
                        $("#topalert-popover-servers").popover('hide');
                    })

                    $('#pagetopservercontent').on('click', function () {
                        $("#topalert-popover").popover('hide');
                    });

                    $('#pagetopalertcontent').on('click', function () {
                        $("#topalert-popover-servers").popover('hide');
                    });

                    get_pagetopalertcontent_content("pagetopalertcontent");
                    get_pagetopalertcontent_content_servers("pagetopservercontent");

                    function create_popover() {
                        $("#topalert-popover").tooltip({ placement: "left" });
                        $("#topalert-popover").popover({ html: true });

                        $("#topalert-popover-servers").tooltip({ placement: "left" });
                        $("#topalert-popover-servers").popover({ html: true });
                    }

                    $("#pagetopalertcontent").everyTime(30000, "timer-pagetopalertcontent", function() {
                        get_pagetopalertcontent_content("pagetopalertcontent");
                    });

                    $("#pagetopservercontent").everyTime(30000, "timer-pagetopservercontent", function() {
                        get_pagetopalertcontent_content_servers("pagetopservercontent");
                    });

                    // but we also update it after 2 seconds in the case of adding a new server
                    setTimeout(function() { get_pagetopalertcontent_content("pagetopalertcontent"); }, 2000);
                    setTimeout(function() { get_pagetopalertcontent_content_servers("pagetopservercontent"); }, 2000);

                    function get_pagetopalertcontent_content() {
                        var data = { };
                        post_ajax_data_with_callback("system_alert", data, function(html) {

                            html = html.trim();
                            $("#pagetopalertcontent").html(html);

                            create_popover();
                        });
                    }

                    function get_pagetopalertcontent_content_servers() {
                        var data = { };
                        post_ajax_data_with_callback("fused_servers", data, function(html) {

                            html = html.trim();
                            $("#pagetopservercontent").html(html);

                            create_popover();
                        });
                    }
                });
            </script>
        </div>
        <div class="header-right system-alerts">
            <div id="pagetopservercontent"></div>
        </div>

    <?php } // $authenticated ?>

    <div id="popup_layer">
        <div id="popup_content">
            <div id="popup_close">
                <a id="close_popup_link" style="display: inline-block;" title="<?php echo _("Close"); ?>"><i class="fa fa-times" style="font-size: 16px;"></i></a>
            </div>
            <div id="popup_container">
            </div>
        </div>
    </div>

    <?php
    $feedback_name = get_user_attr('name');
    $feedback_email = get_user_attr('email');
    ?>
    <div id="feedback_layer">
        <div id="feedback_content">

            <div id="feedback_close">
                <a id="close_feedback_link" style="display: inline-block;" title="<?php echo _("Close"); ?>"><i class="fa fa-times" style="font-size: 16px;"></i></a>
            </div>

            <div id="feedback_container">

                <div id="feedback_header">
                    <strong><?php echo _('Send Us Feedback'); ?></strong>
                </div>
                <div id="feedback_data">
                    <p><?php echo _("We love input!  Tell us what you think about this product and you'll directly drive future innovation!"); ?></p>
                    <form id="feedback_form" method="get" action="<?php echo get_ajax_proxy_url(); ?>">

                        <input type="hidden" name="proxyurl" value="https://api.nagios.com/feedback/">
                        <input type="hidden" name="proxymethod" value="post">

                        <input type="hidden" name="product" value="<?php echo get_product_name(true); ?>">
                        <input type="hidden" name="version" value="<?php echo get_product_version(); ?>">
                        <input type="hidden" name="build" value="<?php echo get_product_build(); ?>">

                        <label for="feedbackCommentBox"><?php echo _("Comments"); ?>:</label>
                        <textarea class="textarea form-control" name="comment" style="width: 100%; height: 100px;"></textarea>

                        <label for="feedbackNameBox"><?php echo _("Your Name (Optional)"); ?>:</label>
                        <input type="text" size="30" name="name" id="feedbackNameBox" value="<?php echo encode_html($feedback_name); ?>" class="textfield form-control">

                        <label for="feedbackEmailAddressBox"><?php echo _("Your Email Address (Optional)"); ?>:</label>
                        <input type="text" size="30" name="email" id="feedbackEmailAddressBox" value="<?php echo encode_html($feedback_email); ?>" class="textfield form-control">

                        <div>
                            <div class="fl" id="feedbackFormButtons">
                                <input type="submit" class="submitbutton btn btn-sm btn-primary" name="submitButton" value="<?php echo _("Submit"); ?>" id="submitFeedbackButton">
                            </div>
                            <div class="fr feedback-pp">
                                <a href="https://www.nagios.com/legal/privacy-policy/" target="_blank" rel="noreferrer"><?php echo _("Privacy Policy"); ?></a>
                            </div>
                            <div class="clear"></div>
                        </div>

                    </form>
                </div>
            </div>
        </div>
    </div>

<script>
    $( document ).ready(function() {
        var auto_logins = []
        
        $.get( "<?php echo $base_url; ?>/ajaxhelper.php", { cmd: "authenticate_auto_login" }, function( auto_login_data ) {
            try {
                JSON.parse(auto_login_data);
            } catch (e) {
                return false;
            }
            auto_logins = JSON.parse(auto_login_data);
        }).done(function(){
            auto_logins.forEach(auto_login => {
                if ( auto_login['server_user'] ) {
                    $.ajax({
                        type: "POST",
                        url: auto_login['server_url'] + "api/v1/authenticate?",
                        data: { username: auto_login['server_user'], password: auto_login['server_pass'] },
                        success: function( auth_token_data ){
                            var token_url = auto_login['server_url'] + "login.php?token=" + auth_token_data['auth_token'];
                            $('#server-al-' + auto_login["server_id"]).children('a').attr('href', token_url);
                        }
                    })
                }
            });
        });
    });
</script>

<!-- PARENT HEADER END -->
<?php
