<?php

/**
 * Relational DB SELECT for Post and Note
 * - using WP Post Meta
 *
 * @todo Replace only if your creating your own Plugin
 * @todo dst - Find all and replace text
 * @todo DST - Find all and replace text
 * @todo dealer - Custom post type. Replace it with your custom post
 *
 */

// Exit if accessed directly
if( !defined( 'ABSPATH' ) ) exit;

/**
 * Relational DB Query
 *
 * To independently use this, 
 * DST_DB_Query::get_posts($post_id); // $post_id of a current `dealer` post type
 * DST_DB_Query::get_dealers($post_id) - $post_id of a current `post` post type
 *
 * @since 1.0.0
 */
class DST_DB_Query {

	/**
	 * Getting values WP Options (Database)
	 *
	 * To display its value, <?php echo DST()->db->get_option('','dst_options', 0) ?>
	 *
	 * @access public
	 * @since 1.0.0
	 * @param string $wp_option It's a get_option key
	 * @param int $index_array Position of indexes
	 * @param int|string $default_value Default value when empty
	 * @return array $output 
	 */
	public function get_option($default_value, $wp_option, $index_array){
		$output = $default_value;
		if($index_array === false){
			$output = get_option($wp_option);
			return $output;
		}
  		if(!empty(get_option($wp_option)[$index_array]) ){
    		$output = get_option($wp_option)[$index_array];
  		}
  		return $output;
	}

	/**
	 * Get Associated Meta 
	 *
	 * Used in the-content-filer.php
	 * @access public
	 * @since 1.0.0
	 * @param int $post_id Post ID of a current Post Type `dealer`
	 * @return array $dealer_meta Post Meta Data
	 */
	public function get_meta($post_id){
		$meta_key='dst_postmeta_input_key'; 
		
		$dealer_meta = array();

		if(!empty(get_post_meta($post_id, $meta_key))){
			$dealer_meta = get_post_meta($post_id, $meta_key);
		}
		return $dealer_meta;
	}

	/**
	 * Finding Related Post and Postmeta using Postcode
	 *
	 * Used in the wp-ajax...php 
	 * @access public
	 * @since 1.0.0
	 * @param int $post_code input from ajax search form
	 * @return array $results Post Meta Data
	 */
	public function related_postmeta($post_code){
		
		// this maybe overkill, but better safe!
		if(empty($post_code))
			return;

		$max = 10;
		$sort = 'DESC';	
		$post_type = 'dealer';
		$meta_key='dst_postmeta_input_key'; 
		$post_meta = array();
		$results = array();

		$args = array( // can be rearranged
					'numberposts'   => $max,
					'offset'           => 0,
					'category'         => '',
					'category_name'    => '',
					'orderby'          => 'date',
					'order'            => $sort,
					'include'          => '',
					'exclude'          => '',
					'meta_key'         => '',
					'meta_value'       => '',
					'post_type'        => $post_type,
					'post_mime_type'   => '',
					'post_parent'      => '',
					'author'	   => '',
					'post_status'      => 'publish',
					'suppress_filters' => true 
		);
			/**
			 * @see Get Posts https://developer.wordpress.org/reference/functions/get_posts/
			 */ 
			$get_posts = get_posts($args, ARRAY_A); // Accepts OBJECT, ARRAY_A, or ARRAY_N

			if(!empty($get_posts)){
				foreach ($get_posts as $single_post) {
					$get_postmeta = get_post_meta($single_post->ID, $meta_key);
					
					// Postcode in 4th index 
					if($get_postmeta[4] == $post_code){
						// $results[] = $get_postmeta;
						$results[] = array(
							'ID' 			=> $single_post->ID,
							'post_title' 	=> $single_post->post_title, 
							'post_uri' 		=> $single_post->guid,
							'post_meta' 	=> $get_postmeta
						);
					}
				}
			}
			// $results = $get_postmeta;
			// $results = $get_postmeta[0][3];
			return $results;
	}
	
	/**
	 * Display All Posts Dealer with its Post Meta
	 *
	 * Used in the wp-ajax...php 
	 * @access public
	 * @since 1.0.0
	 * @param int $post_code input from ajax search form
	 * @return array $results Post Meta Data
	 */
	public function dealers_postmeta(){
		$max = 10;
		$sort = 'DESC';	
		$post_type = 'dealer';
		$meta_key='dst_postmeta_input_key'; 
		$post_meta = array();
		$results = array();

		$args = array( // can be rearranged
					'numberposts'   => $max,
					'offset'           => 0,
					'category'         => '',
					'category_name'    => '',
					'orderby'          => 'date',
					'order'            => $sort,
					'include'          => '',
					'exclude'          => '',
					'meta_key'         => '',
					'meta_value'       => '',
					'post_type'        => $post_type,
					'post_mime_type'   => '',
					'post_parent'      => '',
					'author'	   => '',
					'post_status'      => 'publish',
					'suppress_filters' => true 
		);
			/**
			 * @see Get Posts https://developer.wordpress.org/reference/functions/get_posts/
			 */ 
			$get_posts = get_posts($args, ARRAY_A); // Accepts OBJECT, ARRAY_A, or ARRAY_N

			if(!empty($get_posts)){
				foreach ($get_posts as $single_post) {
					$get_postmeta = get_post_meta($single_post->ID, $meta_key);
					
					$results[] = array(
							'ID' 			=> $single_post->ID,
							'post_title' 	=> $single_post->post_title, 
							'post_uri' 		=> $single_post->guid,
							'post_meta' 	=> $get_postmeta
					);
				}
			}
			return $results;
	}

	/**
	 * Relational DB SELECT to get Posts of a current Note
	 *
	 * @access public
	 * @since 1.0.0
	 * @param int $post_id Post ID of a current Post Type `dealer`
	 * @return array $posts_with_dealer Posts results of a current dealer
	 */
	public function get_posts($post_id){ 	

		$posts_with_dealer = array();
		$post_type = NOTE_FOR_POSTS_PTYPE; // default: $post_type = 'post'
		$args = array( 'post_type' => $post_type);
		$all_posts = get_posts($args); // Get WP Posts
		$post_meta_key = 'dst_postmeta_input_key'; // @todo make sure this is a correct key	

		// Only Execute if Post Meta Exist
		if( get_post_meta( $post_id, $post_meta_key, true ) ) {
			// Array Handler
			foreach($all_posts as $single_post){	

				$single_post_id = $single_post->ID;	

				// This do the DB relation trick
				foreach( get_post_meta($post_id, $post_meta_key, false) as $meta_value )  { 
					// Let's find all posts with dealers
					if($meta_value == $single_post_id ){		
						$posts_with_dealer[] = $single_post; // Store into array if found a match
						break; // If match found, there's no sense of continue searching
					}
				}
			}
		} 
		return $posts_with_dealer;
	}	

	/**
	 * Relational DB SELECT to get Posts of a current Note Version 2
	 *
	 * @access public
	 * @since 1.0.0
	 * @param int $post_id Post ID of a current Post Type `dealer`
	 * @return array $posts_with_dealer Posts results of a current dealer
	 */
	public function get_posts_v2($post_id){ 	

		$posts_with_dealer = array();
		$get_meta_values = array();

		// Add some test data here - a custom field, that is
		$meta_key='dst_postmeta_input_key';
		$post_type = NOTE_FOR_POSTS_PTYPE; // default: $post_type = 'post'

		// Only Execute if Post Meta Exist
		if( get_post_meta( $post_id, $meta_key, true ) ) {
			
			// Array handler for meta_values
			foreach ( get_post_meta( $post_id, $meta_key, false ) as $meta_value) { // $meta_value is a post ID
					$get_meta_values[] = $meta_value; // assigning to $get_meta_values array
			}

			// Get Posts that was included in the `include` key
			$args = array( 'post_type'		=> $post_type, 
						   'numberposts'	=> '-1',
						   'orderby'        => 'date',
						   'order'          => 'DESC',
						   'include'        => $get_meta_values // Since Meta Values stores Post ID(s)
					); 
			$posts_with_dealer = get_posts($args); // Assigning to Var Array
		}
		return $posts_with_dealer;
	}	
	/**
	 * Relational DB SELECT to get Notes of a current Post (Reversed)
	 *
	 * @access public
	 * @since 1.0.0
	 * @param int $post_id Post ID of a current Post Type `post`
	 * @return array $dealers_with_post Notes results of a current post
	 */
	function get_dealers($post_id){ 	

		$dealers_with_post = array();
		$post_type = 'dealer'; // @todo just aim the correct post_type
		
		$args = array( 'post_type' => $post_type); 
		$all_dealers = get_posts($args); // Get All Notes Array
		$post_meta_key = 'dst_postmeta_input_key'; // @todo make sure this is a correct key	
		
		// Notes Array Handler
		foreach($all_dealers as $single_dealer){	
			$single_dealer_id = $single_dealer->ID;	

			// Only Execute if Post Meta Exist
			if( get_post_meta( $single_dealer_id, $post_meta_key, true ) ) {
			
				// This do the DB relation trick
				foreach( get_post_meta($single_dealer_id, $post_meta_key, false) as $meta_value )  {
					// Let's find all posts with dealers
					if($meta_value == $post_id ){		
						$dealers_with_post[] = $single_dealer; // Store into array if found a match
						break; // If match found, there's no sense of continue searching
					}
				}
			
			}
		}	
		return $dealers_with_post;
	}
}


