<?php

/**
 * The main controller for data management
 *
 * @link       https://aheadoftheweb.com/
 * @since      1.0.0
 *
 * @package    Aow_Hub_Node
 * @subpackage Aow_Hub_Node/admin
 */

/**
 * The main controller for data management
 *
 * Defines the plugin name and version.
 *
 * @package    Aow_Hub_Node
 * @subpackage Aow_Hub_Node/admin
 * @author     Graeme <Gibson>
 */
class Aow_Hub_Node_Data {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version, $admin ) {

		$this->plugin_name = $plugin_name;
		$this->version = $version;
		$this->admin = $admin;
		
	}
	
	/**
	 * Retrieve value in remoteData object by path
	 *
	 * @since 1.4.0
	 * @return  mixed
	 */
	function getDataByPath($o,$path)
	{	    
	    $parts = explode('->', $path);

	    // if you want to  remove the first dummy object-> reference
	    //array_shift($parts);
	    $l = count($parts);
	  
	    while ($l)
	    {
	        $p = array_shift($parts); $l--;
	        if ( isset($o->{$p}) ) $o = $o->{$p};
	        else {$o = null; break;}
	    }
	    return $o;
	}
	
	/**
	 * Get data from either the database or the customizer
	 *
	 * @since    1.0.0
	 * @param      string    $fields       The fields you wish to get
	 * @param      string    $id    The id for the clinic you wish to get the fields from. If nothing is set, we will get the fields from the customizer (this is single clinic mode)
	 */
	public function get_data( $fields = array(), $id = FALSE, $posttype, $single = FALSE ){
		// Build $data variable container
		$data = array();
		// Check if field is an array, if not, make it one
		if( !is_array( $fields ) ){
			$fields = array( $fields => $fields );
		}
		
		if( array_key_exists( 'all', $fields ) ){
			$post_fields = 'all';
			$meta_fields = 'all';
		}else{
			$post_fields = ( array_key_exists( 'post', $fields ) ) ? $fields[ 'post' ] : FALSE;
			$meta_fields = ( array_key_exists( 'meta', $fields ) ) ? $fields[ 'meta' ] : FALSE;
		}

        if( $id ){
			// An id being set means we want to get info from 
			if( is_array( $id ) || $id == 'all' ){
				$options = array(
					'single'		=> $single,
					'post_fields'	=> $post_fields,
					'meta_fields'	=> $meta_fields,
					'posttype'		=> $posttype,
				);
				// Get array of fields for a spcific clinic by ID
				$posts = $this->get_loop( $options );
				foreach( $posts as $k => $v){
					// Get each field from the database and put it in the $data variable
					$data[ $k ] = $v;
				}
			}else{
				$options = array(
					'single'		=> $single,
					'post_fields'	=> $post_fields,
					'meta_fields'	=> $meta_fields,
					'posttype'		=> $posttype,
					'ID'			=> $id,
				);
				// Get array of fields for a spcific clinic by ID
				$data = $this->get_loop( $options );
			}
            
			return $data;
        }else{
            // Get array of fields from the customizer
			foreach( $fields as $k => $v){
				// Get each field from the database and put it in the $data variable
			}
			return $data;
        }
	}
	
	/**
	 * Set data to either the database or the customizer
	 *
	 * @since    1.0.0
	 * @param      string    $fields       The fields you wish to set
	 * @param      string    $id    The id for the clinic you wish to set the fields to. If nothing is set, we will set the fields to the customizer (this is single clinic mode)
	 */
	public function set_data( $fields = array(), $id = FALSE ){
		// Build $data variable container
		$data = '';
		// Check if field is an array, if not, make it one
		if( !is_array( $fields ) ){
			$fields = array( $fields => $fields );
		}
        if( $id ){
            // Set array of fields for a spcific clinic by ID
            foreach( $fields as $k => $v){
				// Set each field to the database
			}
			return true;
        }else{
            // Set array of fields to the customizer
			foreach( $fields as $k => $v){
				// Set each field to the database
			}
			return true;
        }
	}
	
	public function get_loop( $options = array() ){
		$result = array();
		$posttype = $options[ 'posttype' ];
		// WP_Query arguments
		$args = array(
			'post_type' => array( $posttype->posttype ),
			'order'		=> 'ASC',
			'orderby'   => 'order_clause',
			'posts_per_page'	=> -1,
		);
		$id = ( array_key_exists( 'ID', $options ) ) ? $options[ 'ID' ] : FALSE;
		if( $id ){
			$args[ 'meta_query' ] = array(
				array(
					'key' 	=> $posttype->key,
					'value' => $id,
				),
			);
		}else{
			$args[ 'meta_query' ] = array(
				'order_clause' => array(
					'key' => $posttype->key,
				)
			);
		}
		// The Query
		$q = new WP_Query( $args );
		// The Loop
		if ( $q->have_posts() ) {
			$i = 0;
			while ( $q->have_posts() ) {
				$post_fields = array();
				$meta_fields = array();
				$q->the_post();
				$key = get_post_meta( $q->post->ID, $posttype->key );
				
				$key[ 0 ] = ( !empty( $key[ 0 ] ) ) ? $key[ 0 ] : 'static' . $i;
				$i++;
				if( $options[ 'post_fields' ] ){
					if( $options[ 'post_fields' ] == 'all' ){
						$post_fields = $q->post;	
					}else{
						foreach( $options[ 'post_fields' ] as $field ){
							$post_fields[ $field ] = $q->post->$field;
						}	
					}
					
				}
				if( $options[ 'meta_fields' ] ){
					if( $options[ 'meta_fields' ] == 'all' ){
						$meta_fields = get_post_meta( $q->post->ID );
					}else{
						foreach( $options[ 'meta_fields' ] as $field ){
							$meta_fields[ $field ] = get_post_meta( $q->post->ID, $field );
						}
					}
				}
				if( $options[ 'single' ] ){
					if( $options[ 'single' ] == 'post' ){
						$result[ $key[0] ] = $post_fields[ $options[ 'post_fields' ][ 0 ] ][ 0 ];
					}else if( $options[ 'single' ] == 'meta' ){
						$result[ $key[0] ] = $meta_fields[ $options[ 'meta_fields' ][ 0 ] ][ 0 ];
					}else{
						$result[ $key[0] ] = false;
					}
				}else{
					$result[ $key[0] ] = array( 
						'post' 	=> $post_fields,
						'meta'	=> $meta_fields,
					);	
				}
				
				// do something
			}
		} else {
			// no posts found
		}

		// Restore original Post Data
		wp_reset_postdata();
		return $result;
	}
	
	public function update_from_cip( $cip, $posttype ){
		$posttype = $this->admin->cpt[ $posttype ];
		$protected_fields = $this->admin->get_protected_fields( $posttype->posttype );
		$fields_array = array();
		if( !array_key_exists( $cip->id, $protected_fields ) || isset( $protected_fields[ $cip->id ] ) && $protected_fields[ $cip->id ] == 'FALSE' ){
			$fields_array = $posttype->get_meta( $cip );
			$hubid = $fields_array[ $posttype->key ];
			$name = $posttype->name;
			//var_dump( $cip->$name ); die();
			$id = false;
			wp_reset_postdata();

			$q = new WP_Query( "post_type=$posttype->posttype&meta_key=$posttype->key&meta_value=$hubid" );
				
			if( $q->have_posts() ){
				$q->the_post();
				$id = $q->post->ID;
				$q->post_title = $cip->$name;
			}else{
				//no results
			}
			if( $id ){
				foreach( $fields_array as $k => $v ){
					update_post_meta( $id, $k, $v );	
				}
			}
		}
		return true;
	}
	
	public function set_cip( $data, $posttype ){
		//$cips = json_decode( json_encode( $data ), TRUE );
		$cips = $data;
		$posttype = $this->admin->cpt[ $posttype ];
		$protected_fields = $this->admin->get_protected_fields( $posttype->posttype );
		// Get a list of all clinics in this post type to have something to test new data against
		$clinics_to_delete = $this->get_data( array( 'meta' => array( $posttype->key ) ), 'all', $posttype, 'meta' );
		// Remove any clinics from list that don't have a hubid (this ensures that we don't delete posts that werwe created manually)
		$clinics_to_delete = array_filter( $clinics_to_delete );
		$fields_array = array();
		$new_clinics = 0;

		foreach( $cips as $cip ){
			if( !array_key_exists( $cip->id, $protected_fields ) || isset( $protected_fields[ $cip->id ] ) && $protected_fields[ $cip->id ] == 'FALSE' ){
				$new_clinics++;
				$fields_array = $posttype->get_meta( $cip->cip );
				$hubid = $fields_array[ $posttype->key ];
				$id = false;
				wp_reset_postdata();

				$q = new WP_Query( "post_type=$posttype->posttype&meta_key=$posttype->key&meta_value=$hubid" );
				if( $q->have_posts() ){
					$q->the_post();
					$id = $q->post->ID;
					$q->post_title = $cip->name;
					unset( $clinics_to_delete[ $hubid ] );
				}else{
					$new_post = array(
					  'post_title'    => $cip->name,
					  'post_type'	  => $posttype->posttype,
					  'post_status'   => 'publish',
					);
					// Insert the post into the database
					$id = wp_insert_post( $new_post );
					unset( $clinics_to_delete[ $hubid ] );
				}
				if( $id ){
					foreach( $fields_array as $k => $v ){
						update_post_meta( $id, $k, $v );	
					}
				}
			}else{
				$fields_array = $posttype->get_meta( $cip->cip );
				$hubid = $fields_array[ $posttype->key ];
				unset( $clinics_to_delete[ $hubid ] );
			}
		}
		if( $posttype->posttype == 'clinic' ){
			$post_count = wp_count_posts( 'clinic' );
			
			set_theme_mod( 'aow_clinic_count', $post_count->publish );
		}
		if( !empty( $clinics_to_delete ) ){
			$q = new WP_Query( array( 
				'post_type' => $posttype->posttype,
				'meta_key' => $posttype->key,
				'meta_value' => $clinics_to_delete
				)
			);
			if( $q->have_posts() ){
				$q->the_post();
				$id = $q->post->ID;
				wp_delete_post( $id );
			}
		}
		return true;
	}
	
	public function convert_groupcip( $data = FALSE, $direction = 'toarray' ){
		if( $data ){
			if( $direction == 'toarray' ){
				$data = json_decode( $data );
				$data = $data->AllCIPs;
				$data_array = array();
				$clinics = array();
				foreach( $data as $d ){
					$d = reset($d);
					$clinics[ $d->ClinicInfoPackage->HUBinfo->hubID ] = $d;
				}
				return $clinics;
			}
		}
		return $data;
		
		/*
		$current_data = json_decode( $current_data );
	$current_data = $current_data->AllCIPs;
	$total_clinics = 0;
	$data_table = '<table>';
	$data_table_body = '';
	foreach( $current_data as $d ){
		$d = reset($d);
		$data_table_body .= '<tr><td>' . $d->ClinicName . '</td></tr>';
		$total_clinics++;
	}
	$data_table .= '<tr><td>Clinics in Dataset: ' . $total_clinics . '</td></tr>';
	$data_table .= $data_table_body;
	$data_table .= '</table>';
	*/
	}

	
}
