<?php
namespace ONLINE_ADAv4;

use ONLINE_ADAv4\Helper;
use ONLINE_ADAv4\WCAG_Scan;

if( !defined ('ABSPATH') ) exit;

function get_active_scan( $refresh = false ) {
	static $scan = null;

	if ( $scan === null || $refresh ) {
		$scan = new WCAG_Scan( get_option('ada_plugin_current_scan') );

		if ( !$scan || $scan->ID === null ) $scan = false;
	}

	return $scan;
}

function get_queried_scan( $refresh = false ) {
	static $scan = null;

	if ( $scan === null || $refresh ) {
		global $post;
		if ( $post && $post instanceof \WP_Post ) {

            $scan = new WCAG_Scan( $post->ID );
        }
		if ( !$scan || $scan->ID === null ) $scan = false;
	}

	return $scan;
}

/**
 * Receives the "Start Scan" action, and triggers the scan to begin.
 * @param $post_id
 */
function start_scan_on_save( $post_id ) {

	$nonce = empty($_POST['ada_plugin_start_scan']) ? false : stripslashes($_POST['ada_plugin_start_scan']);
	if ( !$nonce || !wp_verify_nonce( $nonce, 'start-scan-' . $post_id ) ) return;

	// nonce matches, this is a legit start scan request.
	$scan = new WCAG_Scan( $post_id );

    $_oadaas_use_query_strings = $_POST["ada_plugin__oadaas_use_query_strings"] == "yes" ? 1 : 0;
    update_post_meta( $post_id, "_oadaas_use_query_strings", $_oadaas_use_query_strings );
    $color_contrast_report = $_POST["ada_plugin__oadaas_include_cbr"] == "yes" ? 1 : 0;
	update_post_meta( $post_id, "_oadaas_include_cbr", $color_contrast_report );
	$snapshot_path = wp_upload_dir()["basedir"] . "/oadaas/snapshot.png";
	$get_snapshot = 1;
	if(file_exists($snapshot_path) && is_file($snapshot_path)){
		$get_snapshot = 0;
	}
	
	update_post_meta($post_id, "_oadaas_get_snapshot", (int)$get_snapshot);
	
	$result = $scan->start_the_scan();

	if ( is_wp_error( $result ) ) {
		wp_die( wp_kses($result,wp_kses_allowed_html()) );
		exit;
	}
}
add_action( 'save_post', __NAMESPACE__.'\\start_scan_on_save', 30 );

/**
 * Saves articles that have been checked off from the list. When all items are checked off, complete the scan.
 *
 * @param $scan_id
 */
function checklist_save_response($scan_id)
{
	if (get_post_type($scan_id) != 'wcag_scan') {
		return;
	}
	if (!isset($_POST['wcag_checklist_action'])) {
		return;
	}

	if ($_POST['wcag_checklist_action'] != 'save-responses') {
		return;
	}

	$completed_items = array();

	$all_articles = Helper::getWcagArticlesModel(2);

    // Save post meta status of items. We don't care if they were checked previously.
	foreach ($all_articles as $index => $article) {
		$index = sanitize_text_field($index);
		$is_checked = !empty($_POST['wcag']['checklist'][$index]);

		if ($is_checked) {
			$completed_items[] = $index;
		}
	}

	update_post_meta($scan_id, '_oadaas_checklist_completed_items', $completed_items);

    // If we completed all items, complete the scan
	if (count($completed_items) == count($all_articles)) {
        // If this scan will schedule another scan, we need to unhook the save_post action so that it doesn't immediately complete the scan that will be created.
		remove_action('save_post', __NAMESPACE__ . '\\checklist_save_response');

		$scan = new WCAG_Scan($scan_id);
		$scan->complete_the_scan();
	}
}
add_action('save_post', __NAMESPACE__ . '\\checklist_save_response');

function get_task_details( $step_key ) {
	$task_description = "Unknown task";
	$task_details = "Wasn't able to find the current task";
	$scan = get_active_scan();

	switch( $step_key ) {
		case 'ada-scan':
			$task_description = 'Auditing your website for compliance issues.';
			$pages_scanned = get_post_meta($scan->ID, "_oadaas_pages_scanned", true);

			if ( empty($pages_scanned) ) {
				$pages_scanned = [];
			}

			$sitemap = Helper::get_sitemap();
			
			$all_pages = combine_sitemap_pages($sitemap, $scan->ID);
			$task_details = "Sitemap contains " . count($all_pages) . " pages. <br>";
			$current_page = get_current_scan_page($sitemap, $pages_scanned, $all_pages);
			if( $current_page != "complete" ){
				$task_details .= "Current page: " . $current_page . "<br>";
				$task_details .= "Pages audited: " . (count($pages_scanned)+1) . " / " . count($all_pages);
			}
			if( $current_page == "complete" ){
				$task_details .= "finished auditing";
			}

			break;
		case 'color-blind-report':
			/* CONDITIONS */
			$include_cbr = (int)get_post_meta($scan->ID, "_oadaas_include_cbr", true);
			$cbr_complete = get_post_meta($scan->ID, "_oadaas_cbr_complete", true);

			/* IF INCLUDE CBR */
			/* IF CBR IS NOT COMPLETED */
			if( $include_cbr && !$cbr_complete ){
				$details = do_cbr($scan);
				$task_description = $details["task_description"];
				$task_details = $details["task_details"];
			}

			if( !$include_cbr && !$cbr_complete ){
				$task_description = "Checking for color blind report";
				$task_details = "Skipping color blind report...";
			}

			break;
		case "scan_finished":
			$task_description = "Audit is complete";
			$task_details = "Redirecting to audit report";
			break;
	}

	return array( $task_description, $task_details );
}

function do_cbr($scan){
	$filter_step = $scan->filter_step;
	$task_description = "Taking a snapshot of your site and creating the color blind report";

	if (empty($filter_step)) {
		$filter_step = 0;
	}

	if ($filter_step == 0) {
		$task_details = "Taking a snapshot of your homepage";
	} else {
		if ($filter_step != 10) {
			$task_details = "Creating filter " . $filter_step . " of " . "9";
		}
		if ($filter_step == 10) {
			$task_details = "Combining filters into 1 pdf";
		}
	}

	return [ "task_description" => $task_description, "task_details" => $task_details ];
}

function get_current_scan_page($sitemap, $pages_scanned, $all_pages = null){
	if(empty($all_pages)){
		$all_pages = [];

		foreach ($sitemap as $k => $v) {
		//$k == "non_query_links
		//$v = array of pages
			foreach ($v as $page) {
				$matches = explode(Plugin::$instance->info["home_url"], sanitize_text_field($page));
				if ($matches[1] === "" || $matches[1] === " ") {
					$matches[1] = "/";
				}
				$all_pages[] = $matches[1];
			}
		}
	}
	if( isset(array_values(array_diff($all_pages, $pages_scanned))[0]) ){
		return array_values(array_diff($all_pages, $pages_scanned))[0];
	}
	return "complete";
}

function combine_sitemap_pages($sitemap, $scan_id){

	$use_qs = get_post_meta($scan_id, "_oadaas_use_query_strings", true);
	//If use query links was selected and there are both query and non-query links, use both
	if( $use_qs && !empty($sitemap["query_links"]) && !empty($sitemap["non_query_links"]) ){
		$all_pages = array_merge( array_values($sitemap["non_query_links"]), array_values($sitemap["query_links"]) );
	}
	//If use query strings was selected and there are query links but no non-query links, just use query links
	if( $use_qs && !empty($sitemap["query_links"]) && empty($sitemap["non_query_links"]) ){
		$all_pages = array_values($sitemap["query_links"]);
	}
	//If don't use query strings OR use query stings but there are no query links and there are non-query links
	if( !$use_qs ||
		( $use_qs && empty($sitemap["query_links"]) ) &&
		!empty($sitemap["non_query_links"])
	){
		$all_pages = array_values($sitemap["non_query_links"]);
	}
	//If there are no query links or non-query links, the sitemap is empty
	if( empty($sitemap["query_links"]) && empty($sitemap["non_query_links"]) ){
		$all_pages = [];
	}

	if( !empty($all_pages) ){
		foreach ($all_pages as $k => $page) {
			$page = sanitize_text_field($page);
			$matches = explode(Plugin::$instance->info["home_url"], $page);
			if ($matches[1] === "" || $matches[1] === " ") {
				$matches[1] = "/";
			}
			$all_pages[$k] = $matches[1];
		}
	}

	return $all_pages;
}

/**
 * Returns an array with all of the step keys that are used by the plugin.
 */
function get_step_keys() {
	$keys = apply_filters( __NAMESPACE__ . '\\step-keys', array(
		'ada-scan',
		'color-blind-report',
		"scan_finished"
	));

	// Re-index the array to ensure we are starting from zero.
	return array_values( $keys );
}

/**
 * Returns an array of the scan progress details, based on the current step.
 *
 * @param $scan
 *
 * @return mixed
 */
function get_step_details( $scan ) {
	$step_keys = get_step_keys();
	$step_key = $scan->current_step;
	$step_index = array_search( $step_key, $step_keys );

	$details = array(
		$step_key,
		$step_index,
		count($step_keys),
	);

	return $details;
}

/**
 * Deletes data out of the oada_scans table when a scan is deleted
 *
 * @param $scan->ID
 *
 * @return void
 */

 function delete_scan_data($id){
	Helper::delete_scan_data($id);
 }
 add_action( 'before_delete_post', __NAMESPACE__.'\\delete_scan_data' );

 function email_admin_on_complete( $scan ){
	$to = get_option("admin_email");
	$subject = "Your audit is complete";
	$message = "Your Accessibility Audit for ".get_site_url()." was completed on " . gmdate( "Y-m-d h:i:s", get_post_meta($scan->ID, "_oadaas_scan-completion-date", true) );

	wp_mail($to, $subject, $message);
 }
 add_action( __NAMESPACE__ . '\\scan-completed', __NAMESPACE__."\\email_admin_on_complete", 10, 1 );

function get_computed_time($sitemap, $include_cbr)
{
	$query_links = !empty($sitemap["query_links"]) ? $sitemap["query_links"] : [];
	$non_query_links = !empty($sitemap["non_query_links"]) ? $sitemap["non_query_links"] : [];
	$total_pages = array_merge($query_links, $non_query_links);

	$total_in_seconds = count($total_pages) * 4;

	if( $include_cbr ){
		//Color blind report takes on average another 2 minutes. 2 minutes * 60 = 120 seconds
		$total_in_seconds += 120;
	}

	$hours_total = $total_in_seconds / 3600;
	$hours = floor($hours_total);
	$hours_dec = $hours_total - $hours;

	$minutes_total = $hours_dec * 60;
	$minutes = floor($minutes_total);
	$minutes_dec = $minutes_total - $minutes;

	$seconds_total = $minutes_dec * 60;
	$seconds = floor($seconds_total);

	if( $hours > 0 ){
		return $hours . " hours, " . $minutes . " minutes, and " . $seconds ." seconds";
	}else if ($minutes > 0) {
		return $minutes . " minutes and " . $seconds . " seconds";
		//return lz($hours) . ":" . lz($minutes) . ":" . lz($seconds);
	} else {
		return " < 1 minute ";
	}
}

add_filter('custom_menu_order', __NAMESPACE__ . '\\plugin_menu_order');

function plugin_menu_order($menu_ord)
{
	if (is_multisite()) return;
	if (!is_user_logged_in() || !is_admin() || !current_user_can("administrator")) {
		return;
	}

	global $submenu;
	if (!isset($submenu["edit.php?post_type=wcag_scan"])) {
		return;
	}

	$menus = [
		"Getting Started",
		"Start Audit",
		"Audit Results",
		"Scheduled Audits",
		"Sitemap",
		"Alt Tag Manager",
		"Guidelines",
		"Community",
		"License",
	];

	if(!Helper::is_pro()){
		$menus[] = "Unlock Full Audit";
	}

	$menus[] = "Get Certified";

	$arr = array();
	foreach ($menus as $menu) {
		foreach ($submenu["edit.php?post_type=wcag_scan"] as $sub) {
			if ($sub[0] == $menu) {
				$arr[] = $sub;
			}
		}
	}
	$submenu["edit.php?post_type=wcag_scan"] = $arr;

	return $menu_ord;
}

add_action("admin_menu", __NAMESPACE__ . "\\external_redirects", 99999999);
function external_redirects()
{
	global $submenu;
	
	if (is_multisite()) return;
	if (!isset($submenu["edit.php?post_type=wcag_scan"])) {
		return;
	}
	if (!is_user_logged_in() || !is_admin() || !current_user_can("administrator")) {
		return;
	}
	$redirects = [
		"Get Certified" => "https://onlineada.com/certification/",
		"Unlock Full Audit" => "https://adaplugin.com/purchase/",
		"Scheduled Audits" => "edit.php?post_status=future&post_type=wcag_scan",
	];

	$redirects = apply_filters(__NAMESPACE__ . "\\oada_redirects", $redirects);
	
	foreach ($redirects as $slug => $link) {
		foreach ($submenu["edit.php?post_type=wcag_scan"] as $index => $sub) {
			if ($sub[0] === $slug) {
				$submenu["edit.php?post_type=wcag_scan"][$index][2] = $link;
			}
		}
	}

}

add_action( "pre_get_posts", __NAMESPACE__ . "\\filter_published" );
function filter_published($ob){
	global $post_type, $pagenow;

	if ( $pagenow == 'edit.php' && $post_type == 'wcag_scan' && !in_array("post_status", array_keys($ob->query_vars) ) ) {
		$ob->set("post_status" , "publish");
	}
}