<?php

// We need the ABSPATH
if (!defined('ABSPATH')) exit;

function pagelayer_sc_dm_sidebar(&$el){

	$html = '';
	$current_doc_id = documentor()->get_current_doc_id();
	$current_hub_id = 0;

	$doc_hubs = wp_get_post_terms(
		$current_doc_id,
		'docs_hub',
		['fields' => 'ids']
	);

	// Check for explicit Hub assignments
	if(!empty($doc_hubs) && !is_wp_error($doc_hubs)){
		$current_hub_id = $doc_hubs[0];
	} else{
		// If no explicit Hub, check its Categories for a mapped Hub
		$doc_cats = wp_get_post_terms(
			$current_doc_id,
			'docs_category',
			['fields' => 'ids']
		);
		if(!empty($doc_cats) && !is_wp_error($doc_cats)){
			foreach($doc_cats as $cat_id){
				$mapped_hubs = get_term_meta($cat_id, 'documentor_associated_hubs', false);
				// Grab the first valid Hub mapped to this category
				if(!empty($mapped_hubs) && is_array($mapped_hubs)){
					$current_hub_id = $mapped_hubs[0];
					break;
				}
			}
		}
	}

	// Fetch only the docs for that hub
	$include_ids = [];
	
	if($current_hub_id > 0){
		// Find all categories that belong to this specific Hub
		$matching_cats = get_terms([
			'taxonomy' => 'docs_category',
			'meta_query' => [
				[
					'key'     => 'documentor_associated_hubs',
					'value'   => $current_hub_id,
					'compare' => '='
				]
			],
			'fields' => 'ids'
		]);

		$cat_count = (!empty($matching_cats) && !is_wp_error($matching_cats)) ? count($matching_cats) : 0;
		$tax_query = ['relation' => 'OR'];

		// Always allow docs explicitly assigned to this Hub.
		$tax_query[] = array(
			'taxonomy' => 'docs_hub',
			'field' => 'term_id',
			'terms' => $current_hub_id
		);

		// Also allow docs with no explicit Hub if they belong to a mapped category.
		if($cat_count > 0){
			$tax_query[] = array(
				'relation' => 'AND',
				array('taxonomy' => 'docs_category', 'field' => 'term_id', 'terms' => $matching_cats),
				array('taxonomy' => 'docs_hub', 'operator' => 'NOT EXISTS')
			);
		}

		// Run the database query to get just the matching document IDs
		$docs_query = new WP_Query(array(
			'post_type' => 'docs',
			'posts_per_page' => -1,
			'fields' => 'ids',
			'tax_query' => $tax_query
		));

		if(!empty($docs_query->posts)){
			$include_ids = $docs_query->posts;
		} else{
			$include_ids = array(0);
		}
	}

	$args = array(
		'title_li'  => '',
		'order'     => 'menu_order',
		'child_of'  => empty($el['atts']['hide_parent']) ? 0 : $current_doc_id,
		'echo'      => false,
		'post_type' => 'docs',
		'walker'    => new Documentor_Walker_Docs(),
	);

	if(!empty($include_ids)){
		$args['include'] = implode(',', $include_ids);
	}

	$nav_list = wp_list_pages($args);

	if($nav_list){
		$html  = '<a class="documentor-sidebar-toggler"><i class="fas fa-times"></i></a>';
		$html .= '<ul class="documentor-nav-list'.( $el['atts']['show_child'] ? ' documentor-nav-list-show-childs' : '' ) .'">';
		$html .=  $nav_list;
		$html .= '</ul>';
	} 

	$el['atts']['post_html'] = $html;
}

function pagelayer_sc_dm_feedback(&$el){
	
	$show_counts = $el['atts']['show_counts'];
	$positive_title = $el['atts']['positive_title'];
	$negative_title = $el['atts']['negative_title'];
	$el['atts']['pcount'] = '';
	$el['atts']['ncount'] = '';
	$no_votes = $el['atts']['no_votes'];
	$positive = (int) get_post_meta( get_the_ID(), 'positive', true );
	$negative = (int) get_post_meta( get_the_ID(), 'negative', true );

	if($show_counts){
		$el['atts']['positive_title'] = $positive ? sprintf( '%s %s', number_format_i18n( $positive ), $positive_title ) : $no_votes;
		$el['atts']['negative_title'] = $negative ? sprintf( '%s %s', number_format_i18n( $negative ), $negative_title ) : $no_votes;
	}

	if($positive){ 
		$el['atts']['pcount'] = '<span class="badge">'. esc_html( number_format_i18n( $positive ) ) .'</span>';
	} 

	if($negative){ 
		$el['atts']['ncount'] = '<span class="badge">'. esc_html( number_format_i18n( $negative ) ) .'</span>';
	}
	
}

function pagelayer_sc_dm_article(&$el){

	$children = wp_list_pages( 'title_li=&order=menu_order&child_of=' . get_the_ID() . '&echo=0&depth=1&post_type=' . get_post_type() );

	if(!$children && (pagelayer_is_live() ||  wp_doing_ajax())){
		$children = '<li class="page_item"><a href="javascript_void(0)">Sub Category 1</a></li><li class="page_item"><a href="javascript_void(0)">Sub Category 2</a></li>';
	}

	if(!$children){
		$el['atts']['heading'] = '';	
	}
	 
	$el['atts']['post_html'] = $children;
}
function pagelayer_sc_dm_title(&$el){

	global $post;

	$title =  pagelayer_is_live() ? "Title" : get_the_title( );

	$el['atts']['title'] = $title;
}

function pagelayer_sc_dm_breadcrumbs(&$el){
	
	$breadcrumbs = documentor()->get_breadcrumbs_array();
	$html = '';
	
	foreach( $breadcrumbs as $k => $crumb ){
		if( $k > 0 ){ 
			$html .= '<li class="delimiter">'. $el['atts']['separator'].'</li>';
		}
		
		$html .= '<li itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">';
		
		if(isset($crumb['url'])) $html .= '<a itemprop="item" href="'. esc_url( $crumb['url'] ).'">';
		
		$html .= '<span itemprop="name">'. esc_html( $crumb['label'] ) .'</span>';
		
		if(isset($crumb['url'])) $html .= '</a>';
		
		$html .= '<meta itemprop="position" content="'. esc_attr( $k + 1 ) .'" />';
		$html .= '</li>';
	}

	$el['atts']['post_html'] = $html;
}

function pagelayer_sc_dm_adjacent_links(&$el){
	
	$html = '';
	$prev_post_id = documentor()->get_previous_adjacent_doc_id();
	$next_post_id = documentor()->get_next_adjacent_doc_id();

	if($prev_post_id || $next_post_id){
		
		$html = '<nav class="documentor-single-adjacent-nav">';
	  
		if( $prev_post_id ){
			$html .= '<span class="nav-previous">';
			$html .= '<a href="'.esc_url( get_the_permalink( $prev_post_id ) ) .'" class="documentor-btn documentor-btn-md">'. esc_html( get_the_title( $prev_post_id ) ) .'</a>';
			$html .= '</span>';
		}
	  
		if( $next_post_id ){
			$html .= '<span class="nav-next">';
			$html .= '<a href="'.esc_url( get_the_permalink( $next_post_id ) ) .'" class="documentor-btn documentor-btn-md">'. esc_html( get_the_title( $next_post_id ) ) .'</a>';
			$html .= '</span>';
		}
	  
		$html .= '</nav>';
	}

	$el['atts']['post_html'] = $html;
}

function pagelayer_sc_dm_archive_box(&$el){
	global $wp_query;

	$is_editor = (pagelayer_is_live() || wp_doing_ajax());

	// Check if current page is a a linked Hub
	$is_hub_page = false;
	if(is_page()){
		$linked_hub = get_post_meta(get_the_ID(), '_documentor_linked_hub_id', true);
		if(!empty($linked_hub)){
			$is_hub_page = true;
		}
	}

	//Check if we are on the Main Documentation Archive Page
	$is_main_docs_page = (!is_tax('docs_hub') && !$is_hub_page && !is_search() && !$is_editor);
	$html = '';
	$show_hub_grid = false;
	$hub_grid_html = '';

	if(pagelayer_is_live() || wp_doing_ajax()){
		$args = array(
				'post_type'		=> 'docs',
				'posts_per_page' => -1, // phpcs:ignore
				'post_parent'	 => 0,
				'orderby'		  => array(
				'menu_order' => 'ASC',
				'date'		 => 'DESC',
				),
		);

		$wp_query = new WP_Query( $args );
	}

	// Fetch the Hub ID from either the Taxonomy OR the Page
	$selected_hub_id = 0;
	if(is_tax('docs_hub')){
		$selected_hub_id = get_queried_object_id();
	} elseif(is_page()){
		$linked_hub = get_post_meta(get_the_ID(), '_documentor_linked_hub_id', true);
		if(!empty($linked_hub)){
			$selected_hub_id = intval($linked_hub);
		}
	}

	$matching_cats = array();
	if($selected_hub_id > 0){
		$matching_cats = get_terms(array(
			'taxonomy' => 'docs_category',
			'meta_query' => array(
				array(
					'key'     => 'documentor_associated_hubs',
					'value'   => $selected_hub_id,
					'compare' => '='
				)
			),
			'fields' => 'ids'
		));
		if(is_wp_error($matching_cats)) $matching_cats = array();
	}

	$current_term = false;

	if( have_posts()){
		while ( have_posts() ){
			// Set up global $post data for the current document
			the_post(); 
			
			$terms = wp_get_post_terms( get_the_ID(), 'docs_category' );
			$hubs = wp_get_post_terms(get_the_ID(), 'docs_hub');
			$display_term_name = false;

			if(empty($selected_hub_id) && !empty($hubs)){
				continue;
			} elseif(!empty($selected_hub_id)){
				$has_selected_hub = false;

				if(!empty($hubs) && !is_wp_error($hubs)){
					foreach($hubs as $hub){
						if(!empty($hub->term_id) && $selected_hub_id === intval($hub->term_id)){
							$has_selected_hub = true;
							break;
						}
					}
				}

				if(!$has_selected_hub && !empty($hubs)){
					continue;
				}

				if($terms && !empty($terms)){
					if(!empty($matching_cats)){
						foreach($terms as $t){
							if(in_array($t->term_id, $matching_cats)){
								$display_term_name = $t->name;
								break;
							}
						}
					}

					if(!$has_selected_hub && !$display_term_name){
						continue;
					}
				} elseif(!$has_selected_hub){
					continue;
				}
			}

			if($terms && !empty($terms) && !$display_term_name){
				// Look through the doc's categories and find the one that belongs to this Hub
				$display_term_name = $terms[0]->name;
			}
			
			// Print the Correct Header
			if($display_term_name && $current_term !== $display_term_name){
				$current_term = $display_term_name;
				$html .= '<li class="documentor-archive-list-category">';
				$html .= esc_html($current_term);
				$html .= '</li>';
			}

			$html .= '<li class="documentor-archive-list-item">';
			$html .=  documentor_loop_title($el['atts']);
			$html .=  documentor_loop_articles($el['atts']);
			$html .= '</li>';
		}
	} elseif(pagelayer_is_live() || wp_doing_ajax()){
		$html .= '<li class="documentor-archive-list-item">';
		$html .=  documentor_loop_title($el['atts']);
		$html .=  documentor_loop_articles($el['atts']);
		$html .= '</li>';
	 }

	$el['atts']['post_html'] = $html;
}

function documentor_loop_title($atts){
	$html = '';
	$articles = get_pages(
		array(
			'child_of'  => get_the_ID(),
			'post_type' => 'docs',
		)
	);
	$articles_count = count( $articles );	 

	$html .= '<a href="'. get_the_permalink().'" class="documentor-archive-list-item-title">';
	
	if($atts['hicon']){
		$html .= '<i class="'. $atts['hicon'].'"></i>';
	}
	
	$html .= get_the_post_thumbnail( '','documentor_archive' ); 
	$html .= '<span>';
	$html .= '<span>';
	$html .= sprintf( esc_html( _n( '%s Article', '%s Articles', $articles_count, 'documentor' ) ), esc_html( $articles_count ) );
	$html .= '</span>';
	$html .= '<h2>'. get_the_title() .'</h2>';
	$html .= '</span>';
	$html .= '</a>';
	
	return $html;
}

function documentor_loop_articles($atts){
	
	$html ='';
	$show = $atts['show_articles'];
	$articles_number = $atts['articles_depth'];

	if ( -1 === $articles_number ) {
		$articles_number = 9999;
	}

	if ( ! $show || $articles_number < 1 ) {
		return;
	}

	$top_articles = new WP_Query(
		array(
			'post_type'		=> 'docs',
			'posts_per_page' => -1, // phpcs:ignore
			'post_parent'	 => get_the_ID(),
			'orderby'		  => array(
				'menu_order' => 'ASC',
				'date'		 => 'DESC',
			),
		)
	);
	
	$parent_link  = get_permalink();
	$count = 0;

	$nav_list = wp_list_pages(
		array(
			'title_li'  => '',
			'order'	  => 'menu_order',
			'child_of'  => documentor()->get_current_doc_id(),
			'echo'		=> false,
			'post_type' => 'docs',
			'icon'		=> $atts['icon'],
			'depth'	  => $articles_number,
			'walker'	 => new Documentor_Walker_Docs(),
		)
	);

	if(!$nav_list && (pagelayer_is_live() || wp_doing_ajax())){
		$nav_list = '<li class="page_item"><a href="">List</a></li>';
	}

	if ($nav_list) {
		$show_childs = documentor()->get_option( 'sidebar_show_nav_childs', 'documentor_single', false );
		$html .= '<div class="home_page_cats slimscroll-virt">';
		$html .= '<ul class="documentor-nav-list'. ( $show_childs ? ' documentor-nav-list-show-childs' : '' ).'">';
		$html .=  $nav_list; 
		$html .= '</ul>';
		$html .= '</div>';
	} 
	
	wp_reset_postdata(); 
	return $html;
}

function pagelayer_sc_dm_hub_list(&$el){
	$hubs = get_terms([
		'taxonomy' => 'docs_hub',
		'hide_empty' => false,
	]);

	if(empty($hubs)){
		$el['atts']['hub_list_html'] = !empty($el['no_hub']) ? $el['no_hub'] : __('No Doc Hub created yet', 'documentor');
		return;
	}
	
	if(is_wp_error($hubs)){
		$el['atts']['hub_list_html'] = $hubs->get_error_message();	
		return;
	}

	$active_hubs_count = 0;
	$boxes_html = '';

	foreach($hubs as $hub){
		$hub_id = $hub->term_id;

		$sections = get_posts([
			'post_type' => 'docs',
			'post_status' => 'publish',
			'posts_per_page' => -1,
			'fields' => 'ids',
			'post_parent' => 0,
			'tax_query'      => [
				[
					'taxonomy' => 'docs_hub',
					'field'    => 'term_id',
					'terms'    => $hub_id,
				],
			],
		]);

		if(empty($sections)) {
			continue;
		}

		$query = new \WP_Query([
			'post_type' => 'docs',
			'post_status' => 'publish',
			'post_parent__in' => $sections,
			'posts_per_page' => -1,
			'fields' => 'ids',
		]);

		$section_count = count($sections);
		$doc_count = (int) $query->found_posts;
		
		// Now we need to get all the sub child docs id
		if(!empty($query->posts) && is_array($query->posts)){
			$query = new \WP_Query([
				'post_type' => 'docs',
				'post_status' => 'publish',
				'post_parent__in' => $query->posts,
				'posts_per_page' => -1,
				'fields' => 'ids',
			]);
			
			$doc_count += (int) $query->found_posts;
		}

		if($section_count === 0 && $doc_count === 0){
			continue; 
		}

		$active_hubs_count++;

		// Robustly find the linked Page URL (Check Term Meta, then Post Meta)
		$page_url = get_term_link($hub);

		// Format text grammar
		$section_text = $section_count === 1 ? '1 Section' : $section_count . ' Sections';
		$doc_text = $doc_count === 1 ? '1 Doc' : $doc_count . ' Docs';

		$boxes_html .= '<a href="' . esc_url($page_url) . '" class="documentor-hub-box">';
		$boxes_html .= '<span class="documentor-hub-title">' . esc_html($hub->name) . '</span>';
		$boxes_html .= '<span class="documentor-hub-meta">' . $section_text . ' &bull; ' . $doc_text . '</span>';
		$boxes_html .= '</a>';
	}

	if($active_hubs_count <= 0){
		$el['atts']['hub_list_html'] = !empty($el['no_hub']) ? $el['no_hub'] : 'No Doc Hub found';
		return;
	}
	
	$el['atts']['hub_list_html'] = $boxes_html;
}