<?php
namespace ONLINE_ADAv4;
if (!defined('ABSPATH')) exit;

/**
 * If this was a scheduled scan, notify the person set as the reminder contact.
 *
 * These are hooked into the events that switch post status from future to draft/private/publish.
 *
 * @param $post
 */
function remind_on_scan_begin($post){
    if (get_post_type($post->ID) != 'wcag_scan') return;

    $email = get_post_meta($post->ID, '_oadaas-remind-on-start', true);
    $reminder_sent = get_post_meta($post->ID, '_oadaas-reminder-sent', true);

	// Abort if reminder sent already
    if ($reminder_sent) return;

	// Abort if the scan isn't pending
    $scan = new WCAG_Scan($post->ID);
    if ($scan->status != 'pending') return;

	// Start the scan
    $start_scan_result = $scan->start_the_scan();

	// Send an email notification
    if ($email) {
        $subject = 'A new accessibility scan is pending';
        $headers = array('Content-Type: text/html; charset=UTF-8');

        ob_start();
        if (is_wp_error($start_scan_result)) {
			echo "<p>A scheduled scan is now ready. However, the scan could not be started due to an error:</p><br>";

			echo wp_kses("<p>Error Code: <?php echo wp_kses( $start_scan_result->get_error_code(),wp_kses_allowed_html() ); ?></p><br>",wp_kses_allowed_html());

			echo "<p>Error Message:</p><br>";
			echo wp_kses($start_scan_result->get_error_message(),wp_kses_allowed_html());

        } else {
            echo "<p>A scheduled scan has been started, and will soon be ready for your review.</p>";
        }

        echo '<p>';
        edit_post_link('Go to scan', '', '', $post->ID);
        echo '</p>';

        echo "<p><em>This email was sent by the Accessibility Plugin for Wordpress. Your email was set to receive a notification when the scan schedule was triggered.</em></p>";

        wp_mail($email, $subject, ob_get_clean(), $headers);

        // Don't send again for this scan
        update_post_meta($post->ID, '_oadaas-reminder-sent', 1);
    }
}
add_action('future_to_draft', __NAMESPACE__.'\\remind_on_scan_begin', 10, 2);
add_action('future_to_private', __NAMESPACE__ . '\\remind_on_scan_begin', 10, 2);
add_action('future_to_publish', __NAMESPACE__ . '\\remind_on_scan_begin', 10, 2);

/**
 * When a scan which had a schedule becomes completed, make a new scan scheduled in the future. Attach the reminder email to it, and give it the same schedule.
 *
 * @param $scan
 */
function reschedule_scan_on_completion($scan)
{
    $schedule_time = get_post_meta($scan->ID, '_oadaas-schedule-time', true); // Unix timestamp
    if (!$schedule_time) return;

    $schedule = get_post_meta($scan->ID, '_oadaas-schedule', true); // strtotime string, eg: +1 month
    $email = get_post_meta($scan->ID, '_oadaas-schedule-remind-email', true); // Email address, or zero if left blank

	// Create a new scan scheduled in the future.
    $args = array(
        'post_type' => 'wcag_scan',

        'post_title' => 'Audit ' . gmdate('Y-m-d', $schedule_time),

        'post_status' => 'future',
        'edit_date' => 'true',
        'post_date' => gmdate('Y-m-d H:i:s', $schedule_time),
    );

    $post_id = wp_insert_post($args);

    if ($post_id) {
		// Let the old scan know the ID of it's scheduled scan.
        update_post_meta($scan->ID, '_oadaas_next_scheduled_scan_id', $post_id);
        update_post_meta($scan->ID, '_oadaas_next_scheduled_scan_date', $schedule_time);

		// Store the information from the previous scan.
        update_post_meta($post_id, '_oadaas-remind-on-start', $email);

        update_post_meta($post_id, '_oadaas-schedule', $schedule);
        update_post_meta($post_id, '_oadaas-schedule-remind-email', $email);

        $schedule_time = strtotime($schedule);
        if ($schedule_time && (time() < $schedule_time)) {
            update_post_meta($post_id, '_oadaas-schedule-time', $schedule_time);
        }
    }
}
add_action(__NAMESPACE__ . '\\scan-completed', __NAMESPACE__.'\\reschedule_scan_on_completion');


/**
 * Save the date that the next scan should be posted
 *
 * @param $post_id
 */
function save_schedule_setting($post_id)
{
    if (get_post_type($post_id) != 'wcag_scan') return;
    if (!isset($_POST['oadaas-schedule-nonce'])) return;

    $nonce = sanitize_text_field(stripslashes($_POST['oadaas-schedule-nonce']));
    if (!wp_verify_nonce($nonce, 'save-schedule-' . $post_id)) return;

    $schedule = sanitize_text_field(stripslashes($_POST['wcag-scan-schedule']));
    update_post_meta($post_id, '_oadaas-schedule', $schedule);

    $email = sanitize_email(stripslashes($_POST['oadaas-schedule-remind-email']));
    update_post_meta($post_id, '_oadaas-schedule-remind-email', $email ? $email : "0");

	// We need to make sure that the schedule is in the future, otherwise this will repeatedly create new scans.
    $schedule_time = strtotime($schedule);

    if ($schedule_time && (time() < $schedule_time)) {
        update_post_meta($post_id, '_oadaas-schedule-time', $schedule_time);
    } else {
        update_post_meta($post_id, '_oadaas-schedule-time', '');
    }
}
add_action('save_post', __NAMESPACE__.'\\save_schedule_setting');

/**
 * Display the scheduling field for the provided scan
 *
 * @param $scan
 */
function display_schedule_field($scan)
{
    $schedule = get_post_meta($scan->ID, '_oadaas-schedule', true);
    $schedule_time = get_post_meta($scan->ID, '_oadaas-schedule-time', true);
    $email = get_post_meta($scan->ID, '_oadaas-schedule-remind-email', true);

	// The default email should be the admin's email address. But if this is empty, we store a zero. That way we can keep it empty.
    if (!$email) {
        if ($email === "0") $email = "";
        else $email = get_option('admin_email');
    }

    ?>
	<div class="wcag-schedule-field">
		<input type="hidden" name="oadaas-schedule-nonce" value="<?php echo esc_attr(wp_create_nonce('save-schedule-' . $scan->ID)); ?>">

		<p>
			<label for="wcag-scan-schedule">This audit should run</label>
			<select name="wcag-scan-schedule" id="wcag-scan-schedule">
				<option value="" <?php selected($schedule, ''); ?>>Once</option>
				<option value="+1 month" <?php selected($schedule, '+1 month'); ?>>Every month</option>
				<option value="+3 months" <?php selected($schedule, '+3 months'); ?>>Every 3 months</option>
				<option value="+6 months" <?php selected($schedule, '+6 months'); ?>>Every 6 months</option>
				<option value="+1 year" <?php selected($schedule, '+1 year'); ?>>Once per year</option>
			</select>
            <span class="wcag-scan-schedule-reminder-text"> and send a
				<label for="oadaas-schedule-remind-email">reminder email</label> to
				<input type="email" name="oadaas-schedule-remind-email" id="oadaas-schedule-remind-email" placeholder="Email (Optional)" value="<?php echo esc_attr($email); ?>">
			</span>.
			<?php if ($schedule_time) echo "The audit is currently set to run " . esc_html(human_time_diff(time(), $schedule_time)) . " from now."; ?>
		</p>
	</div>
	<?php

}