<?php
require_once(dirname(__FILE__) . '/../component-helper.inc.php');
block_non_admins();

route_request();
function route_request() {

    if (grab_request_var('deploy_dashboards') !== '')
        deploy_dashboards();
    else if (grab_request_var('undeploy') !== '')
        undeploy_dashboards();

    show_deploy_dashboards();
}

function deploy_dashboards() {

    $deploy = grab_request_var('deploy', null);
    $name = grab_request_var('name', null);
    $sync = grab_request_var('sync', null);
    $home = grab_request_var('home', null);
    $screen = grab_request_var('screen', null);
    $users = grab_request_var('users', null);

    // we only care about the submission if we have user data and deploy checkboxes checked
    if (is_array($users) && is_array($deploy)) {

        $success_count = 0;
        $error_msgs = array();

        foreach ($users as $user_id => $user_status) {

            if ($user_status != 1)
                continue;

            if (!is_valid_user_id($user_id))
                continue;

            // now, lets look at each of the dashboards we want to deploy
            foreach ($deploy as $dashboard_id => $dashboard_status) {

                if ($dashboard_status != 1)
                    continue;

                if (empty($name[$dashboard_id]))
                    continue;

                $dashboard_name = encode_html($name[$dashboard_id]);

                if (get_dashboard($dashboard_id) === false) {
                    $error_msgs[] = sprintf(_('Dashboard %s is invalid!'), "($dashboard_name)");
                    continue;
                }

                $sync_dashboard = false;
                if (!empty($sync[$dashboard_id]))
                    $sync_dashboard = true;

                // now see if we are overriding home or screen
                // can't be both
                $home_dashboard = false;
                $screen_dashboard = false;
                if ($home == $dashboard_id)
                    $home_dashboard = true;
                if (!$home_dashboard && $screen == $dashboard_id)
                    $screen_dashboard = true;

                if (deploy_dashboard_to_user_or_dashboard($dashboard_id, $user_id, $dashboard_name, $sync_dashboard, $home_dashboard, $screen_dashboard) === false) {

                    $username = get_username($user_id);
                    $error_msgs[] = sprintf(_('Unable to deploy dashboard %s to %s!'), "($dashboard_name)", $username);

                } else {

                    $success_count++;
                }
            }
        }

        if (count($error_msgs) == 0) {
            flash_message(_('All dashboards deployed successfully!'));
        } else {
            flash_message(
                _('Some errors occured while deploying dashboards!') . " $success_count " . _('were deployed successfully.'), 
                'error', 
                array(
                    'details' => implode("\n<br>", $error_msgs)
                )
            );
        }

    } else if ($users === null) {

        flash_message(_('No users selected to deploy to!'), 'error');

    } else if ($deploy === null) {

        flash_message(_('No dashboards selected to deploy!'), 'error');

    }
}


function undeploy_dashboards() {

    global $db;

    $bind = array(
        ':user_id' => intval($_SESSION['user_id']),
        );
    $deployed = $db->exec_query(
        'SELECT dashboard_id, dashboard_name, sync, user_id FROM dashboards WHERE sync IN (SELECT dashboard_id FROM dashboards WHERE user_id = :user_id)', $bind);

    if (!is_array($deployed)) {
        flash_message(_("You have no deployed dashboards to remove or unsync."), 'error');
        return;
    }

    $remove = grab_request_var('remove');
    $unsync = grab_request_var('unsync');

    $removed_count = null;
    $unsynced_count = null;
    $errmsg = '';

    if (is_array($remove)) {
        $removed_count = 0;
        foreach ($remove as $id => $r) {

            // check if this id belongs to us...
            $belongs = false;
            foreach ($deployed as $d) {
                if ($d['dashboard_id'] == $id) {
                    $belongs = true;
                    break;
                }
            }

            if ($belongs) {

                $bind = array(':dashboard_id' => $id);
                $removed = $db->exec_query('DELETE FROM dashboards WHERE dashboard_id = :dashboard_id', $bind);
                if ($removed)
                    $removed_count++;
                else
                    $errmsg .= _('Unable to delete dashboard_id: ') . $id . '<br />';
            }
        }
    }

    if (is_array($unsync)) {
        $unsynced_count = 0;
        foreach ($unsync as $id => $u) {

            // check if this id belongs to us...
            $belongs = false;
            foreach ($deployed as $d) {
                if ($d['dashboard_id'] == $id) {
                    $belongs = true;
                    break;
                }
            }

            // only if it belongs to us AND
            // we didn't just remove it
            if ($belongs && !isset($remove[$id])) {

                $bind = array(':dashboard_id' => $id);
                $unsynced = $db->exec_query('UPDATE dashboards SET sync = 0 WHERE dashboard_id = :dashboard_id', $bind);
                if ($unsynced)
                    $unsynced_count++;
                else
                    $errmsg .= _('Unable to unsync dashboard_id: ') . $id . '<br />';
            }
        }
    }

    if (!empty($errmsg)) {

        if (!is_array($remove) && is_array($unsync)) {
            $errmsg .= sprintf(_('But successfully unscyned %s dashboards!'), $unsynced_count);
        } else if (is_array($remove) && !is_array($unsync)) {
            $errmsg .= sprintf(_('But successfully removed %s dashboards!'), $removed_count);
        } else {
            $errmsg .= sprintf(_('But successfully unsynced %s dashboards and removed %s dashboards!'), $unsynced_count, $removed_count);
        }

        flash_message($errmsg, 'error');

    } else {

        if ($unsynced_count > 0 && $removed_count == 0) {
            flash_message(sprintf(_('Successfully unscyned %s dashboards!'), $unsynced_count));
        } else if ($unsynced_count == 0 && $removed_count > 0) {
            flash_message(sprintf(_('Successfully removed %s dashboards!'), $removed_count));
        } else {
            flash_message(sprintf(_('Successfully unscyned %s dashboards and removed %s dashboards!'), $unsynced_count, $removed_count));
        }
    }
}

function show_deploy_dashboards() {

    global $db;

    $title = _('Deploy Dashboards');
    child_page($title, 'home');

    echo well_top_page_header($title);

    $dashboards = get_dashboards();
    $users = get_users();

    if (!$dashboards || count($dashboards) == 0) {

        echo '<p>' . _("There aren't any dashboards to deploy!") . ' <a href="http://fusion/nagiosfusion/dashboards/?fusionwindow=manage.php" target="_top">' . _('Click here') . 
        '</a> ' . _('to make some, and then try again later.') . '</p>';
        exit();
    }

    if (!$users || count($users) <= 1) {

        echo '<p>' . _('There are no other users on this system, so you have no one to deploy a dashboard to.') . '</p>';
        exit();
    }


    // how many deployed do we have
    $bind = array(
        ':user_id' => intval($_SESSION['user_id']),
        );
    $deployed = $db->exec_query(
        'SELECT 
        d2.dashboard_name AS deployed_from,
        d1.dashboard_id AS dashboard_id, 
        d1.dashboard_name AS dashboard_name, 
        d1.sync AS sync, 
        d1.user_id AS user_id 
        FROM 
        dashboards d1 
        LEFT JOIN
        dashboards d2 
        ON 
        d2.dashboard_id = d1.sync
        WHERE d1.sync IN (SELECT dashboard_id FROM dashboards WHERE user_id = :user_id)', $bind);

    $have_deployed_dashboards = false;
    if (is_array($deployed) && count($deployed) > 0)
        $have_deployed_dashboards = true;

    ?>

    <style>
        table.deploy thead tr th.deploy-th,
        table.deploy tbody tr td {
            vertical-align: top !important;
            text-align: center !important;
        }
        table.deploy thead tr th.deploy-th input, 
        table.deploy tbody tr td input {
            float: none;
        }
    </style>

    <script type="text/javascript">
        $(function(){

            $("#deploy_dashboards").tabs().css({ 
                "min-height": "400px", 
                "overflow" : "auto" });

            $('#deploy_all').click(function() {
                $(".deploy").prop("checked", $(this).prop("checked")); 
            });

            $('#sync_all').click(function() {
                $(".sync").prop("checked", $(this).prop("checked")); 
            });

            $('#users_all').click(function() {
                $(".users").prop("checked", $(this).prop("checked")); 
            });

            $('.deploy').change(function() {
                $text = $("#name_" + $(this).data('id'));
                if ($(this).is(':checked')) {
                    set_dynamic_required($text);
                } else {
                    remove_dynamic_required($text);
                }
            });

            // you cant choose both home and screen
            // for the same dashboard, so we disable one if the other is clicked
            $('.home').click(function() {

                // reset all of these
                $('.home, .screen').show();

                $('.home').each(function() {
                    if ($(this).prop("checked")) {
                        if ($(this).val() != 'none') {
                            $('input.screen[value="' + $(this).val() + '"]').prop('checked', false);
                        } else {
                            $('input.screen').show();
                        }
                    } 
                });

                $('.screen').each(function() {
                    if ($(this).prop("checked")) {
                        if ($(this).val() != 'none') {
                            $('input.home[value="' + $(this).val() + '"]').prop('checked', false);
                        } else {
                            $('input.home').show();
                        }
                    }
                });
            });

            $('.screen').click(function() {

                // reset all of these
                $('.home, .screen').show();

                $('.screen').each(function() {
                    if ($(this).prop("checked")) {
                        if ($(this).val() != 'none') {
                            $('input.home[value="' + $(this).val() + '"]').prop('checked', false);
                        } else {
                            $('input.home').show();
                        }
                    }
                });

                $('.home').each(function() {
                    if ($(this).prop("checked")) {
                        if ($(this).val() != 'none') {
                            $('input.screen[value="' + $(this).val() + '"]').prop('checked', false);
                        } else {
                            $('input.screen').show();
                        }
                    } 
                });
            });


            $(".copy_to").click(function() {
                $("#" + $(this).data("input-id")).val($(this).data("dest"));
                $("#" + $(this).data("input-id")).keyup();
                $("#deploy_" + $(this).data("check-id")).prop("checked", true);
            });

            $('#remove_all').click(function() {
                $(".remove").prop("checked", $(this).prop("checked")); 
            });

            $('#unsync_all').click(function() {
                $(".unsync").prop("checked", $(this).prop("checked")); 
            });
        });

    </script>

    <div id="deploy_dashboards">

        <ul>
            <li>
                <a href="#deploy">
                    <?php echo _('Deploy Dashboards'); ?>
                </a>
            </li>

            <?php if ($have_deployed_dashboards) { ?>
            <li>
                <a href="#synced">
                    <?php echo _('Manage Synced Dashboards'); ?>
                </a>
            </li>
            <?php } ?>
        </ul>

        <div id="deploy">

            <p><?php echo _('This tool allows admins to deploy one or more of their own dashboards to other users. This can be useful when you design a dashboard that other users may want access to.'); ?></p>

            <p><?php echo _("If you want each user's copy of your dashboard to stay synchronized with your dashboard, select the 'Sync' option."); ?></p>

            <form>

                <h5 class="ul"><?php echo _('Dashboards To Deploy'); ?></h5>

                <p><?php echo _("Specify which of your dashboards should be deployed. If you choose to override a user's home or screen dashboard, please note that you can't choose the same dashboard for both."); ?></p>

                <?php

                // generate some popup content for tooltips
                $sync_title = _('Synchronize Dashboard');
                $sync_content = _('If this checkbox is selected, then the specified user(s) dashboard deployed using this utility will remain syncronized with the source dashboard.');
                $oh_title = _('Override Home Dashboard');
                $oh_content = 
                    _("If this radio button is selected, then the corresponding dashboard will override the specified users' home dashboard.") . 
                    '<br /><br />' . 
                    _("Select the radio button in the header row to ensure that no deployed dashboards override the users' home dashboard.");
                $os_title = _('Override Screen Dashboard');
                $os_content = 
                    _("If this radio button is selected, then the corresponding dashboard will override the specified users' screen dashboard.") . 
                    '<br /><br />' . 
                    _("Select the radio button in the header row to ensure that no deployed dashboards override the users' screen dashboard.");

                ?>

                <table class="table table-condensed table-striped table-bordered table-auto-width deploy">
                    <thead>
                        <tr>
                            <th class="deploy-th"><?php echo _('Deploy'); ?><div><input type="checkbox" id="deploy_all" value="1"></div></th>
                            <th class="deploy-th"><?php echo _('Source Name'); ?></th>
                            <th class="deploy-th"><?php echo _('Destination Name'); ?></th>
                            <th class="deploy-th">
                                <?php echo _('Sync') . '&nbsp;' . pop($sync_title, $sync_content); ?>
                                <br />
                                <input type="checkbox" id="sync_all">
                            </th>
                            <th class="deploy-th">
                                <?php echo _('Home') . '&nbsp;' . pop($oh_title, $oh_content); ?>
                                <br />
                                <input type="radio" name="home" class="home" value="none">
                            </th>
                            <th class="deploy-th">
                                <?php echo _('Screen') . '&nbsp;' . pop($os_title, $os_content); ?>
                                <br />
                                <input type="radio" name="screen" class="screen" value="none">
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php

                        foreach ($dashboards as $d) {

                            // why would we let a user redeploy a deployed dashboard?
                            if ($d['sync'])
                                continue;

                            // dashboard id
                            $did = $d['dashboard_id'];
                            $dname = $d['dashboard_name'];
                            ?>

                            <tr>
                                <td>
                                    <input type="checkbox" class="deploy" name="deploy[<?php echo $did; ?>]" value="1" data-id="<?php echo $did; ?>" id="deploy_<?php echo $did; ?>" />
                                </td>
                                <td style="vertical-align: middle !important;">
                                    <?php echo $dname; ?>
                                    <a style="cursor: pointer;" 
                                        class="copy_to" 
                                        data-dest="<?php echo $dname; ?>" 
                                        data-input-id="name_<?php echo $did; ?>" 
                                        data-check-id="<?php echo $did; ?>" 
                                        title="' . _('Click here to copy the dashboard name into the destination') . '">

                                        <img src="<?php echo get_icon_url('b_next2.png'); ?>" style="float: right;" />
                                    </a>
                                </td>
                                <td>
                                    <input type="text" id="name_<?php echo $did; ?>" class="form-control condensed" name="name[<?php echo $did; ?>]" placeholder="<?php echo $dname; ?>" style="width: 200px;">
                                </td>
                                <td>
                                    <input type="checkbox" class="sync" name="sync[<?php echo $did; ?>]" value="1" />
                                </td>
                                <td>
                                    <input type="radio" class="home" name="home" value="<?php echo $did; ?>" />
                                </td>
                                <td>
                                    <input type="radio" class="screen" name="screen" value="<?php echo $did; ?>" />
                                </td>
                            </tr>

                            <?php
                        }
                    ?>
                    </tbody>
                </table>

                <h5 class="ul"><?php echo _('Deploy to Users'); ?></h5>

                <p><?php echo _('Specify which users the dashboards should be deployed to.'); ?></p>

                <p>
                    <label style="font-weight: normal; cursor: pointer;">
                        <input type="checkbox" id="users_all" style="cursor: pointer;" />
                        &nbsp;&nbsp;<?php echo _('Check or uncheck all users.'); ?>
                    </label>
                </p>

                <div class="sel-users-new" style="width: 400px; margin-bottom: 20px;">
                    <?php
                        foreach ($users as $u) {
                            echo '<div class="checkbox">';
                            echo '<label>';
                            echo '<input type="checkbox" class="users" name="users[' . $u['user_id'] . ']" value="1"> ' . $u['name'] . ' (' . $u['username'] . ')' . '</label></div>';
                        }
                    ?>
                </div>

                <div id="formButtons">
                    <input type="submit" class="btn btn-sm btn-primary" name="deploy_dashboards" id="updateButton" value="<?php echo _('Deploy Dashboards'); ?>" />
                    <input type="submit" class="btn btn-sm btn-default" name="cancel" id="cancelButton" value="<?php echo _('Cancel'); ?>" />
                </div>

            </form>

        </div><!-- deploy -->

        <?php if ($have_deployed_dashboards) { ?>
        <div id="synced">

            <p><?php echo _("Use this utility to unsynchronize or remove any dashboards that you've deployed. When you synchronize a dashboard to a non-administrator, they have no way of removing it or editing it."); ?></p>

            <form>

            <h5 class="ul"><?php echo _('Synchronized Dashboards'); ?></h5>

            <p><?php echo _("Use this table to specify which dashboards to unsync or remove."); ?></p>

            <table class="table table-condensed table-striped table-bordered table-auto-width deploy">
                <thead>
                    <tr>
                        <th class="deploy-th">
                            <?php echo _('Remove'); ?>
                            <div>
                                <input type="checkbox" id="remove_all" value="1">
                            </div>
                        </th>
                        <th class="deploy-th">
                            <?php echo _('Unsync'); ?>
                            <div>
                                <input type="checkbox" id="unsync_all" value="1">
                            </div>
                        </th>
                        <th class="deploy-th">
                            <?php echo _('Deployed From'); ?>
                        </th>
                        <th class="deploy-th">
                            <?php echo _('Dashboard Name'); ?>
                        </th>
                        <th class="deploy-th">
                            <?php echo _('User'); ?>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    foreach ($deployed as $d) {

                        $user = get_username($d['user_id']);
                        echo '
                            <tr>
                                <td><input type="checkbox" class="remove" name="remove[' . $d['dashboard_id'] . ']" value="1" /></td>
                                <td><input type="checkbox" class="unsync" name="unsync[' . $d['dashboard_id'] . ']" value="1" /></td>
                                <td>' . $d['deployed_from'] . '</td>
                                <td>' . $d['dashboard_name'] . '</td>
                                <td>' . $user . '</td>
                            </tr>';
                    }
                    ?>
                </tbody>
            </table>

            <div id="formButtons">
                <input type="submit" class="btn btn-sm btn-primary" name="undeploy" id="updateButton" value="<?php echo _('Un-Deploy Dashboards'); ?>" />
                <input type="submit" class="btn btn-sm btn-default" name="cancel" id="cancelButton" value="<?php echo _('Cancel'); ?>" />
            </div>

        </form>

        </div><!-- synced -->
        <?php } ?>
    </div>

    <?php
}

