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

route_request();
function route_request() {

    $pageopt = get_pageopt();

    switch ($pageopt) {

        case 'update':
            update_view();
            break;

        case 'delete':
            delete_the_view();
            break;

        case 'edit':
            edit_view();
            break;

        default:
            show_views();
            break;
    }
}


function show_views($reload = false) {

    $title = _('Manage My Views');
    child_page($title);

    // unlike a lot of other pages, we don't actually reload here
    // we just run the update menu javascript
    if ($reload)
        echo '<script type="text/javascript">update_views_menu();</script>';

    echo well_top_page_header($title);
    ?>
    <div class="page-buttons" style="margin-bottom: 10px;">
        <a href="?edit" class="btn btn-sm btn-primary">
            <i class="fa fa-plus-circle"></i>
            <span><?php echo _('Add a View'); ?></span>
        </a>
    </div>
    <?php

    echo '<div style="margin: 20px 0 10px 0;">';
    echo '<p>' . _('Adding views is handled via either the "Add a View" button directly above this paragraph, or the menu') . ' (<i class="fa fa-bars"></i>) ' . _("icon in the top right corner of the screen. Once you move your mouse over the menu icon, you're presented with different options. Select the Add View ") . ' (<i class="fa fa-plus-circle"></i>) ' . _("icon to add whatever page you're currently on to your views!") . '</p>';
    echo '<p>' . _('Use the Manage My Views table below to re-order, edit, and remove views. You can drag and drop the views to re-order them, click the pencil to edit them, or click on the red &times; to remove them.') . '</p>';
    echo '</div>';

    $user_id = 0;
    if (isset($_SESSION['user_id']))
        $user_id = intval($_SESSION['user_id']);

    $select_statement = "SELECT * FROM views WHERE user_id = $user_id";
    $opts = array(
        'default_pagination' => array(
            'orderby_column'    => 'view_order',
            ),
        'display_footer' => false,
        'ignore_pagination_div' => true,
        'static_limit' => 99999,
        'table_class' => 'table table-condensed table-hover table-bordered table-striped',
        'table_html' => 'style="width: 50%;"',
        'tbody_id' => 'sortable',
        'pre_table_html' => 
            '<script>
                $(function() { 

                    $("#sortable").sortable({

                        stop: function(event, ui) {

                            var order_arr = {};

                            $(".view_order").each(function(order, el) {
                                order_arr[order] = $(el).attr("id");
                            });

                            post_ajax_data_with_callback("update_view_order", order_arr, function(html) { update_views_menu(); });
                        }

                    }).disableSelection();
                });
            </script>',
        'columns' => array(
            'view_title' => array(
                'th' => _('View Title'),
                'replace_macros' => true,
                'td' => '%view_title%<input class="view_order" type="hidden" id="%view_id%" value="%view_order%" />',
                ),
            'actions' => array(
                'th' => '',
                'width' => '60px',
                'transform' => 'views_build_action_td',
                'replace_macros' => true,
                ),
            ),
        );
    echo '<form method="post">';
    echo get_paged_table($select_statement, null, $opts);
    echo '</form>';
    ?>
    <style>
        .table tbody#sortable tr td:last-child { text-align: center; }
        .table tbody tr.ui-sortable-helper td { border: none; }
        .table tbody tr.ui-sortable-helper td:last-child { display: none; }
    </style>


    <script type="text/javascript">
        $(function() {
            get_ajax_data_html("get_my_views_menu", 0, $("#test"));
        });
    </script>
    <?php
}

function edit_view() {

    // server_id of -1 means add, otherwise edit
    $view_id = grab_request_var('view_id', -1);
    if (is_array($view_id))
        $view_id = -1;

    $title = _('Add View');
    $submit_button_value = $title;
    if ($view_id != -1) {
        $title = _('Edit View');
        $submit_button_value = _('Update View');
    }

    $view_title = get_view_attr('view_title', $view_id, '');
    $view_title = grab_request_var('view_title', $view_title);
    
    $view_url = get_view_attr('view_url', $view_id, '');
    $view_url = grab_request_var('view_url', $view_url);


    child_page($title);
    echo well_top_page_header($title);

    ?>
    <form method="post"  action="?update"  class="formbuilder" >
        <input name="update"  value="1"  type="hidden"  />
        <input name="view_id" id="view_id" value="<?php echo $view_id; ?>"  type="hidden"  />
        <div class="formbuilder-div formbuilder">
            <h5 class="ul" >
                <?php echo $title; ?>
            </h5>
            <table class="formbuilder-table formbuilder" >
                <tr>
                    <td class="vt">
                        <label for="view_title" >
                            <?php echo _('View Title'); ?>:
                        </label>
                    </td>
                    <td>
                        <input name="view_title"  placeholder="<?php echo _('View Title'); ?>"  value="<?php echo encode_html($view_title); ?>"  type="text" class="form-control textfield" required="true"  />
                    </td>
                </tr>
                <tr>
                    <td>
                        <label for="view_url" >
                            <?php echo _('View URL'); ?>:
                        </label>
                    </td>
                    <td>
                        <input name="view_url"  placeholder="<?php echo _('View URL'); ?>"  value="<?php echo encode_html($view_url); ?>"  type="text" class="form-control textfield" required="true"  />
                    </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_view() {
    
    // no changes in demo
    demo_error('show_views');

    check_nagios_session_protector();

    $update = grab_request_var('update', false);
    $cancel = grab_request_var('cancel', false);
    if (!$update || $cancel)
        flash_message_cb_and_exit('show_views');

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

    $view_title = encode_html(grab_request_var('view_title', ''));
    $view_url = grab_request_var('view_url', '');

    if (empty($view_title))
        flash_message_cb_and_exit('show_views', _("Title can't be empty!"), 'error');

    if (empty($view_url))
        flash_message_cb_and_exit('show_views', _("URL can't be empty!"), 'error');

    if ($view_id != -1) {

        if (set_view_attr('view_url', $view_url, $view_id) &&
            set_view_attr('view_title', $view_title, $view_id)) {

            flash_message(_('View updated successfully!'));
            show_views(true);
            exit();
        } else {
            flash_message_cb_and_exit('show_views', _('Something went wrong updating view!'), 'error');
        }
    } else {
        if (add_view($view_url, $view_title)) {
            flash_message(_('View added successfully!'));
            show_views(true);
            exit();
        } else {
            flash_message_cb_and_exit('show_views', _('Something went wrong adding view!'), 'error');
        }
    }

    show_views();
}

function delete_the_view() {

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

    check_nagios_session_protector();

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

    if (delete_view($view_id)) {
        flash_message(_('View deleted successfully!'));
        show_views(true);
        exit();
    } else {
        flash_message(_('Something went wrong deleting the view!'), 'error');
    }
    
    show_views();
}