<?php
//
// Manage scheduled reports that were created by users
// Copyright (c) 2017 Nagios Enterprises, LLC. All rights reserved.
//

require_once(dirname(__FILE__) . '/../../common.inc.php');

// Initialization stuff
pre_init();
init_session();

// Grab GET or POST variables and check pre-reqs
grab_request_vars();
check_prereqs();
check_authentication(false);

if (!is_admin()) {
    die(_("You do not have access to this section."));
}

route_request();

function route_request()
{
    global $request;
    $cmd = grab_request_var('cmd', '');

    switch ($cmd) {

        case 'remove':
            check_nagios_session_protector();
            do_delete_report();
            break;

        case 'copy':
            check_nagios_session_protector();
            show_copy_report();
            break;

        case 'do-copy':
            check_nagios_session_protector();
            do_copy_report();
            break;

        default:
            show_page();
            break;

    }
}

function do_copy_report()
{
    $reports = grab_request_var("reports", array());
    $users = grab_request_var("users", array());
    $user_id = intval(grab_request_var("user_id", 0));
    $length = intval(grab_request_var("length", 10));

    // If empty, go back
    if (empty($reports) || empty($users)) {
        header("Location: manage.php?user_id=".$user_id."&length=".$length);
    }

    // For each user apply the reports
    foreach ($users as $u) {
        $email = get_user_attr($u, "email");
        
        // For each report, create a copy and save it for the user
        foreach ($reports as $rid => $uid) {
            $report = scheduledreporting_component_get_report_id($rid, $uid);
            $report['recipients'] = $email;

            // Add report, update cron
            $id = scheduledreporting_component_add_report($report, $u);
            scheduledreporting_component_update_cron($id, $u);
        }
    }

    // Return to the main page
    flash_message(_("Report(s) have been copied to the user(s) selected."));
    header("Location: manage.php?user_id=".$user_id."&length=".$length);
}

function show_copy_report()
{
    $reports = grab_request_var("reports", array());
    $user_id = intval(grab_request_var("user_id", 0));
    $length = intval(grab_request_var("length", 10));

    // If empty, go back
    if (empty($reports)) {
        header("Location: manage.php?user_id=".$user_id."&length=".$length);
    }

    // Get all reports
    $scheduled_reports = array();
    foreach ($reports as $rid => $uid) {
        $scheduled_reports[$rid] = scheduledreporting_component_get_report_id($rid, $uid);
    }

    // Get all users
    $users = get_users();

    do_page(array("page_title" => _('Copy Scheduled Reports'), "enterprise" => true), true);
    ?>

    <h1><?php echo _('Copy Scheduled Report'); ?></h1>

    <p style="margin-top: 10px;"><?php echo _("The following report(s) will be copied:"); ?></p>

    <table class="table table-condensed table-bordered table-striped table-auto-width">
        <thead>
            <tr>
                <th><?php echo _("Report Name"); ?></th>
                <th><?php echo _("User"); ?></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($scheduled_reports as $id => $report) { ?>
        <tr>
            <td><?php echo encode_form_val($report['name']); ?></td>
            <td><?php echo get_user_attr($report['user_id'], 'username'); ?></td>
        </tr>
        <?php } ?>
        </tbody>
    </table>

    <h2><?php echo _("Select User(s)"); ?></h2>

    <p><?php echo _("Select the user(s) you would like to copy the selected reports to."); ?><br><?php echo _("The report's <b>recipient email</b> will be set to the email address of the user the scheduled report is copied to."); ?></p>

    <form method="post">
        <input type="hidden" name="cmd" value="do-copy">
        <input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
        <input type="hidden" name="length" value="<?php echo $length; ?>">
        <?php foreach ($scheduled_reports as $id => $report) { ?>
        <input type="hidden" name="reports[<?php echo $id; ?>]" value="<?php echo $report['user_id']; ?>">
        <?php } ?>
        <?php echo get_nagios_session_protector(); ?>
        <div>
            <select name="users[]" style="width: 300px;" size="12" multiple>
                <?php foreach ($users as $user) { ?>
                <option value="<?php echo $user['user_id']; ?>"><?php echo $user['username']; ?> (<?php echo $user['name']; ?>)</option>
                <?php } ?>
            </select>
        </div>
        <div style="margin-top: 20px;">
            <button type="submit" class="btn btn-sm btn-primary"><?php echo _("Copy"); ?></button>
            <a href="manage.php?user_id=<?php echo $user_id; ?>&length=<?php echo $length; ?>" class="btn btn-sm btn-default"><?php echo _("Cancel"); ?></a>
        </div>
    </form>

    <?php
    do_page_end(true);
}

function do_delete_report()
{
    $reports = grab_request_var("reports", array());
    $user_id = intval(grab_request_var("user_id", 0));
    $length = intval(grab_request_var("length", 10));

    // Verify that report and user ID is set
    if (empty($reports)) {
        flash_message(_("Report could not be found."), FLASH_MSG_ERROR);
        header("Location: manage.php?user_id=".$user_id."&length=".$length);
    }

    // Remove the report
    foreach ($reports as $rid => $uid) {
        scheduledreporting_component_delete_report($rid, $uid);
    }

    flash_message(_("Report removed successfully."));
    header("Location: manage.php?update=1&user_id=".$user_id."&length=".$length);
}

function show_page()
{
    $update = grab_request_var("update", 0);
    $page = intval(grab_request_var("page", 1));
    $length = intval(grab_request_var("length", 10));
    if ($length < 5) { $length = 5; }

    // Check for filters
    $user_id = intval(grab_request_var("user_id", 0));
    $offset = 0;

    // Get a list of all scheduled reports of users
    $scheduled_reports = array();
    if (empty($user_id)) {
        $scheduled_reports = scheduledreporting_component_get_all_reports();
    } else {
        $scheduled_reports = scheduledreporting_component_get_reports($user_id);
    }

    // Do paging stuff
    $total = count($scheduled_reports);
    $pages = ceil($total / $length);

    // Set page to max
    if ($page > $pages+1) {
        $page = $pages;
    }

    $offset = ($page - 1) * $length;
    $max = $offset + $length;
    if ($max > $total) { $max = $total; }

    // Sort the array (natural str compare on 'name' of report)
    uasort($scheduled_reports, function($a, $b) { return strnatcmp($a['name'], $b['name']); });
    $scheduled_reports = array_slice($scheduled_reports, $offset, $length);

    // Grab users
    $users = get_users();

    // Do actual enterprise only check
    make_enterprise_only_feature();

    // Enterprise Edition message
    if (get_theme() != 'xi5') {
        echo enterprise_message();
    }

    do_page(array("page_title" => _('Scheduled Reports'), "enterprise" => true), true);
    ?>

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

        // Do form submit if we delete/clone multiple reports
        $('#multi-cmd').change(function() {
            var val = $(this).val();

            // Don't do anything if we don't have anything checked
            if ($('.sel-checkbox:checked').length == 0) {
                $('#multi-cmd').val('');
                return;
            }

            $('.cmd-input').val(val);
            if (val != "") {
                if (val == "remove") {
                    
                    if (!confirm("<?php echo _("Are you sure you want to delete these reports? This cannot be undone."); ?>")) {
                        return;
                    }
                }
                $('form.multi-form').submit();
            }
        });

        // Update number of records
        $('.num-records').change(function() {
            var num = $(this).val();
            $('.num-records').val(num);
            $('input[name="length"]').val(num);
            $('form.filter').submit();
        });

        // Update the report sidebar if we need to
        <?php if ($update) { ?>
        if ($('#leftnav div.menusectiontitle[data-id="menu-reports-scheduledreportings"]', window.parent.document).length) {
            $.get('<?php echo get_base_url(); ?>includes/components/scheduledreporting/schedulereport.php', { 'getajaxdata': 1 }, function(data) {
                $('#leftnav div.menusectiontitle[data-id="menu-reports-scheduledreportings"]', window.parent.document).eq(0).parent().find('ul.menusection').html(data.html);
                $('#leftnav div.menusectiontitle[data-id="menu-reports-scheduledreportings"] span.num', window.parent.document)[0].innerHTML = '('+data.count+')';
            }, 'json');
        }
        <?php } ?>

    });
    </script>

    <form class="filter" method="get">
        <input type="hidden" name="length" value="<?php echo $length; ?>">
        <div class="well report-options">
            <div class="fl">
                <h1><?php echo _('Scheduled Reports'); ?></h1>
            </div>
            <div class="fl form-inline" style="margin-left: 20px;">
                <div class="input-group">
                    <label class="input-group-addon"><?php echo _("User"); ?></label>
                    <select name="user_id" class="form-control">
                        <option value=""></option>
                        <?php foreach ($users as $user) { ?>
                        <option value="<?php echo $user['user_id']; ?>"<?php if ($user['user_id'] == $user_id) { echo ' selected'; } ?>><?php echo $user['username']; ?></option>
                        <?php } ?>
                    </select>
                </div>
                <button type="submit" class="btn btn-sm btn-default"><i class="fa fa-filter"></i> <?php echo _("Filter"); ?></button>
            </div>
            <div class="clear"></div>
        </div>
    </form>

    <div style="margin-bottom: 20px;">
        <div class="fl" style="line-height: 26px;">
            <?php echo _("Showing") . " " . ($offset+1) . "-" . $max . " " . _("of") . " " . $total . " " . _("scheduled reports"); ?>
        </div>
        <div class="fr">
            <select class="form-control condensed num-records">
                <option value="5" <?php if ($length == 5) { echo 'selected'; } ?>><?php echo _("5 Per Page"); ?></option>
                <option value="10" <?php if ($length == 10) { echo 'selected'; } ?>><?php echo _("10 Per Page"); ?></option>
                <option value="25" <?php if ($length == 25) { echo 'selected'; } ?>><?php echo _("25 Per Page"); ?></option>
                <option value="50" <?php if ($length == 50) { echo 'selected'; } ?>><?php echo _("50 Per Page"); ?></option>
                <option value="100" <?php if ($length == 100) { echo 'selected'; } ?>><?php echo _("100 Per Page"); ?></option>
            </select>
        </div>
        <div class="fr">
            <a href="?page=1&length=<?php echo $length; ?>&user_id=<?php echo $user_id; ?>" class="btn btn-xs btn-default" title="<?php echo _('First Page'); ?>"><i class="fa fa-fast-backward"></i></a>
            <a href="?page=<?php echo $page-1; ?>&length=<?php echo $length; ?>&user_id=<?php echo $user_id; ?>" <?php if ($page == 1) { echo 'disabled'; } ?> class="btn btn-xs btn-default" title="<?php echo _('Previous Page'); ?>"><i class="fa fa-chevron-left"></i></a>
            <span style="margin: 0 10px;"><?php echo _("Page") . " " . $page . " " . _("of") . " " . $pages; ?></span>
            <a href="?page=<?php echo $page+1; ?>&length=<?php echo $length; ?>&user_id=<?php echo $user_id; ?>" <?php if ($page >= $pages) { echo 'disabled'; } ?> class="btn btn-xs btn-default" title="<?php echo _('Previous Page'); ?>"><i class="fa fa-chevron-right"></i></a>
            <a href="?page=<?php echo $pages; ?>&length=<?php echo $length; ?>&user_id=<?php echo $user_id; ?>" class="btn btn-xs btn-default" title="<?php echo _('Last Page'); ?>"><i class="fa fa-fast-forward"></i></a>
        </div>
        <div class="clear"></div>
    </div>

    <form class="multi-form" method="post">
        <input type="hidden" class="cmd-input" name="cmd" value="">
        <input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
        <?php echo get_nagios_session_protector(); ?>

    <table class="table table-condensed table-bordered table-striped">
        <thead>
            <tr>
                <th style="width: 30px;"></th>
                <th><?php echo _("Report Name"); ?></th>
                <th><?php echo _("User"); ?></th>
                <th><?php echo _("Frequency"); ?></th>
                <th><?php echo _("Recipients"); ?></th>
                <th><?php echo _("Type") ?></th>
                <th style="width: 60px; text-align: center;"><?php echo _("Actions"); ?></th>
            </tr>
        </thead>
        <tbody>
            <?php
            if (count($scheduled_reports) > 0) {
                foreach ($scheduled_reports as $id => $report) {
                    if (empty($report['type'])) { $report['type'] = _('Report'); }
                    $sched = grab_array_var($report, "schedule", array());
                    $hour = grab_array_var($sched, "hour", "");
                    $minute = grab_array_var($sched, "minute", "");
                    $ampm = grab_array_var($sched, "ampm", "");
                    $dayofweek = grab_array_var($sched, "dayofweek", "");
                    $dayofmonth = grab_array_var($sched, "dayofmonth", "");

                    $frequency = $report['frequency'];
                    $days = array(
                        0 => _('Sunday'),
                        1 => _('Monday'),
                        2 => _('Tuesday'),
                        3 => _('Wednesday'),
                        4 => _('Thursday'),
                        5 => _('Friday'),
                        6 => _('Saturday'),
                    );

                    if ($frequency == "Disabled") {
                        $fstr = "";
                    } else if ($frequency == "Once") {
                        $fstr = "(" . _("Pending") . ")";
                    } else {
                        $fstr = $hour . ":" . $minute . " " . $ampm;
                    }
                    
                    if ($frequency == "Weekly") {
                        $fstr .= " " . $days[$dayofweek];
                    } else if ($frequency == "Monthly") {
                        $fstr .= ", " . _("Day") . " " . $dayofmonth;
                    }
                ?>
                <tr>
                    <td style="text-align: center;">
                        <input type="checkbox" class="sel-checkbox" name="reports[<?php echo $id; ?>]" value="<?php echo $report['user_id']; ?>">
                    </td>
                    <td><a href="<?php echo "schedulereport.php?edit=1&userid=" . $report['user_id'] . "&length=" . $length . "&id=" . urlencode($id) . "&nsp=" . get_nagios_session_protector_id(); ?>"><?php echo $report['name']; ?></a></td>
                    <td><?php echo get_user_attr($report['user_id'], 'username'); ?></td>
                    <td><?php echo encode_form_val($frequency) . " @ " . $fstr; ?></td>
                    <td><?php echo str_replace(",", ", ", encode_form_val($report['recipients'])) ?></td>
                    <td><?php echo ucfirst($report['type']); ?></td>
                    <td style="text-align: center;">
                        <a href="manage.php?cmd=copy&reports[<?php echo $id; ?>]=<?php echo $report['user_id']; ?>&user_id=<?php echo $user_id; ?>&length=<?php echo $length; ?>&nsp=<?php echo get_nagios_session_protector_id(); ?>" class="tt-bind" data-placement="left" title="<?php echo _("Copy report"); ?>"><img src="<?php echo get_icon_url("page_copy.png"); ?>"></a>&nbsp;
                        <a href="manage.php?cmd=remove&reports[<?php echo $id; ?>]=<?php echo $report['user_id']; ?>&user_id=<?php echo $user_id; ?>&length=<?php echo $length; ?>&nsp=<?php echo get_nagios_session_protector_id(); ?>" class="tt-bind" data-placement="left" title="<?php echo _("Remove"); ?>"><img src="<?php echo get_icon_url("cross.png"); ?>"></a>
                    </td>
                </tr>
            <?php
                }
            } else {
            ?>
            <tr>
                <td colspan="7"><?php echo _("No scheduled reports for the filters selected."); ?></td>
            </tr>
            <?php } ?>
        </tbody>
    </table>

    <div style="margin-top: 20px;">
        <div class="fl form-inline">
            <div class="input-group">
                <label class="input-group-addon"><?php echo _("With selected"); ?></label>
                <select id="multi-cmd" class="form-control">
                    <option></option>
                    <option value="copy"><?php echo _("Copy"); ?></option>
                    <option value="remove"><?php echo _("Remove"); ?></option>
                </select>
            </div>
        </div>
        <div class="fr">
            <select class="form-control condensed num-records">
                <option value="5" <?php if ($length == 5) { echo 'selected'; } ?>><?php echo _("5 Per Page"); ?></option>
                <option value="10" <?php if ($length == 10) { echo 'selected'; } ?>><?php echo _("10 Per Page"); ?></option>
                <option value="25" <?php if ($length == 25) { echo 'selected'; } ?>><?php echo _("25 Per Page"); ?></option>
                <option value="50" <?php if ($length == 50) { echo 'selected'; } ?>><?php echo _("50 Per Page"); ?></option>
                <option value="100" <?php if ($length == 100) { echo 'selected'; } ?>><?php echo _("100 Per Page"); ?></option>
            </select>
        </div>
        <div class="fr">
            <a href="?page=1&length=<?php echo $length; ?>&user_id=<?php echo $user_id; ?>" class="btn btn-xs btn-default" title="<?php echo _('First Page'); ?>"><i class="fa fa-fast-backward"></i></a>
            <a href="?page=<?php echo $page-1; ?>&length=<?php echo $length; ?>&user_id=<?php echo $user_id; ?>" <?php if ($page == 1) { echo 'disabled'; } ?> class="btn btn-xs btn-default" title="<?php echo _('Previous Page'); ?>"><i class="fa fa-chevron-left"></i></a>
            <span style="margin: 0 10px;"><?php echo _("Page") . " " . $page . " " . _("of") . " " . $pages; ?></span>
            <a href="?page=<?php echo $page+1; ?>&length=<?php echo $length; ?>&user_id=<?php echo $user_id; ?>" <?php if ($page >= $pages) { echo 'disabled'; } ?> class="btn btn-xs btn-default" title="<?php echo _('Previous Page'); ?>"><i class="fa fa-chevron-right"></i></a>
            <a href="?page=<?php echo $pages; ?>&length=<?php echo $length; ?>&user_id=<?php echo $user_id; ?>" class="btn btn-xs btn-default" title="<?php echo _('Last Page'); ?>"><i class="fa fa-fast-forward"></i></a>
        </div>
        <div class="clear"></div>
    </div>

    </form>

    <?php
    do_page_end(true);
}