<?php

namespace ONLINE_ADAv4;

use ONLINE_ADAv4\Plugin;
use ONLINE_ADAv4\WCAG_Scan;
if ( !defined( 'ABSPATH' ) ) exit;

/**
 * Register the scan post type, as a menu titled "Accessibility"
 */
function ada_register_post_type() {

	$args = array(
		'label'                 => 'Accessibility Audit',
		'description'           => 'Auditing results from the Ability, Inc Web Accessibility Plugin',
		'labels'                => array(
			'name'                  => 'Accessibility Audits',
			'singular_name'         => 'Accessibility Audit',
			'menu_name'             => 'Accessibility Suite',
			'name_admin_bar'        => 'Accessibility Auditer',
			'archives'              => 'Audit Results',
			'parent_item_colon'     => 'Parent Audit Result:',
			'all_items'             => 'Audit Results',
			'add_new_item'          => 'Start New Audit',
			'add_new'               => 'Start Audit',
			'new_item'              => 'New Audit',
			'edit_item'             => 'View Audit Result',
			'update_item'           => 'Update Audit Result',
			'view_item'             => 'View Audit Result',
			'search_items'          => 'Search Audit Results',
			'not_found'             => 'No audits have been recorded yet. Would you like to <a href="'. admin_url('post-new.php?post_type=wcag_scan') . '">start a new audit</a>?',
			'not_found_in_trash'    => 'Not found in Trash',
			'featured_image'        => 'Featured Image',
			'set_featured_image'    => 'Set featured image',
			'remove_featured_image' => 'Remove featured image',
			'use_featured_image'    => 'Use as featured image',
			'insert_into_item'      => 'Insert into audit result',
			'uploaded_to_this_item' => 'Uploaded to this audit result',
			'items_list'            => 'Audit result list',
			'items_list_navigation' => 'Audit result list navigation',
			'filter_items_list'     => 'Filter audit results',
		),
		'supports'              => array( 'title' ),
		'hierarchical'          => false,
		'public'                => true,
		'show_ui'               => true,
		'show_in_menu'          => true,
		'menu_position'         => 101,
		'menu_icon'             => 'dashicons-universal-access',
		'show_in_admin_bar'     => true,
		'show_in_nav_menus'     => false,
		'can_export'            => false,
		'has_archive'           => false,
		'exclude_from_search'   => true,
		'publicly_queryable'    => false,
		'rewrite'               => false,
		'capability_type'       => 'page',
	);

	register_post_type( 'wcag_scan', $args );
}
add_action( 'init', __NAMESPACE__.'\\ada_register_post_type', 5 );

/**
 * Disable autosave functionality for scans to prevent drafts from being created.
 */
function disable_autosave_for_post_type() {
	if ( 'wcag_scan' == get_post_type() ) wp_dequeue_script( 'autosave' );
}
add_action( 'admin_enqueue_scripts', __NAMESPACE__ . '\\disable_autosave_for_post_type', 15 );

/**
 * Register meta boxes to show on scanning pages
 */
function register_metaboxes() {
	$this_scan = get_queried_scan();

	if ( !$this_scan ) return;
	$current_screen = get_current_screen();

	$screen = 'wcag_scan';
	$meta_boxes = array(
		'info' => array(
			'name' => 'Audit Information',
			'cb' => __NAMESPACE__ . '\\display_info_metabox',
			'seamless' => false,
		),
        'progress' => array(
			'name' => 'Audit Progress',
			'cb' => __NAMESPACE__ . '\\display_progress_metabox',
			'seamless' => true,
		),
        'scan-options' => array(
            'name' => 'Audit Options',
            'cb'   => __NAMESPACE__.'\\display_scan_options_metabox',
            'seamless' => false,
		),
		// Step 3: Self-Assessment compliance checklist
		'checklist' => array(
			'name' => 'Self-Assessment Compliance Checklist',
			'cb' => __NAMESPACE__ . '\\display_checklist_metabox',
			'seamless' => false
		),
		// Scan Report
		'scan-report' => array(
			'name' => 'Audit Report',
			'cb' => __NAMESPACE__ . '\\display_scan_report',
			'seamless' => false
		),
	);

    // Only show the information metabox when the scan is pending.
    if ( $this_scan->status != "pending" ) {
        unset($meta_boxes['info']);
        unset($meta_boxes['scan-options']);
	}

	if( $this_scan->status != "complete" || $screen !== "wcag_scan" ){
		unset($meta_boxes["scan-report"]);
	}

	//Don't show the scan options if another scan is currently active
	//Get current scan will always return something because the current scan ID only gets updated when a new scan starts

	$current_scan = get_active_scan();
	if( !empty($current_scan) ){
		if ($current_scan->status == "in-progress") {
			unset($meta_boxes['scan-options']);
		}
	}

	if ($this_scan->status != 'in-progress' || $this_scan->current_step != 'checklist') { unset($meta_boxes['checklist']); }

	// Don't show the scan progress metabox outside of the scan page if it has been completed, and dismissed.
	if ( $this_scan->status == "complete" && $this_scan->is_dismissed() && $current_screen->base != "post" ) {
		unset($meta_boxes['progress']);
	}

    foreach($meta_boxes AS $id => $params){
        add_meta_box( $screen . '_' . $id, $params['name'], $params['cb'], $screen, 'normal', 'high' );

        // add the "wcag_box" so we can know the metabox is from our plugin without referencing ids
    	add_filter( "postbox_classes_{$screen}_{$screen}_{$id}",  __NAMESPACE__ . '\\metabox_class' );

        // add the "wcag-seamless" class, which removes the "boxed" appearance from the metabox using css.
    	if ( !empty($params['seamless']) ) {
    		add_filter( "postbox_classes_{$screen}_{$screen}_{$id}", __NAMESPACE__ . '\\metabox_class_seamless' );
    	}
    }
}
add_action( 'add_meta_boxes', __NAMESPACE__ . '\\register_metaboxes', 400 );

function display_free_banner(){
    include(Plugin::$instance->info["path"] . "templates/partials/banner.php");
}
/**
 * Displays information regarding progress of the scan. This may be a start scan button if it is not started, the current progress if in progress, or the results if completed.
 */
function display_progress_metabox() {
	include(Plugin::$instance->info["path"] . 'templates/partials/progress.php');
}

/**
 * Displays the scan options to be included with the scan.
 */
function display_scan_options_metabox() {
	include(Plugin::$instance->info["path"] . 'templates/partials/scan-options.php');
}

/**
 * Displays information about what the scan will be doing.
 */
function display_info_metabox() {
	include(Plugin::$instance->info["path"] . 'templates/partials/scan-information.php');
}

/**
 * Displays form for the step "checklist".
 */
function display_checklist_metabox(){
	include(Plugin::$instance->info["path"] . 'templates/step-3-checklist.php');
	wcag_self_assessment_checklist_form(); // see: guidelines.php
}

/**
 * Display the scan report
 */
function display_scan_report(){
	include(Plugin::$instance->info["path"] . 'templates/partials/scan-report.php');
}

/**
 * Adds a class to the metabox to represent a normal metabox. This is to contrast against the seamless layout.
 *
 * @param $classes
 * @return array
 */
function metabox_class( $classes ) {
	$classes[] = "wcag_box";
	return $classes;
}

/**
 * Adds a class to the metabox which is used to make the metabox look seamless - by removing the background, border, and the title/handle.
 *
 * @param $classes
 * @return array
 */
function metabox_class_seamless( $classes ) {
	$classes[] = "wcag_seamless";
	return $classes;
}

/**
 * Displays the scan status next to the name of the scan.
 *
 * @param $post_states
 * @param $post
 *
 * @return array
 */
function display_scan_state_near_title( $post_states, $post ) {
	if ( $post->post_type == "wcag_scan" ) {
		$scan = new WCAG_Scan( $post->ID );

		if ( !$post_states ) $post_states = array();

		if ( $scan->status == "in-progress" ) {
			$m = get_task_details( $scan->current_step );
			$message = wp_strip_all_tags(str_replace(array("\r", "\n"), " ", $m[1]));

			switch($scan->current_step){
				case "ada-scan":

					break;
				case "color-blind-report":
					break;
			}

			if ( $scan->current_step == "ada-scan" || $scan->current_step == "color-blind-report" ) {
				$post_states[] = "In Progress:<br>" . $message;
			}
			if( $scan->current_step == "checklist" ){
				$post_states[] = "Waiting for your input:<br>" . $message;
			}
		}else{
			$post_states[] = ucwords( str_replace( array('-', '_'), ' ', 'Audit ' . $scan->status ) );
		}
	}

	return $post_states;
}
add_filter( 'display_post_states', __NAMESPACE__ . '\\display_scan_state_near_title', 25, 2 );

/**
 * Only allow saving scans as published or future. There is no reason to use drafts or private listings.
 *
 * @param $post_id
 */
function save_scan_as_published( $post_id ) {
	if ( get_post_type( $post_id ) !== "wcag_scan" ) return;
	if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return;

	remove_action( 'save_post', __NAMESPACE__ . '\\save_scan_as_published' );

	$post = get_post( $post_id );

	$args = array(
		'ID' => $post_id
	);

	// Note: 'future' is omitted
	if ( in_array( $post->post_status, array('draft', 'pending', 'private') ) ) $args['post_status'] = 'publish';
	if ( $post->post_password ) $args['post_password'] = '';

	if ( count($args) > 1 ) wp_update_post( $args );

	add_action( 'save_post', __NAMESPACE__ . '\\save_scan_as_published' );
}
add_action( 'save_post', __NAMESPACE__ . '\\save_scan_as_published' );
