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

// TODO: manage non-admin dashboards?
// TODO: deploy dashboard



route_request();
function route_request() {

    $pageopt = get_pageopt();

    // if we chose a multi button, we just redirect the page opt based on the value
    $multi = grab_request_var('multi');
    $valid_multi_values = array('delete', 'show_in_menu', 'hide_in_menu');
    if (in_array($multi, $valid_multi_values))
        $pageopt = $multi;

    switch ($pageopt) {

        case 'show_in_menu':
            update_show_in_menu(1);
            break;

        case 'hide_in_menu':
            update_show_in_menu(0);
            break;

        case 'update':
            update_dashboards();
            break;

        case 'delete':
            delete_dashboards();
            break;

        case 'edit':
            edit_dashboard();
            break;

        case 'deploy':
        	deploy_dashboard();
        	break;

        default:
            show_dashboards();
            break;
    }
}

function update_show_in_menu($show_in_menu = 1) {

    check_nagios_session_protector();

    $dashboard_id = grab_request_var('dashboard_id', -1);

    $count = 0;

    if (is_string($dashboard_id)) {
        $dashboard_id = array($dashboard_id);
    }

    if (is_array($dashboard_id)) {
        foreach ($dashboard_id as $this_dashboard_id) {

            if (update_dashboard($this_dashboard_id, $dashboard_name = null, $show_in_menu, $bgcolor = null))
                $count++;
            else
                flash_message(_('There was an error updating the specified dashboards.'), 'error');
        }
    }

    flash_message(sprintf(_('%d dashboards successfully updated.'), $count));

    show_dashboards(true);
    exit();
}

function delete_dashboards() {

    // no changes in demo
    demo_error('show_dashboards');

	check_nagios_session_protector();

	$dashboard_id = grab_request_var('dashboard_id', -1);

	$count = 0;
    $error = false;

	if (is_string($dashboard_id)) {
		$dashboard_id = array($dashboard_id);
	}

	if (is_array($dashboard_id)) {
		foreach ($dashboard_id as $this_dashboard_id) {

			if (delete_dashboard($this_dashboard_id))
				$count++;
			else {
                $error = true;
				flash_message(_('There was an error deleting the specified dashboards.'), 'error');
                break;
            }
		}
	}

    if (!$error)
	   flash_message(sprintf(_('%d dashboards successfully deleted.'), $count));

    show_dashboards(true);
    exit();
}

function show_dashboards($reload = false) {

    if ($reload)
        reload_page('/dashboards/', 'manage.php');

    $title = _('Manage Dashboards');
    child_page($title);
    echo well_top_page_header($title);
	?>

    <p><?php echo _('Create, edit, and remove dashboards from your dashboard list.'); ?></p>

    <div class="page-buttons">
        <a href="?edit" class="btn btn-sm btn-primary">
            <i class="fa fa-desktop"></i>
            <span><?php echo _('Add a Dashboard'); ?></span>
        </a>
    </div>

    <?php

    $select_statement = "SELECT * FROM dashboards WHERE user_id = :user_id AND screen != 1";
    $bind_array = array(':user_id' => intval($_SESSION['user_id']));
    $opts = array(
        'display_footer' => false,
        'table_class' => 'table table-condensed table-hover table-bordered table-striped',
        'default_pagination' => array(
            'orderby_column' => 'dashboard_name',
            'orderby_order' => 'ASC'
        ),
        'pre_table_html' => 
            '<script>
                $(function() { 
                    $("#select_all").click(function() { 
                        $("input.dashboards_checkbox").prop("checked", $(this).prop("checked")); 
                    }); 
                    $("input.dashboards_checkbox").closest("tr").click(function(ev) {                        
                        // cancel if click is on an input or on a th
                        if (ev.target.nodeName === "INPUT" || ev.target.nodeName === "TH" || ev.target.nodeName === "IMG" || ev.target.nodeName == "SPAN")
                            return;

                        $(this).find("input.dashboards_checkbox").click();
                    });
                });
            </script>',

        'columns' => array(
            'checkbox' => array(
                'th' => '<input type="checkbox" id="select_all" class="dashboards_checkbox" />',
                'td' => '<input type="checkbox" name="dashboard_id[]" value="%dashboard_id%" class="dashboards_checkbox" />',
                'replace_macros' => true,
                'width' => '16px',
                ),

            'dashboard_name' => array(
            	'th' => _('Dashboard Name'),
            	'sortable' => true,
            	'width' => '70%',
            	),

            'actions' => array(
            	'th' => _('Actions'),
            	'transform' => 'dashboards_build_action_td',
            	'replace_macros' => true,
            	),
            ),

        'with_selected' => array(
            array(
                'value' => 'show_in_menu',
                'title' => _('Show in Dashboard Menu'),
                'img' => get_icon_url('folder_add.png')
                ),
            array(
                'value' => 'hide_in_menu',
                'title' => _('Hide from Dashboard Menu'),
                'img' => get_icon_url('folder_delete.png')
                ),
            array(
                'value' => 'delete',
                'title' => _('Delete'),
                'img' => get_icon_url('cross.png'),
                ),
        	),
        );
    echo '<form method="post">';
    echo get_paged_table($select_statement, $bind_array, $opts);
    echo '</form>';
}

function edit_dashboard() {

    $title = _('Manage Dashboard');
	child_page($title);

	$dashboard_id = grab_request_var('dashboard_id', -1);
	if (is_array($dashboard_id))
		$dashboard_id = -1;

	$add_dashboard = $dashboard_id == -1 ? true : false;

	$page_header = _('Add a Dashboard');
	$submit_button_value = _('Add Dashboard');

	$dashboard_name = '';
    $show_in_menu = 1;
	$bgcolor = 'ffffff';

    $screen = false;

	if (!$add_dashboard) {

        $dashboard = get_dashboard($dashboard_id);
        if ($dashboard !== false) {

			$dashboard_name = $dashboard['dashboard_name'];
            $show_in_menu = $dashboard['show_in_menu'];
			$bgcolor = $dashboard['bgcolor'];

            if ($dashboard['screen'] == 1)
                $screen = true;

			$page_header = _('Edit Dashboard');
			$submit_button_value = _('Update Dashboard');
		}
	}
    
    echo well_top_page_header($page_header);

    // if we are a screen dashboard, we don't show bg info (including the spectrum color picker)
    if (!$screen) {
        ?>
        <script>
            $(function () {
            	$('#background').spectrum({
            		color: '#<?php echo $bgcolor; ?>',
                    chooseText: "<?php echo _('Change'); ?>",
                    cancelText: "<?php echo _('Cancel'); ?>",
                    chooseClass: "btn btn-sm btn-default",
                    showPaletteOnly: true,
                    togglePaletteOnly: true,
                    togglePaletteMoreText: "<?php echo _('More'); ?>",
                    togglePaletteLessText: "<?php echo _('Less'); ?>",
                    palette: [
                        ["#000","#444","#666","#999","#ccc","#eee","#f3f3f3","#fff"],
                        ["#f00","#f90","#ff0","#0f0","#0ff","#00f","#90f","#f0f"],
                        ["#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#cfe2f3","#d9d2e9","#ead1dc"],
                        ["#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#9fc5e8","#b4a7d6","#d5a6bd"],
                        ["#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6fa8dc","#8e7cc3","#c27ba0"],
                        ["#c00","#e69138","#f1c232","#6aa84f","#45818e","#3d85c6","#674ea7","#a64d79"],
                        ["#900","#b45f06","#bf9000","#38761d","#134f5c","#0b5394","#351c75","#741b47"],
                        ["#600","#783f04","#7f6000","#274e13","#0c343d","#073763","#20124d","#4c1130"]
                    ],
            		change: function (color) {
            			$('#bgcolor').val(color.toHex());
            		}
            	});
            });
        </script>
        <?php
    }

    ?>
<form method="post"  action="?update"  class="formbuilder" >
    <input name="update"  value="1"  type="hidden"  />
    <input name="dashboard_id"  value="<?php echo $dashboard_id; ?>"  type="hidden"  />
    <input name="bgcolor"  id="bgcolor"  value="ffffff"  type="hidden"  />

    <script>
        if (current_theme == "modern-dark") {
            $("#bgcolor").val("111")
        }
    </script>

    <div class="formbuilder-div formbuilder" >
        <h5 class="ul" >
            <?php echo _('Dashboard Information'); ?>
        </h5>
        <table class="formbuilder-table formbuilder" >
            <tr>
                <td>
                    <label for="dashboard_name" >
                        <?php echo _('Dashboard Name'); ?>:
                    </label>
                </td>
                <td>
                    <input name="dashboard_name"  placeholder="<?php echo _('Dashboard Name'); ?>:"  value="<?php echo encode_html($dashboard_name); ?>" type="text"  id="dashboard_name"  class="form-control textfield"  required="true" maxlength="128" />
                </td>
            </tr>
            <tr>
                <td>
                    <label for="background" >
                        <?php echo _('Background Information'); ?>:
                    </label>
                </td>
                <td>
                    <input id="background"  type="text"  class="form-control textfield"  />
                    <script type="text/javascript">
                        $(function() {
                            var bgcolor = '#FFF'
                            if(current_theme == "modern-dark") {
                                bgcolor = "#111"
                            }
                            $('#background').spectrum({
                                showAlpha: true,
                                color: tinycolor(bgcolor).toRgbString(),
                                chooseText: "<?php echo _('Change'); ?>",
                                cancelText: "<?php echo _('Cancel'); ?>",
                                chooseClass: "btn btn-sm btn-default",
                                showPaletteOnly: true,
                                togglePaletteOnly: true,
                                togglePaletteMoreText: "<?php echo _('More'); ?>",
                                togglePaletteLessText: "<?php echo _('Less'); ?>",
                                palette: [
                                    ["#000","#444","#666","#999","#ccc","#eee","#f3f3f3","#fff"],
                                    ["#f00","#f90","#ff0","#0f0","#0ff","#00f","#90f","#f0f"],
                                    ["#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#cfe2f3","#d9d2e9","#ead1dc"],
                                    ["#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#9fc5e8","#b4a7d6","#d5a6bd"],
                                    ["#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6fa8dc","#8e7cc3","#c27ba0"],
                                    ["#c00","#e69138","#f1c232","#6aa84f","#45818e","#3d85c6","#674ea7","#a64d79"],
                                    ["#900","#b45f06","#bf9000","#38761d","#134f5c","#0b5394","#351c75","#741b47"],
                                    ["#600","#783f04","#7f6000","#274e13","#0c343d","#073763","#20124d","#4c1130"]
                                ],
                                change: function(color) {
                                    $("#bgcolor").val(color.toHex())
                                }
                            });
                        });
                    </script>
                </td>
            </tr>
            <tr>
                <td>
                    <label for="show_in_menu" >
                        <?php echo _('Show in Dashboards Menu'); ?>:
                    </label>
                </td>
                <td>
                    <input name="show_in_menu" type="checkbox" value="1" <?php echo ($show_in_menu == 1) ? 'checked="checked"' : ''; ?> id="show_in_menu" class="checkbox" />
                </td>
            </tr>
        </table>
    </div>
    <div class="clear"></div>
    <div class="formbuilder-buttons">
        <input name="submit"  value="<?php echo $submit_button_value; ?>"  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
}

function update_dashboards() {

	check_nagios_session_protector();

    // if we aren't updating or we pressed cancel then just go ahead and show_dashboards
    $update = grab_request_var('update', false);
    $cancel = grab_request_var('cancel', false);
    if (!$update || $cancel)
        flash_message_cb_and_exit('show_dashboards');

    $dashboard_id = intval(grab_request_var('dashboard_id', -1));

    $dashboard_name = encode_html(trim(grab_request_var('dashboard_name')));
    $show_in_menu = grab_request_var('show_in_menu', 0);
    $bgcolor = grab_request_var('bgcolor');

    $message = '';
    $message_type = '';

    if (empty($dashboard_name) || ctype_space($dashboard_name))
        $message .= _('Dashboard name cannot be blank.') . '<br>';
    if (!ctype_xdigit($bgcolor))
        $message .= _('Background color must be a valid hexadecimal value.') . '<br>';

    if (!empty($message))
        flash_message_cb_and_exit('show_dashboards', $message, 'error');

    // adding a dashboard
    if ($dashboard_id == -1) {
        
       if (add_dashboard($dashboard_name, $user_id = 0, $sync = null, $home = null, $show_in_menu, $screen = null, $bgcolor)) {
           $message = _('Dashboard added successfully.');
           $message_type = 'info';
       } else {
            $message = _('Something went wrong adding the dashboard.');
            $message_type = 'error';
       }

    // updating a dashboard
    } else {

        if (update_dashboard($dashboard_id, $dashboard_name, $show_in_menu, $bgcolor)) {
            $message = _('Dashboard updated successfully.');
            $message_type = 'info';
        } else {
            $message = _('Something went wrong updating the dashboard.');
            $message_type = 'error';
        }
    }

    // only refresh top if a success message occured
    flash_message($message, $message_type);
    if ($message_type == 'info')
        show_dashboards(true);
    else
        show_dashboards();
    exit();
}
