<?php
require_once(dirname(__FILE__) . '/../includes/base.inc.php');
block_non_admins();
block_demo(_('Testing Email'));

route_request();
function route_request() {

    $test = grab_request_var('test');
    if (!empty($test))
        perform_email_test();

    show_email_test();
}


function show_email_test() {

    $email = get_user_attr('email');

    $title = _('Test Email Settings');
    child_page($title);
    echo well_top_page_header($title);

    ?>
    <p>
        <?php echo _('Use this to send a test email to your current logged in user address to verify you can recieve messages from Nagios Fusion.'); ?>
    </p>
    <form method="post" action="">
        <input type="hidden" name="test" value="1">
        <p>
            <?php echo _("An email will be sent to"); ?>: <strong><?php echo $email; ?></strong>
        </p>
        <p>
            <a href="<?php echo get_base_url() . 'account/main.php'; ?>" target="_blank">
                <strong><?php echo _("Change your email address"); ?></strong>
            </a>
        </p>
        <div style="margin-top: 20px;">
            <a href="email.php" class="btn btn-sm btn-default">
                <i class="fa fa-chevron-left"></i> <?php echo _('Back'); ?>
            </a>
            <button type="submit" class="btn btn-sm btn-primary" name="sendbutton">
                <i class="fa fa-paper-plane"></i> <?php echo _('Send Test Email'); ?>
            </button>
        </div>
    </form>

    <?php
}


function perform_email_test() {

    $email = get_user_attr('email');
    $output = array();
    $admin_email = get_option('admin_email');
    $output_type = 'info';

    $subject = _('Nagios Fusion Email Test');
    $message = _('This is a test email from Nagios Fusion.');

    $referer = 'admin/testemail.php';

    $opts = array(
        'from'      => 'Nagios Fusion <' . $admin_email . '>',
        'to'        => $email,
        'subject'   => $subject,
        );

    $opts['message'] = $message;

    $result = send_email($opts, $debug_msg, $referer);

    $output[] = _('A test email was sent to ') . '<strong>' . $email . '</strong>';
    $output[] = '----';
    $output[] = _('Mailer said') . ': <strong>' . $debug_msg . '</strong>';

    // Check for errors
    if ($result == false) {
        $output_type = 'error';
        $output[] = _('An error occurred sending a test email!');
    }
    
    flash_message(implode('<br>', $output), $output_type);
}
