<?php
/*
Plugin Name: RealConnect MLS
Plugin URI: http://realconnectmls.com/
Description: Add live MLS data to your website with customizable templates and styles.
Version: 2.7.3
Author: Birch Studio
Author URI: https://birchstudio.com/
*/
global $wpdb,$table_mls_listing_name,$mls_image_upload_folder_name,$rc_plugin_version;

global $disableUnusedCode;  // added by vikas to disable some code sections so that we can easily enable it back by changing value of this variable..
$disableUnusedCode=true;

$table_mls_listing_name = $wpdb->prefix.'mls_listing';
$mls_image_upload_folder_name = "mls_upload_images"; 
$rc_plugin_version = 2.7;
//error_reporting(E_ERROR);
include_once(LoadPHPFile('/RealConnect/controllers/wppage.php'));
include_once(LoadPHPFile('/RealConnect/RealConnect/RealConnect.php'));   
include_once(LoadPHPFile('/RealConnect/property-listing-filters/property-listing-filters.php'));
function titleCase($string_title_case){
	return ucwords(strtolower($string_title_case));
}
//exit(LoadAssetFile('/RealConnect/images/placeholder.png'));
/*
function realconnect_js(){ 
wp_enqueue_script('bootstrap-js', plugin_dir_url().'RealConnect/js/bootstrap.min.js');
wp_enqueue_script('docs-js',  plugin_dir_url().'RealConnect/js/docs.js');
wp_enqueue_script('viewport-bug-workaround-js', plugin_dir_url().'RealConnect/js/ie10-viewport-bug-workaround.js');
}

add_action('wp_footer','realconnect_js');

function realconnect_css(){
	wp_enqueue_style('bootstrap.min', plugin_dir_url().'RealConnect/css/bootstrap.min.css');
	wp_enqueue_style('bootstrap.min', plugin_dir_url().'RealConnect/css/bootstrap.min.css');
	wp_enqueue_style('bootstrap-theme.', plugin_dir_url().'RealConnect/css/bootstrap-theme.min.css');
	wp_enqueue_style('jquery-ui.css', '//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css');
	wp_enqueue_style('theme', plugin_dir_url().'RealConnect/css/theme.css');
	wp_enqueue_style('last', plugin_dir_url().'RealConnect/css/last.css');
}
add_action('wp_head','realconnect_css');


function realconnect_css(){
	wp_enqueue_style('real-connect-style', plugin_dir_url().'RealConnect/css/real-connect-style.css');
}	
add_action('wp_head','realconnect_css');
*/

// custom pagination

function custom_pagination($total = 0,$current=1,$rang_defference=1){
	       
	    if($total>$rang_defference){
		    $reminder = ceil($total/$rang_defference);
			return  paginate_links(array(
			                'base'               => preg_replace('/\?.*/', '', get_pagenum_link(1)) . '%_%', 
							'format'             => '?page_no=%#%',
                            'current' =>$current,
                            'total' => $reminder,
                            'end_size' =>6,
							//'type' => 'list',
							
							
                            )
                            );  
        }                    
}


//three_hand_picked_homes function for home page 
function hand_picked_homes( $featured_listing ) {

   if(is_array($featured_listing) && count($featured_listing)){
	    ob_start();
		include_once(LoadPHPFile( '/RealConnect/Model/details_model.php'));
		include_once(LoadPHPFile('/RealConnect/Model/shared_model.php'));
		include_once(LoadPHPFile( '/RealConnect/Model/flexdetails_model.php'));
     
     foreach($featured_listing as $mls_ids){
	
	   $mls_id_array = explode(",",$mls_ids);
	   if(count($mls_id_array)){
		   $output_html = '';
		    foreach($mls_id_array as $mls_id){
				$property_type = 'residential';
	          
				$output_html .=  picked_homes_by_mls_id($property_type , $mls_id);
	        }
	        
	        if(!empty($output_html)){
			?>
			<!--HAND PICKED HOMES start-->
			<div class="favorite-places-section hand_picked_section" style="display: inherit;">
			
			<div class="bucket-row">
			<!--<h2 style="text-align: center;">Hand-Picked Homes</h2> Removed by DGR 2017-11-30 -->
			<?php 
			
			 echo $output_html;
			 
			 ?>
			
			</div>
			</div>
			<link href="<?php echo plugin_dir_url('').'RealConnect'; ?>/css/real-connect-style.css" rel="stylesheet">
			<!--HAND PICKED HOMES end-->  
			<?php
			 return ob_get_clean();
			 
				
			}
	        
	   }
	   
    }
  } 
}
add_shortcode( 'hand_picked_homes', 'hand_picked_homes' );


function picked_homes_by_mls_id($property_type = 'residential', $mls_id = 0)
	{
		
		$model_Obj->details_model = new Details_model();
		$model_Obj->shared_model = new Shared_model();
		$model_Obj->flexdetails_model = new Flexdetails_model();
		
		
		if($property_type =='test')
		{
			$model_Obj->details_model->test();
		}
		//initialize the arrays for data that will be sent to the views
		$data = array();
		$headdata = array();
		//comment tpss
		//$this->content['page_title'] = "Property Details";
		$content['page_title'] = "Property Details";
		
		//get client information
		$site_url = site_url();
		$client_info = $model_Obj->shared_model->get_client_info($site_url);
		$mls_type = 'paragon';
		if (count($client_info) > 0) {
			$mls_type = $client_info['mls_feed'];
		}
		//get details to send to the view
		if ($mls_id != 0) {
			if ($mls_type == 'paragon') {
				$data['details'] = $model_Obj->details_model->get_property_details($property_type, $mls_id, $site_url);
				if($data['details'])
				{
					if(count($data['details']['images']) > 0) {
						$image_count = 0;
						foreach ($data['details']['images'] as $image) {
							if ($image_count == 0) {
								$fbImage = $image['url'];
							}
							$image_count++;
						}
					} else {
						$fbImage = LoadAssetFile('/RealConnect/images/placeholder.png');
					}
					$fbDescription = $data['details']['LR_remarks22'];
					$fbTitle = $data['details']['L_Address'].', '.$data['details']['L_City'].', '.$data['details']['L_State'].' '.$data['details']['L_Zip'];
				}
					
			} else {
				$data['details'] = $model_Obj->flexdetails_model->get_property_details($property_type, $mls_id, $site_url);
				if($data['details'])
				{
					if(count($data['details']['images']) > 0) {
						$image_count = 0;
						foreach ($data['details']['images'] as $image) {
							if ($image_count == 0) {
								$fbImage = $image['url'];
							} 
							$image_count++;
						}
					} else {
						$fbImage = LoadAssetFile('/RealConnect/images/placeholder.png');
					}
					$fbDescription = $data['details']['LIST_78'];
					$fbTitle = $data['details']['address'];
				}
					
			}
		
		
		
		} 
		
		
		if(isset($data['details']) && is_array($data['details'])){
			$details = $data['details'];
			$L_Address = '';
			if(isset($details['L_Address'])){
				$L_Address = $details['L_Address'];
		    }
			//DETAILS URL
            
            $details_url = site_url('details/'.$property_type.'/'.$mls_id);
			$first_images = '';
			if (count($details['images']) > 0) {
				
			$first_images = current($details['images']);
		     }
		    $price = '';
		    if(isset($details['L_AskingPrice'])){
			 $price = '$'.number_format($details['L_AskingPrice'], 0, '', ',');
		    }
		    
		     $html = '';
			 $html = '<div id="favorite-1-div" class="bucket-left hand-picked-home ">';
			 $html .= '<a href="'.$details_url.'"><img class="favorite-1-picture" src="'.$first_images['url'].'"  /></a>';
			 $html .= '<span class="address hand-picked-home favorite-1-address" data-place-id="560612">'.$L_Address.'</span>';
			 $html .= '<span class="price favorite-1-price">'.$price.'</span></div>';    
			 return $html;
		    
		}
		
	}
	
// add temlate in plugin diretory
class PageTemplater {

	/**
	 * A reference to an instance of this class.
	 */
	private static $instance;

	/**
	 * The array of templates that this plugin tracks.
	 */
	protected $templates;

	/**
	 * Returns an instance of this class. 
	 */
	public static function get_instance() {

		if ( null == self::$instance ) {
			self::$instance = new PageTemplater();
		} 

		return self::$instance;

	} 

	/**
	 * Initializes the plugin by setting filters and administration functions.
	 */
	private function __construct() {

		$this->templates = array();


		// Add a filter to the attributes metabox to inject template into the cache.
		if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.7', '<' ) ) {

			// 4.6 and older
			add_filter('page_attributes_dropdown_pages_args',array( $this, 'register_project_templates' )
			);

		} else {

			// Add a filter to the wp 4.7 version attributes metabox
			add_filter('theme_page_templates', array($this, 'add_new_template')	);

		       }

		// Add a filter to the save post to inject out template into the page cache
		add_filter('wp_insert_post_data', array( $this, 'register_project_templates' ) );


		// Add a filter to the template include to determine if the page has our 
		// template assigned and return it's path
		add_filter('template_include', array( $this, 'view_project_template') );


		// Add your templates to this array.
	         $this->templates = array(
			'page-templates/properties-template.php' => 'RC Summary Listings Page',
			'page-templates/property-details-template.php' => 'RC Details Page',
			'page-templates/properties-grid-layout-template.php' => 'RC Grid Summary Listings Page',  // DGR 2017-12-09	
			 );
			
	} 

	/**
	 * Adds our template to the page dropdown for v4.7+
	 *
	 */
		public function add_new_template( $posts_templates ) {
			$posts_templates = array_merge( $posts_templates, $this->templates );
			return $posts_templates;		}

	/**
	 * Adds our template to the pages cache in order to trick WordPress
	 * into thinking the template file exists where it doens't really exist.
	 */
	 public function register_project_templates( $atts ) {

		// Create the key used for the themes cache
		$cache_key = 'page_templates-' . md5( get_theme_root() . '/' . get_stylesheet() );

		// Retrieve the cache list. 
		// If it doesn't exist, or it's empty prepare an array
		$templates = wp_get_theme()->get_page_templates();
		if ( empty( $templates ) ) { $templates = array();
		}  

		// New cache, therefore remove the old one
		wp_cache_delete( $cache_key , 'themes');

		// Now add our template to the list of templates by merging our templates
		// with the existing templates array from the cache.
		$templates = array_merge( $templates, $this->templates );

		// Add the modified cache to allow WordPress to pick it up for listing
		// available templates
		wp_cache_add( $cache_key, $templates, 'themes', 1800 );

		return $atts;

	}  

	/**
	 * Checks if the template is assigned to the page
	 */
	 public function view_project_template( $template ) {
		
		// Get global post
		global $post;

		// Return template if post is empty
		if ( ! $post ) { return $template;	}

		// Return default template if we don't have a custom one defined
		if ( ! isset( $this->templates[get_post_meta( 
			$post->ID, '_wp_page_template', true 
		)] ) ) {
			return $template;
		} 

		$file = plugin_dir_path( __FILE__ ). get_post_meta( 
			$post->ID, '_wp_page_template', true
		);

		// Just to be safe, we check if the file exist first
		if ( file_exists( $file ) ) {
			return $file;
		} else {
			echo $file;
		}

		// Return template
		return $template;
 
	}  

} 
add_action( 'plugins_loaded', array( 'PageTemplater', 'get_instance' ) );



/*
 * Create style file for admin rc-admin-style.css and sort-order-jquery-ui.js 
*/ 	
    function rc_load_admin_style_and_javascript($hook ) {
		global $rc_plugin_version,$post;

		if ( $hook == 'post-new.php' || $hook == 'post.php' ) {
			if ( 'real_connect' == $post->post_type ) {     
				wp_enqueue_style('rc_admin_style', LoadAssetFile('/RealConnect/css/rc-admin-style.css'), false, $rc_plugin_version );
				wp_enqueue_script(  'rc_sort_order_script', LoadAssetFile('/RealConnectjs/sort-order-jquery-ui.js'), false, $rc_plugin_version );
            
			}
		}
			
    }
     add_action( 'admin_enqueue_scripts', 'rc_load_admin_style_and_javascript',10,1 );

/*
 * Create custom post type of real_connect  
 */ 
	function create_post_type_real_connect() {
	
		$labels = array(
			 'name'			=> _x( 'View Custom Listings', 'Post Type General Name', 'text_domain' ),
			 'singular_name'=> _x( 'View Custom Listings', 'Post Type Singular Name', 'text_domain' ),
			 'menu_name'             => __( 'RealConnect', 'text_domain' ),
			 'all_items'             => __( 'View Custom Listings', 'text_domain' ),
			 'add_new_item'          => __( 'Add Custom Listing', 'text_domain' ),
			 'add_new'               => __( 'Add Custom Listing', 'text_domain' ),
			 'featured_image'        => __( 'Listing Page Image' ),
			 'remove_featured_image' => __( 'Remove Listing Page Image' ),
			 'set_featured_image'    =>__( 'Listing Page Image' ),
			 'use_featured_image'    =>__( 'Listing Page Image' ),
		);
		$args = array(
			'labels'       => array('name'=> __( 'RealConnect' )),
			'labels'       => $labels,
			'public'       => true,
			'has_archive'  => true,
			//supports'     => array('title','editor','thumbnail'), 
			'supports'     => array('title','thumbnail'), 
			'menu_icon' => 'dashicons-admin-home',
			'show_in_menu'  =>	'RealConnect'
			
		);
		// check real custom post enable or not
		include_once(LoadPHPFile('/RealConnect/Model/shared_model.php'));
		$site_url = get_site_url();
		$model_Obj = new \stdClass();
		$model_Obj->shared_model = new Shared_model();
		$client_info = $model_Obj->shared_model->get_client_info($site_url);
		if (count($client_info) > 0) {
				if(isset($client_info['rc_custom_listing_module_status']) && $client_info['rc_custom_listing_module_status'] == 1){
					add_theme_support('post-thumbnails',array('real_connect')); 
					register_post_type( 'real_connect',$args);
				}
		}	
	}
	add_action( 'init', 'create_post_type_real_connect' );
	
	function real_connect_post_mycustomname_link($post_link, $post = 0, $leavename = false) {
		if($post->post_type == 'real_connect') {
			$property_type = get_post_meta($post->ID, 'rc_subcategory_or_property_type', true );
			$property_type = preg_replace('/\s+/', '', $property_type);
			return home_url('details/'.$property_type.'/'.$post->ID . '/');
		} 
		else {
			return $post_link;
		}
	}
	add_filter('post_type_link', 'real_connect_post_mycustomname_link', 1, 3);
	
/* 
 * create meta box of real_connect post type 
 */
	function add_real_connect_fields_meta_box() {
		add_meta_box(
			'real_connect_fields_meta_box', // $id
			'Custom Listing Fields', // $title
			'real_connect_custom_listing_fields_in_meta_box', // $callback
			'real_connect', // $screen
			'normal', // $context
			'high' // $priority
		);
	}
	add_action( 'add_meta_boxes', 'add_real_connect_fields_meta_box' );

/*
 * custom listing fields list
 */ 

	function real_connect_custom_listing_fields_in_meta_box() {
		echo '<input type="hidden" name="real_conenct_meta_box_nonce" value="'.wp_create_nonce( basename(__FILE__) ).'">';
		include_once(LoadPHPFile('/RealConnect/page-templates/admin/rc_custom_listing_fields.php'));
	
	}

/*
 * 
 *save custom listing data in meta table 
 */
	function save_real_conenct_custom_listing_fields_in_meta( $post_id ) { 
	    
		 // verify nonce
		if (isset($_POST['real_conenct_meta_box_nonce']) &&  !wp_verify_nonce( $_POST['real_conenct_meta_box_nonce'], basename(__FILE__) ) ) {
			return $post_id; 
		}

		// check autosave
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return $post_id;
		}
		
		// check permissions
		if (isset($_POST['post_type']) &&  'page' === $_POST['post_type'] ) {
			if ( !current_user_can( 'edit_page', $post_id ) ) {
				return $post_id;
			} elseif ( !current_user_can( 'edit_post', $post_id ) ) {
				return $post_id;
			}  
		}
		// rc add mls listing form field array key name
		$rc_post_array_parent_field_key = 'real_connect_fields';	
		if(isset($_POST['post_type']) && ($_POST['post_type'] == 'real_connect') && isset($_POST[$rc_post_array_parent_field_key]) ){
			$rc_fields_vlues_array = $_POST[$rc_post_array_parent_field_key];
			foreach($rc_fields_vlues_array as $rc_field_key=>$rc_values){
				
				$old = get_post_meta( $post_id, $rc_field_key, true );
				$new = $_POST[$rc_post_array_parent_field_key][$rc_field_key];
			
				if ($new !== $old ) {
					update_post_meta( $post_id, $rc_field_key, $new );
				} elseif ( '' === $new && $old ) {
				//delete_post_meta( $post_id, 'real_connect_fields', $old );
				}
			}
			if(get_post_status($post_id) == "publish" ){
				data_formate_for_algolia($post_id,'insert');
		    }
		}
	}
	add_action( 'save_post', 'save_real_conenct_custom_listing_fields_in_meta' );

/*
 * Add the custom columns to the real_connect post type:
 */ 

	function set_custom_edit_real_connect_columns($columns) {
	
		unset( $columns['author'] );
		unset( $columns['date'] );
		$columns['post_id'] = __( 'Mls number', 'your_text_domain' );
		$columns['rc_street_address'] = __( 'Street Address', 'your_text_domain' );
		$columns['rc_city'] = __( 'City', 'your_text_domain' );
		$columns['rc_state'] = __( 'State', 'your_text_domain' );
		//$columns['rc_zip'] = __( 'Zip', 'your_text_domain' );
		$columns['rc_price'] = __( 'Price', 'your_text_domain' );
		$columns['rc_subcategory_or_property_type'] = __( 'Property type', 'your_text_domain' );
		$columns['date'] = __( 'Date', 'your_text_domain' );
    
		return $columns;
	}
 	add_filter( 'manage_real_connect_posts_columns', 'set_custom_edit_real_connect_columns' );

/*
 *  Add the data to the custom columns for the real_connect post type 
 */

	function custom_real_connect_column( $column, $post_id ) {
	    
		$rc_meta_value = get_post_meta($post_id, $column, true);
		switch ( $column ) {
			case 'post_id':
			    echo $post_id;
				break;
				
			default: 
			if(isset($rc_meta_value)){
				echo $rc_meta_value;
			}	
			
		}
	}
	add_action( 'manage_real_connect_posts_custom_column' , 'custom_real_connect_column', 10, 2 );

/*
* real-connect post type filter of  field 
*/ 

	function rc_filter_sortable_columns( $columns ) {

		$columns['post_id'] = 'post_id';
		$columns['rc_city'] = 'rc_city';
		$columns['rc_state'] = 'rc_state';
		$columns['rc_price'] = 'rc_price';
		$columns['rc_subcategory_or_property_type'] = 'rc_subcategory_or_property_type';

		return $columns;
	}
	add_filter( 'manage_edit-real_connect_sortable_columns', 'rc_filter_sortable_columns' );
	

	

/*
 *  Only run our customization on the 'edit.php' page in the admin. 
 */
 
	function real_connect_edit_filter_load() {
		add_filter( 'request', 'sort_real_connect' );
	}
	add_action( 'load-edit.php', 'real_connect_edit_filter_load' );

/*
 *  Sorts the sort_real_connect. 
 */
	function sort_real_connect( $vars ) {
           
		/* Check if we're viewing the 'movie' post type. */
		if ( isset( $vars['post_type'] ) && 'real_connect' == $vars['post_type'] ) {

			/* Check if 'orderby' is set to 'rc_subcategory_or_property_type'. */
			if ( isset( $vars['orderby'] ) && 'rc_city' == $vars['orderby'] ) {

				/* Merge the query vars with our custom variables. */
				$vars = array_merge(
					$vars,
					array(
						'meta_key' => 'rc_city',
						'orderby' => 'rc_city'
					)
				);
			}
			/* Check if 'orderby' is set to 'rc_subcategory_or_property_type'. */
			if ( isset( $vars['orderby'] ) && 'rc_state' == $vars['orderby'] ) {

				/* Merge the query vars with our custom variables. */
				$vars = array_merge(
					$vars,
					array(
						'meta_key' => 'rc_state',
						'orderby' => 'rc_state'
					)
				);
			}
			/* Check if 'orderby' is set to 'rc_subcategory_or_property_type'. */
			if ( isset( $vars['orderby'] ) && 'rc_price' == $vars['orderby'] ) {

				/* Merge the query vars with our custom variables. */
				$vars = array_merge(
					$vars,
					array(
						'meta_key' => 'rc_price',
						'orderby' => 'rc_price'
					)
				);
			}
			/* Check if 'orderby' is set to 'rc_subcategory_or_property_type'. */
			if ( isset( $vars['orderby'] ) && 'rc_subcategory_or_property_type' == $vars['orderby'] ) {

				/* Merge the query vars with our custom variables. */
				$vars = array_merge(
					$vars,
					array(
						'meta_key' => 'rc_subcategory_or_property_type',
						'orderby' => 'rc_subcategory_or_property_type'
					)
				);
			}
	}

	return $vars;
}

/* Filter the RC Custom mls Single Post Template with our custom function*/

function rc_custom_mls_single_post_template($single) {

    global $wp_query, $post;

    /* Checks for single template by post type */
    if ( $post->post_type == 'real_connect' ) {
        if ( file_exists(LoadPHPFile('/RealConnect/views/main/rc_custom_mls_single_post_template.php')) ) {
            return LoadPHPFile('/RealConnect/views/main/rc_custom_mls_single_post_template.php');
        }
    }

    return $single;

}
add_filter('single_template', 'rc_custom_mls_single_post_template');


/*
*  create data formate for algolia 
*/ 
function data_formate_for_algolia($rc_post_id,$action){
	$rc_meta_values = get_post_meta($rc_post_id);
	
	$meta_data = array();
	foreach($rc_meta_values as $rc_meta_key=>$rc_meta_value){
	$meta_data[$rc_meta_key] = $rc_meta_value[0];
	}
	
	$default_img = LoadAssetFile('/RealConnect/images/placeholder.png');
	if ( has_post_thumbnail() ) {
		$image_url=  wp_get_attachment_url( get_post_thumbnail_id($rc_post_id));
	}
	//$image_url=  get_the_post_thumbnail_url($rc_post_id,'full');
		if(empty($image_url)){
			$image_url = $default_img; 
		}
	//ADDRESS
	$address = '';
	if(isset($meta_data['rc_street_address']) && !empty($meta_data['rc_street_address'])){
		$address = titleCase(trim($meta_data['rc_street_address']));
	}
	//city
	$city = '';
	if(isset($meta_data['rc_city']) && !empty($meta_data['rc_city'])){
		$city = $meta_data['rc_city'];
	}
	//price
	$price = '';
	if(isset($meta_data['rc_price']) && !empty($meta_data['rc_price'])){
		$price = $meta_data['rc_price'];
	}
	//property type
	$property_type = '';
	if(isset($meta_data['rc_subcategory_or_property_type']) && !empty($meta_data['rc_subcategory_or_property_type'])){
		
		$property_type = $meta_data['rc_subcategory_or_property_type'];
	}
	//beds
	$beds = '';
	if(isset($meta_data['rc_of_beds']) && !empty($meta_data['rc_of_beds'])){
		$beds = $meta_data['rc_of_beds'];
	}
	//acreage
	$acreage = '';
	if(isset($meta_data['rc_acres']) && !empty($meta_data['rc_acres'])){
		$acreage = $meta_data['rc_acres'];
	}
	//sqr_fit
	$sqr_fit = '';
	if(isset($meta_data['rc_sq_ft_finished']) && !empty($meta_data['rc_sq_ft_finished'])){
		$sqr_fit = $meta_data['rc_sq_ft_finished'];
	}
	$insert_data = array(
		"property_type" => strtolower($property_type),
		"price"         => (int)$price,
		"address"       => $address,
		"sqr_fit"       => (int)$sqr_fit,
		"beds"          => (int)$beds,
		"acreage"       => (float)$acreage,
		"city"          => $city,
		"img_url"       => $image_url,
		"website_url"   => site_url(),
		"wp_rc_post_id" => (int)$rc_post_id,
		"objectID"      =>  site_url()."-".$rc_post_id
		);
	
	save_real_connect_post_data_in_algolia($insert_data,$action);
}

/*
* Update real connect post
*/ 
function real_connect_update_post($post_ID, $post_after, $post_before){
	
	if (!isset($post_after->ID) || $post_after->post_type != 'real_connect'){
        return;
    }
    //define action which are apply in algolia
	$action ='';
    if($post_after->post_status == "publish"){
		$action = "update";
	}
	if($post_after->post_status == "trash"){
		$action = "delete";
	}
	
	
    $rc_post_id = $post_after->ID;
    $rc_meta_values = get_post_meta($rc_post_id);
    if(isset($rc_meta_values['rc_subcategory_or_property_type'])){
       data_formate_for_algolia($rc_post_id,$action);
    }
    
}

add_action( 'post_updated', 'real_connect_update_post', 10, 3 ); //don't forget the last argument to allow all three arguments of the function


/*  
* save real conenct post data in algolia
*/ 
function save_real_connect_post_data_in_algolia($data = null,$action = ''){
	
	if(empty($action)){
		return;
	}
	if(empty($data) || $data == null){
		return; 
	}
	try{
		require_once(LoadPHPFile('/RealConnect/algoliasearch-client-php-master/algoliasearch.php'));
		
		require_once(LoadPHPFile('/RealConnect/algoliasearch-client-php-master/algolia_api_credentials.php'));
		
		// algolia api credentials
		$client = new \AlgoliaSearch\Client(algolia_application_id, algolia_admin_api_key);
		// select indeces of algolia 
		$index = $client->initIndex(algolia_index_name);
		if($action == 'insert' || $action == 'update'){
			$res = $index->addObjects(array($data));
			aglolia_log("on ".date("Y-m-d h:i:s A")." $action Objects in algolia, object id: ".$data['objectID']." \n");

		}else if($action == 'delete'){
			$res = $index->deleteObjects(array($data['objectID']));
			aglolia_log("on ".date("Y-m-d h:i:s A")." $action Objects in algolia, object id: ".$data['objectID']."  \n");

		}
	}catch(Exception $e) {
		aglolia_log(date("Y-m-d H:i:s").' Message: ' .$e->getMessage()." \n");
	}
	
}
/*
* Algolia create log file
*/ 
function aglolia_log ($str) {
  error_log("$str", 3, LoadPHPFile('/RealConnect/algoliasearch-client-php-master/algolia.log'));
}

/*
* Create shortcode for alglolia form
*/  
function create_shortcode_for_algolia_search_form(){
	
	include_once(LoadPHPFile('/RealConnect/Model/shared_model.php'));
	$site_url = get_site_url();
	$model_Obj = new \stdClass();
	$model_Obj->shared_model = new Shared_model();
	$client_info = $model_Obj->shared_model->get_client_info($site_url);
	if (count($client_info) > 0) {
		if(isset($client_info['mls_feed']) && $client_info['mls_feed'] == 'flexmls'){
			include_once(LoadPHPFile('/RealConnect/views/main/algolia_flexsearch_form.php'));
		}else{
			include_once(LoadPHPFile('/RealConnect/views/main/algolia_search_form.php'));
		}
	}
}
add_shortcode( 'rc_search_form', 'create_shortcode_for_algolia_search_form' );


/*
 * Plugin Menu in dashboard
 */ 
add_action('admin_menu', 'rc_dashboard_menus'); 
function rc_dashboard_menus(){
    //add_menu_page('RealConnect', 'RealConnect', 'manage_options', 'RealConnect', 'Dashboard' );
    // check real custom post enable or not
		include_once(LoadPHPFile( '/RealConnect/Model/shared_model.php'));
		$site_url = get_site_url();
		$model_Obj = new \stdClass();
		$model_Obj->shared_model = new Shared_model();
		$client_info = $model_Obj->shared_model->get_client_info($site_url);
		if (count($client_info) > 0) {
				if(isset($client_info['rc_custom_listing_module_status']) && $client_info['rc_custom_listing_module_status'] == 1){
					add_menu_page('RealConnect', 'RealConnect', 'manage_options', 'RealConnect', 'rc_dashboard_page', 'dashicons-admin-home' );
					add_submenu_page('RealConnect', 'Add Custom Listing', 'Add Custom Listing', 'manage_options', 'post-new.php?post_type=real_connect','',40 );
					add_submenu_page('RealConnect', 'Settings', 'Settings', 'manage_options', 'rc-configuration','rc_plugin_settings_page_content' );
					add_submenu_page('RealConnect', 'Custom CSS', 'Custom CSS', 'manage_options', 'rc-custom-css','rc_custom_css_page_content' );
				
				}else{	
				add_menu_page('RealConnect Configuration', 'RealConnect', 'manage_options', 'rc-configuration', 'rc_dashboard_page' );
				add_submenu_page('rc-configuration', 'Settings', 'Settings', 'manage_options', 'rc-configuration','rc_plugin_settings_page_content' );
				add_submenu_page('rc-configuration', 'Custom CSS', 'Custom CSS', 'manage_options', 'rc-custom-css','rc_custom_css_page_content' );

			}
		}
}       

function rc_dashboard_page()
{
	echo '<h1>RealConnect</h1>';
}

add_action( 'admin_init', 'rc_custom_css_form_init' );
function rc_custom_css_form_init() {
    register_setting(
        'rc_custom_css', // A settings group name. Must exist prior to the register_setting call. This must match the group name in settings_fields()
        'rc_custom_css_form_data' //The name of an option to sanitize and save.
    );
    add_settings_section( 'rc_section_id', 'RealConnect > Custom CSS', 'rc_section_callback', 'rc_custom_css_page' );
    add_settings_field( 'rc_field_name_id', 'Add your custom CSS', 'rc_custom_css_callback', 'rc_custom_css_page', 'rc_section_id' );
}

function rc_section_callback() {
	settings_errors(); 
	echo "Tip: Standard CSS formatting is required. If you don't know what this is, ask your friendly neighborhood web developer.";
}

function rc_custom_css_callback() {
    $option = get_option( 'rc_custom_css_form_data' );
    if ( isset( $option['rc_custom_css'] ) ) {
		$custom_css = esc_attr( $option['rc_custom_css'] );
    }else{
		$custom_css = '';
	}
    echo "<textarea rows='15' cols='40' style='width:100%;max-width:100%;background:#fff;height: 500px;' name='rc_custom_css_form_data[rc_custom_css]' >".$custom_css."</textarea>";
}

function rc_custom_css_page_content()
{ 
	if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( __( 'You do not have sufficient permissions to access this page.', 'yasr' ) );
    }
	 ?>
    <div class="wrap">
        <form method="post" action="options.php" enctype="multipart/form-data">  
			 <?php settings_fields( 'rc_custom_css' );
				do_settings_sections( 'rc_custom_css_page' );
				submit_button( 'Save' );
            ?>
		</form>
    </div>
    <?php
}

add_action('wp_footer','rc_custom_css_display');
function rc_custom_css_display()
{
	$option = get_option( 'rc_custom_css_form_data' );
	$rc_settings = get_option( 'rc_plugin_settings_form_data' );
    if ( isset( $option['rc_custom_css'] ) ) {
		$custom_css = esc_attr( $option['rc_custom_css'] );
    }else{
		$custom_css = '';
	}
	if ( isset( $rc_settings['rc_background_color'] ) ) {
		$rc_background_color = 'body{background:'.esc_attr( $rc_settings['rc_background_color'] ).'}';
    }else{
		$rc_background_color = '';
	}
	if ( isset( $rc_settings['rc_text_color'] ) ) {
		$rc_text_color = 'body{color:'.esc_attr( $rc_settings['rc_text_color'] ).'}';
    }else{
		$rc_text_color = '';
	}
    echo '<style>'.$custom_css.' '.$rc_background_color.' '.$rc_text_color.'</style>';
}

add_action( 'admin_init', 'rc_plugin_settings_form_init' );
function rc_plugin_settings_form_init() {
    register_setting(
        'rc_plugin_settings', // A settings group name. Must exist prior to the register_setting call. This must match the group name in settings_fields()
        'rc_plugin_settings_form_data' //The name of an option to sanitize and save.
    );
    add_settings_section( 'rc_section_id', 'Settings', 'rc_plugin_settings_section_callback', 'rc_plugin_settings_page' );
    add_settings_field( 'rc_sidebar', 'Detail Page Sidebar', 'rc_plugin_settings_page_callback', 'rc_plugin_settings_page', 'rc_section_id',array ( 'rc_field' => 'rc_sidebar' ) );
    add_settings_field( 'rc_detail_view', 'Detail Page Content', 'rc_plugin_settings_page_callback', 'rc_plugin_settings_page', 'rc_section_id',array ( 'rc_field' => 'rc_detail_view' ) );
    add_settings_field( 'rc_background_color', 'Background Color', 'rc_plugin_settings_page_callback', 'rc_plugin_settings_page', 'rc_section_id',array ( 'rc_field' => 'rc_background_color' ) );
    add_settings_field( 'rc_text_color', 'Text Color', 'rc_plugin_settings_page_callback', 'rc_plugin_settings_page', 'rc_section_id',array ( 'rc_field' => 'rc_text_color' ) );
    add_settings_field( 'rc_listing_page_layout', 'Listing Page layout', 'rc_plugin_settings_page_callback', 'rc_plugin_settings_page', 'rc_section_id',array ( 'rc_field' => 'rc_listing_page_layout' ) );

}

function rc_plugin_settings_section_callback() {
    echo "Some Plugin Settings";
     settings_errors(); 
}

function rc_plugin_settings_page_callback($args) {
    $option = get_option( 'rc_plugin_settings_form_data' );
    if ( isset( $option['rc_sidebar'] ) ) {
		$rc_sidebar = esc_attr( $option['rc_sidebar'] );
    }else{
		$rc_sidebar = '';
	}
    if ( isset( $option['rc_detail_view'] ) ) {
		$rc_detail_view = esc_attr( $option['rc_detail_view'] );
    }else{
		$rc_detail_view = '';
	}
    if ( isset( $option['rc_background_color'] ) ) {
		$rc_background_color = esc_attr( $option['rc_background_color'] );
    }else{
		$rc_background_color = '';
	}
    if ( isset( $option['rc_text_color'] ) ) {
		$rc_text_color = esc_attr( $option['rc_text_color'] );
    }else{
		$rc_text_color = '';
	}
	if ( isset( $option['rc_listing_page_layout'] ) ) {
		$rc_listing_page_layout = esc_attr( $option['rc_listing_page_layout'] );
    }else{
		$rc_listing_page_layout = '';
	}
	
	
	if ( 'rc_sidebar' === $args[ 'rc_field' ] ) {
    ?>
    <select name="rc_plugin_settings_form_data[rc_sidebar]">
		<option value="">Default</option>
		<option value="rc-sidebar-1" <?php if($rc_sidebar == 'rc-sidebar-1'): echo "selected"; endif; ?>>Sidebar 1</option>
		<option value="rc-sidebar-2" <?php if($rc_sidebar == 'rc-sidebar-2'): echo "selected"; endif; ?>>Sidebar 2</option>
    </select>
    <?php } else if('rc_detail_view' === $args[ 'rc_field' ] ){ ?>
    <select name="rc_plugin_settings_form_data[rc_detail_view]">
		<option value="">Default</option>
		<option value="rc-detail-view-1" <?php if($rc_detail_view == 'rc-detail-view-1'): echo "selected"; endif; ?>>Detail View 1</option>
		<option value="rc-detail-view-2" <?php if($rc_detail_view == 'rc-detail-view-2'): echo "selected"; endif; ?>>Detail View 2</option>
    </select>
    <?php } else if('rc_background_color' === $args[ 'rc_field' ] ){ ?>
    
    <input type="text" name="rc_plugin_settings_form_data[rc_background_color]" value="<?php echo $rc_background_color; ?>" Placeholder="#000000"/>
    
    <?php } else if('rc_text_color' === $args[ 'rc_field' ] ){ ?>
    <input type="text" name="rc_plugin_settings_form_data[rc_text_color]" value="<?php echo $rc_text_color; ?>" Placeholder="#000000"/>
    <?php
	}else if('rc_listing_page_layout' === $args[ 'rc_field' ] ){ ?>
    <select name="rc_plugin_settings_form_data[rc_listing_page_layout]">
		<option value="">Default</option>
		<option value="rc-listing-layout-1" <?php if($rc_listing_page_layout == 'rc-listing-layout-1'): echo "selected"; endif; ?>>Layout 1</option>
		<option value="rc-listing-layout-2" <?php if($rc_listing_page_layout == 'rc-listing-layout-2'): echo "selected"; endif; ?>>Layout 2</option>
    </select>
    <?php }
}

function rc_plugin_settings_page_content()
{ 
	if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( __( 'You do not have sufficient permissions to access this page.', 'RealConnect' ) );
    }
	 ?>
    <div class="wrap">
        <form method="post" action="options.php" enctype="multipart/form-data">  
			 <?php settings_fields( 'rc_plugin_settings' );
				do_settings_sections( 'rc_plugin_settings_page' );
				submit_button( 'Update Settings' );
            ?>
		</form>
    </div>
    <?php
}

function LoadAssetFile($file)
{
	
	$theme_dir= get_stylesheet_directory();
	$theme_uri= get_stylesheet_directory_uri(); 
	$plugin_dir_url =  plugin_dir_url('');
	
	//$file='/'.$file;
	
	if(file_exists($theme_dir.'/'.$file))
	{
		//echo $theme_dir.DS.$file;
		return str_replace('//RealConnect','/RealConnect',$theme_uri.'/'.$file);
	}
	else{
		return str_replace('//RealConnect','/RealConnect',$plugin_dir_url.'/'.$file);
	}
	
}



function LoadPHPFile($file)
{
	
	$theme_dir= get_stylesheet_directory(); 
	$plugin_dir =  ABSPATH . 'wp-content/plugins/';
    $file_path = str_replace('//RealConnect','/RealConnect',$theme_dir.'/'.$file);    
	
	if(file_exists($file_path))
	{
		//echo $theme_dir.DS.$file;
		return str_replace('//RealConnect','/RealConnect',$theme_dir.'/'.$file);
	}
	else{
		return str_replace('//RealConnect','/RealConnect',$plugin_dir.'/'.$file);
	}
	
}

//exit(LoadPHPFile('/RealConnect/views/main/rc_custom_mls_details_view.php'));