<?php
/**
 * Get the document setting base on the given option name.
 *
 * @param string $name
 * @param string $default
 *
 * @return string
 */
function doc8_get_setting( $name, $default = '' ) {
	$options = get_option( 'doc8_settings' );

	if ( empty($options) || empty($options[$name])) {
		return $default;
	}

	return $options[$name];
}

/**
 * Returns the custom post type slug use in registration.
 *
 * @return string
 */
function doc8_get_post_type() {
	return 'docu';
}

/**
 * Returns the custom post type slug use to compose the document permalink.
 *
 * @since 1.0.0
 */
function doc8_get_post_type_slug() {
	return doc8_get_setting( 'doc8_slug', 'doc' );
}

/**
 * Returns the custom category slug use to compose the document permalink.
 *
 * @return mixed
 */
function doc8_get_category_slug() {
	return doc8_get_setting( 'doc8_category_slug', 'category' );
}

/**
 * Register custom post type and custom taxonomies.
 *
 * @since 1.0.0
 */
function doc8_register() {
	$name = __( 'Document', 'docu' );

	register_post_type( doc8_get_post_type(), array(
		'hierarchical' => true,
		'labels'       => array(
			'name'          => 'DoC8', // Don't translate the main name
			'singular_name' => $name,
			'edit_item'     => $name,
			'add_new_item'  => __( 'New Document', 'docu' ),
			'new_item'      => __( 'New Document', 'docu' ),
			'all_items'     => __( 'Documents', 'docu' ),
		),
		'public'          => true,
		'show_ui'         => true,
		'has_archive'     => true,
		'capability_type' => 'page',
		'menu_icon'       => 'dashicons-pressthis',
		'supports'        => array(
			'title',
			'editor',
			'slug',
			'page-attributes',
			'thumbnail',
		),
		'rewrite' => array(
			'slug'       => doc8_get_post_type_slug(),
			'with_front' => false,
		),
		'register_meta_box_cb' => 'doc8_meta_boxes',
	) );
}

/**
 * Check if the current page is of doc8 type.
 *
 * @return bool
 */
function is_doc8() {
	return get_post_type() == doc8_get_post_type();
}

/**
 * Check if the current page is of search type.
 *
 * @return mixed
 */
function is_doc8_search() {
	global $wp_query;

	$is_search = $wp_query->get( 'doc8_search' );

	return $is_search;
}

/**
 * Returns the selected document template.
 *
 * @param $template
 *
 * @return mixed
 */
function doc8_page_template( $template ) {
	$is_search = is_doc8_search();

	if ( ! is_doc8() && ! $is_search ) {
		return $template;
	}

	$doc_template = doc8_get_setting( 'doc8_template', '' );

	if ( ! $is_search && ( empty($doc_template) || 'default' == $doc_template ) ) {
		return $template;
	}

	if ( $is_search ) {
		$tpl = 'document-searchresults.php';

		$theme_template = locate_template( $tpl );

		if ( $theme_template ) {
			return $theme_template;
		}

		if ( 'standard' == $doc_template ) {
			$theme_template = doc8()->get_plugin_path() . 'templates/search-standard.php';

			return $theme_template;
		}
	}

	if ( is_archive() ) {
		$tpl = 'archive-' . doc8_get_post_type() . '.php';

		$theme_template = locate_template( $tpl );

		if ( $theme_template ) {
			return $theme_template;
		}

		if ( 'standard' == $doc_template ) {
			$template = doc8()->get_plugin_path() . 'templates/archive-standard.php';

			return $template;
		}
	}

	if ( is_singular() ) {
		$tpl = 'single-' . doc8_get_post_type() . '.php';

		$theme_template = locate_template( $tpl );

		if ( $theme_template ) {
			return $theme_template;
		}

		if ( 'standard' == $doc_template ) {
			$template = doc8()->get_plugin_path() . 'templates/single-standard.php';

			return $template;
		}
	}

	return $template;
}

/**
 * Get the document heading title on documents pages.
 *
 * @param string $title
 *
 * @return string
 */
function doc8_get_heading_title( $title = '' ) {
	if ( ! is_doc8() && ! is_doc8_search() ) {
		return $title;
	}

	return doc8_get_setting( 'doc8_heading_title', '' );
}

/**
 * Print the document heading title.
 *
 * @since 1.0.0
 */
function doc8_heading_title() {
	echo doc8_get_heading_title();
}

/**
 * Get the document tagline on document pages.
 *
 * @param string $desc
 *
 * @return string
 */
function doc8_get_heading_description( $desc = '' ) {
	if ( ! is_doc8() && ! is_doc8_search() ) {
		return $desc;
	}

	return doc8_get_setting( 'doc8_heading_tagline' );
}

/**
 * Print the document heading description.
 *
 * @since 1.0.0
 */
function doc8_heading_description() {
	echo doc8_get_heading_description();
}

/**
 * Filter query results base on document settings.
 *
 * @param $wp_query
 *
 * @return mixed
 */
function doc8_pre_get_documents( $wp_query ) {
	$post_type = $wp_query->get( 'post_type' );

	if ( ! $wp_query->is_main_query() || ! $wp_query->is_archive() || $post_type != doc8_get_post_type() ) {
		return $wp_query;
	}

	$per_page = doc8_get_setting( 'doc8_per_page', 20 );
	$wp_query->set( 'posts_per_page', $per_page );

	$search = doc8_get_search_term();
	if ( ! empty($search) && $wp_query->is_post_type_archive( doc8_get_post_type() ) ) {
		$wp_query->set( 's', doc8_get_search_term() );
		$wp_query->set( 'doc8_search', true );

		return $wp_query;
	}

	$wp_query->set( 'post_parent', 0 );

	return $wp_query;
}

/**
 * Filter the documents order sequence base on preferred settings.
 *
 * @param $orderby
 * @param $wp_query
 *
 * @return string
 */
function doc8_documents_orderby( $orderby, $wp_query ) {
	global $wpdb;

	$post_type = $wp_query->get( 'post_type' );

	if ( $post_type != doc8_get_post_type() ) {
		return $orderby;
	}

	$orderby = doc8_get_setting( 'doc8_orderby', 'menu_order' );
	$order = doc8_get_setting( 'doc8_order', 'asc' );

	$orderby = " {$wpdb->posts}.{$orderby} {$order}";

	return $orderby;
}

/**
 * Outputs the document template base on the given name.
 *
 * @param string $name
 */
function doc8_get_template_part( $name ) {
	// Check the theme templates, it may have been overriden
	$theme_template = locate_template( $name . '.php' );

	if ( $theme_template ) {
		require $theme_template;

		return;
	}

	// Check the templates directory inside the theme
	$theme_template = locate_template( 'templates/' . $name . '.php' );
	if ( $theme_template ) {
		require $theme_template;

		return;
	}

	// Use the default templates
	$path = doc8()->get_plugin_path() . '/templates/';
	$template = $path . $name . '.php';

	if ( file_exists( $template ) && is_readable( $template ) ) {
		require $template;
	}
}

/**
 * Get the top most parent of the given document object.
 *
 * @param WP_Post $post
 *
 * @return mixed
 */
function doc8_get_parent_post( $post ) {
	if ( ! $post->post_parent || 0 == $post->post_parent ) {
		return $post;
	}

	$parent = get_post( $post->post_parent );

	if ( is_wp_error( $parent ) ) {
		return $post;
	}

	if ( $parent->post_parent > 0 ) {
		$parent = doc8_get_parent_post( $parent );
	}

	return $parent;
}

/**
 * Iterate the given list of documents.
 *
 * @param array $list
 * @param bool $hierarchical
 *
 * @return string
 */
function doc8_get_document_list( $list = array(), $hierarchical = true ) {
	global $post;

	if ( ! is_doc8() || empty($list) ) {
		return '';
	}

	$post_parent = doc8_get_parent_post( $post );
	$items = array();
	$format = '<a href="%1$s" rel="bookmark">%2$s</a>';
	foreach ( $list as $doc ) {
		$link = sprintf( $format, $doc['url'], $doc['title'] );

		if ( $hierarchical && ! empty($doc['children']) ) {
			$link .= doc8_get_document_list( $doc['children'], $hierarchical );
		}

		$class = '';

		if ( $post && $doc['ID'] == $post->ID ) {
			$class = 'active';
		}

		if ( $post_parent && $post_parent->ID == $doc['ID'] ) {
			$class = 'active';
		}

		$item = sprintf( '<li class="%1$s">%2$s</li>', $class, $link );

		array_push( $items, $item );
	}

	return sprintf( '<ul>%s</ul>', implode( ' ', $items ) );
}

/**
 * Outputs the list of documents.
 */
function doc8_document_list() {
	$list = doc8_get_children(0, true );

	echo doc8_get_document_list( $list );
}

/**
 * Get the list of documents base on the given parent ID.
 *
 * @param int $parent_id
 * @param bool $hierarchy
 *
 * @return array
 */
function doc8_get_children( $parent_id, $hierarchy = false ) {
    $docs = get_posts( array(
        'post_type'        => doc8_get_post_type(),
        'post_parent'      => $parent_id,
        'posts_per_page'   => -1,
        'suppress_filters' => true,
        'orderby'          => doc8_get_setting( 'doc8_orderby', 'menu_order' ),
        'order'            => doc8_get_setting( 'doc8_order', 'asc' ),
    ) );

    $lists = array();

    foreach ( $docs as $doc ) {
        $list = array(
            'ID'      => $doc->ID,
            'title'   => $doc->post_title,
            'url'     => esc_url_raw( get_permalink( $doc->ID ) ),
            'content' => $doc->post_content,
        );

        if ( true === $hierarchy ) {
            $list['children'] = doc8_get_children( $doc->ID, $hierarchy );
        }

        $lists[] = $list;
    }

    return $lists;
}

/**
 * Outputs the action url use in search form.
 */
function doc8_action_url() {
	$url = get_post_type_archive_link( doc8_get_post_type() );

	echo esc_url_raw( $url );
}

/**
 * Returns the search term.
 *
 * @return string
 */
function doc8_get_search_term() {
	if ( ! is_post_type_archive( doc8_get_post_type() ) ) {
		return '';
	}

	if ( empty($_GET['search']) ) {
		return '';
	}

	$search = $_GET['search'];

	return esc_attr( $search );
}

/**
 * Returns an array of code language types.
 *
 * @return array
 */
function doc8_get_attachments_types() {
	$attchment_types = array(
		'text' => 'Text',
		'html' => 'HTML',
		'css'  => 'CSS',
		'sass' => 'Sass',
		'scss' => 'SCSS',
		'php'  => 'PHP',
		'perl' => 'Perl',
		'python' => 'Python',
		'mysql' => 'MySQL',
		'javascript'   => 'Javascript',
		'json' => 'JSON',
		'ruby' => 'Ruby',
	);

	return $attchment_types;
}

/**
 * Get an array of attachments attached to the given document ID.
 *
 * @param $doc_id
 *
 * @return array
 */
function doc8_get_attachments( $doc_id ) {
	$files = get_post_meta( $doc_id, 'doc8_attachments', true );

	return empty($files) ? array() : $files;
}

/**
 * Add code attachments at the bottom of the document content.
 *
 * @param $content
 *
 * @return string
 */
function doc8_set_document_attachments( $content ) {
	if ( get_post_type() != doc8_get_post_type() ) {
		return $content;
	}

	$attachments = doc8_get_attachments( get_the_ID() );
	if ( empty($attachments) ) {
		return $content;
	}

	$tabs = array();
	$tab_contents = array();
	$types = doc8_get_attachments_types();
	$active = false;

	foreach ( $attachments as $pos => $attachment ) {
		$type = $attachment['type'];
		$link = sprintf( '<a href="#%1$s" data-lang="%1$s">%2$s</a>', $type, $types[$type] );
		$class = '';

		if ( ! $active ) {
			$class = 'class="active"';
			$active = true;
		}

		$tabs[] = sprintf( '<li %1$s>%2$s</li>', $class, $link );

		$editor_id = 'doc8-editor-' . get_the_ID() . '-' . $type . '-' . $pos;
		$tab_contents[] = sprintf( '<textarea class="doc8-code" data-code="%1$s" id="%2$s">%3$s</textarea>', $type, $editor_id, esc_textarea( $attachment['file'] ) );

		//$tab_contents[] = sprintf( '<div class="doc8-tab-content">%2$s</div>', '', $tab_content );
	}

	$tabs = sprintf( '<ul class="code-item">%s</ul>', implode( ' ', $tabs ) );
	$tab_contents = sprintf( '<div class="doc8-codes">%s</div>', implode( ' ', $tab_contents ) );
	$attach = sprintf( '<div class="code-attachments">%s</div>', $tabs . $tab_contents );

	$content .= $attach;

	return $content;
}
