<?php
include_once dirname(__FILE__) . '/doc-rank-helper.php';

/**
 * Handles AJAX requests to filter analytics overview data by date.
 *
 * This function processes incoming AJAX requests to filter the analytics overview
 * based on the provided date range. It retrieves relevant data and returns the
 * filtered results in the appropriate format for the admin analytics dashboard.
 *
 * @return void Outputs the filtered analytics data as a JSON response.
 */
function ezd_filter_date_from_search() {
	global $wpdb;

	$start_date = sanitize_text_field( $_POST['startDate'] );
	$end_date   = sanitize_text_field( $_POST['endDate'] );

	$search_keyword = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}eazydocs_search_log WHERE created_at BETWEEN '$start_date' AND '$end_date' ORDER BY created_at DESC" );

	$labels              = [];
	$total_search        = [];
	$searchCount         = [];
	$searchCountNotFound = [];

	$m  = gmdate( "m" ); //current month
	$de = gmdate( "d" ); //current day
	$y  = gmdate( "Y" ); //current year

	// Generating apexChart labels
	$datediff = strtotime( $end_date ) - strtotime( $start_date );
	$datediff = floor( $datediff / ( 60 * 60 * 24 ) );

	for ( $i = 0; $i < $datediff + 1; $i ++ ) {
		$labels[]              = gmdate( "Y-m-d", strtotime( $start_date . ' + ' . $i . 'day' ) );
		$total_search[]        = 0;
		$searchCount[]         = 0;
		$searchCountNotFound[] = 0;
	}


	// Get 7 data date wise
	foreach ( $search_keyword as $key => $item ) {
		foreach ( $labels as $datekey => $weekdays ) {
			if ( $weekdays == gmdate( 'Y-m-d', strtotime( $item->created_at ) ) ) {
				$total_search[ $datekey ]        = count( $search_keyword );
				$searchCount[ $datekey ]         = array_sum( array_column( $search_keyword, 'count' ) );
				$searchCountNotFound[ $datekey ] = array_sum( array_column( $search_keyword, 'not_found_count' ) );
			}
		}
	}

	wp_send_json_success( array(
		'labels'              => $labels,
		'searchCount'         => $searchCount,
		'totalSearch'         => $total_search,
		'searchCountNotFound' => $searchCountNotFound
	) );
	wp_die();  //die();
}
add_action( 'wp_ajax_ezd_filter_date_from_search', 'ezd_filter_date_from_search' );


/**
 * Handles AJAX pagination for helpful docs search in the admin analytics section.
 *
 * This function processes AJAX requests to paginate the list of helpful documents
 * based on search criteria. It is typically used in the admin area to improve
 * user experience when browsing analytics related to helpful documentation.
 *
 * @return void Outputs the paginated results as a JSON response.
 */
function ezd_search_helpful_docs_paginate() {
	$type = $_GET['type'] ?? 'most_helpful';

	if ( $type == 'most_helpful' ) {
		if ( isset( $_GET['total_page'] ) ) {
			$total_page = intval( $_GET['total_page'] );

			$posts = get_posts( [ 'post_type' => 'docs', 'posts_per_page' => - 1, 'inclusive' => true ] );

			$post_data = [];
			foreach ( $posts as $key => $post ) {
				$post_data[ $key ]['post_id']        = $post->ID;
				$post_data[ $key ]['post_title']     = $post->post_title;
				$post_data[ $key ]['post_edit_link'] = get_edit_post_link( $post->ID );
				$post_data[ $key ]['post_permalink'] = get_permalink( $post->ID );
				// sum of total positive votes for a post
				$post_data[ $key ]['positive_time'] = array_sum( get_post_meta( $post->ID, 'positive', false ) );

				$post_data[ $key ]['negative_time'] = array_sum( get_post_meta( $post->ID, 'negative', false ) );
			}
			// if post has positive_time number large then negative_time number then show large number first
			usort( $post_data, function ( $a, $b ) {
				return $b['positive_time'] <=> $a['positive_time'];
			} );

			foreach ( $post_data as $key => $post ) {
				if ( $post['positive_time'] > 0 ) {
					if ( $key >= 0 && $key <= $total_page ) {
						ezd_render_doc_rank_item( $post, $key, 'most_helpful' );
					}
				}
			}

			wp_reset_postdata();

		} else {
			// Return an error message if the total_page parameter is not set
			echo 'Error: total_page parameter is missing';
		}
	} elseif ( $type == 'most_viewed' ) {
		if ( isset( $_GET['total_page'] ) ) {
			$total_page = intval( $_GET['total_page'] );

			$posts = get_posts( [ 'post_type' => 'docs', 'posts_per_page' => $total_page, 'meta_key' => 'post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC', 'inclusive' => true  ] );

			$post_data = [];
			foreach ( $posts as $key => $post ) {
				$post_data[ $key ]['post_id']        = $post->ID;
				$post_data[ $key ]['post_title']     = $post->post_title;
				$post_data[ $key ]['post_edit_link'] = get_edit_post_link( $post->ID );
				$post_data[ $key ]['post_permalink'] = get_permalink( $post->ID );
				// sum of total positive votes for a post
				$post_data[ $key ]['positive_time'] = array_sum( get_post_meta( $post->ID, 'positive', false ) );

				$post_data[ $key ]['negative_time'] = array_sum( get_post_meta( $post->ID, 'negative', false ) );
			}
			
			foreach ( $post_data as $key => $post ) {
				if ( $key >= 0 && $key <= $total_page ) {
					ezd_render_doc_rank_item( $post, $key, 'most_viewed' );
				}
			}

			wp_reset_postdata();

		} else {
			// Return an error message if the total_page parameter is not set
			echo 'Error: total_page parameter is missing';
		}
	} else {
		if ( isset( $_GET['total_page'] ) ) {
			$total_page = intval( $_GET['total_page'] );

			$posts = get_posts( [ 'post_type' => 'docs', 'posts_per_page' => - 1, 'inclusive' => true ] );

			$post_data = [];
			foreach ( $posts as $key => $post ) {
				$post_data[ $key ]['post_id']        = $post->ID;
				$post_data[ $key ]['post_title']     = $post->post_title;
				$post_data[ $key ]['post_edit_link'] = get_edit_post_link( $post->ID );
				$post_data[ $key ]['post_permalink'] = get_permalink( $post->ID );
				// sum of total positive votes for a post
				$post_data[ $key ]['positive_time'] = array_sum( get_post_meta( $post->ID, 'positive', false ) );

				$post_data[ $key ]['negative_time'] = array_sum( get_post_meta( $post->ID, 'negative', false ) );
			}
			// if post has positive_time number large then negative_time number then show large number first
			usort( $post_data, function ( $a, $b ) {
				return $b['negative_time'] <=> $a['negative_time'];
			} );

			foreach ( $post_data as $key => $post ) {
				if ( $post['negative_time'] > 0 ) {
					if ( $key >= 0 && $key <= $total_page ) {
						ezd_render_doc_rank_item( $post, $key, 'least_helpful' );
					}
				}
			}
		} else {
			// Return an error message if the total_page parameter is not set
			echo 'Error: total_page parameter is missing';
		}
	}
	wp_die(); // Always remember to call wp_die() after sending an AJAX response
}
add_action( 'wp_ajax_ezd_search_helpful_docs_paginate', 'ezd_search_helpful_docs_paginate' );
add_action( 'wp_ajax_nopriv_ezd_search_helpful_docs_paginate', 'ezd_search_helpful_docs_paginate' );


/**
 * Analytics Reset
 * Overview reset callback
 */
function ezd_reset_overview_data(){
	// called views meta
	ezd_views_postmeta_reset();
	// called feedback table
	ezd_feedback_table_reset();
	// called search data
	ezd_reset_search_data();
}


/**
 * Post meta views reset callback
 */
function ezd_views_postmeta_reset(){
    global $wpdb;	
    // SQL query to delete all rows with the specified meta key
    $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->postmeta} WHERE meta_key = %s", 'post_views_count' ) );
    // Delete all records from eazydocs_view_log
    $wpdb->query( "DELETE FROM {$wpdb->prefix}eazydocs_view_log" );
}


/**
 * Post meta feedback reset callback
 */
function ezd_feedback_table_reset(){
	global $wpdb;	
	$wpdb->query( "
		DELETE FROM {$wpdb->prefix}postmeta 
		WHERE post_id IN (
			SELECT ID FROM {$wpdb->prefix}posts WHERE post_type = 'docs'
		) 
		AND meta_key IN ('positive_time', 'negative_time', 'positive', 'negative')
	" );	
    setcookie('eazydocs_response', '', time() - 3600, COOKIEPATH, COOKIE_DOMAIN);
}


/**
 * Search tables reset callback
 */
function ezd_reset_search_data(){	
	global $wpdb;	
	$search_keyword_table 	= $wpdb->prefix . 'eazydocs_search_keyword';
	$search_logs_table 		= $wpdb->prefix . 'eazydocs_search_log';	
	$wpdb->query( "DELETE FROM $search_keyword_table" );	
	$wpdb->query( "DELETE FROM $search_logs_table" );
}


/**
 * Overview reset ajax action
 */
function ezd_overview_reset(){
	ezd_reset_overview_data();
}
add_action('wp_ajax_ezd_overview_reset', 'ezd_overview_reset');
add_action('wp_ajax_nopriv_ezd_overview_reset', 'ezd_overview_reset');


/**
 * Feedback reset ajax action
 */
function ezd_reset_feedback() {
	ezd_feedback_table_reset();	
}
add_action('wp_ajax_ezd_reset_feedback', 'ezd_reset_feedback' );
add_action('wp_ajax_nopriv_ezd_reset_feedback', 'ezd_reset_feedback' );


/**
 * Views reset ajax action
 */
function ezd_reset_views(){
    ezd_views_postmeta_reset();
}
add_action('wp_ajax_ezd_reset_views', 'ezd_reset_views');
add_action('wp_ajax_nopriv_ezd_reset_views', 'ezd_reset_views');


/**
 * Search reset ajax action
 */
function ezd_search_table_reset(){
	ezd_reset_search_data();
}
add_action('wp_ajax_ezd_search_table_reset', 'ezd_search_table_reset');
add_action('wp_ajax_nopriv_ezd_search_table_reset', 'ezd_search_table_reset');