<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       http://example.com
 * @since      1.0.0
 *
 * @package    WP_Zillow_Review
 * @subpackage WP_Zillow_Review/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    WP_Zillow_Review
 * @subpackage WP_Zillow_Review/admin
 * @author     Your Name <email@example.com>
 */
class WP_Zillow_Review_Admin {

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

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

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

		$this->_token = $plugintoken;
		$this->version = $version;
		//for testing==============
	$this->version = time();
		//===================
				

	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in WP_Zillow_Review_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The WP_Zillow_Review_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */
		//only load for this plugin wp_zillow-settings-pricing
		if(isset($_GET['page'])){
			if($_GET['page']=="wp_zillow-reviews" || $_GET['page']=="wp_zillow-templates_posts" || $_GET['page']=="wp_zillow-get_zillow" || $_GET['page']=="wp_zillow-get_pro"){
			wp_enqueue_style( $this->_token, plugin_dir_url( __FILE__ ) . 'css/wpzillow_admin.css', array(), $this->version, 'all' );
			wp_enqueue_style( $this->_token."_wpzillow_w3", plugin_dir_url( __FILE__ ) . 'css/wpzillow_w3.css', array(), $this->version, 'all' );
			}
			//load template styles for wp_zillow-templates_posts page
			if($_GET['page']=="wp_zillow-templates_posts"|| $_GET['page']=="wp_zillow-get_pro"){
				//enque template styles for preview
				wp_enqueue_style( $this->_token."_style1", plugin_dir_url(dirname(__FILE__)) . 'public/css/wprev-public_template1.css', array(), $this->version, 'all' );
			}
		}

	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in WP_Zillow_Review_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The WP_Zillow_Review_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */
		

		//scripts for all pages in this plugin
		if(isset($_GET['page'])){
			if($_GET['page']=="wp_zillow-reviews" || $_GET['page']=="wp_zillow-templates_posts" || $_GET['page']=="wp_zillow-get_zillow" || $_GET['page']=="wp_zillow-get_pro"){
				//pop-up script
				wp_register_script( 'simple-popup-js',  plugin_dir_url( __FILE__ ) . 'js/wpzillow_simple-popup.min.js' , '', $this->version, false );
				wp_enqueue_script( 'simple-popup-js' );
				
			}
		}
		
	
		//scripts for review list page
		if(isset($_GET['page'])){
			if($_GET['page']=="wp_zillow-reviews"){
				//admin js
				wp_enqueue_script('wpzillow_review_list_page-js', plugin_dir_url( __FILE__ ) . 'js/wpzillow_review_list_page.js', array( 'jquery','media-upload','thickbox' ), $this->version, false );
				//used for ajax
				wp_localize_script('wpzillow_review_list_page-js', 'adminjs_script_vars', 
					array(
					'wpzillow_nonce'=> wp_create_nonce('randomnoncestring')
					)
				);
				
 				wp_enqueue_script('thickbox');
				wp_enqueue_style('thickbox');
		 
				wp_enqueue_script('media-upload');
				wp_enqueue_script('wptuts-upload');

			}
			
			//scripts for templates posts page
			if($_GET['page']=="wp_zillow-templates_posts"){
			
				//admin js
				wp_enqueue_script('wpzillow_templates_posts_page-js', plugin_dir_url( __FILE__ ) . 'js/wpzillow_templates_posts_page.js', array( 'jquery' ), $this->version, false );
				//used for ajax
				wp_localize_script('wpzillow_templates_posts_page-js', 'adminjs_script_vars', 
					array(
					'wpzillow_nonce'=> wp_create_nonce('randomnoncestring'),
					'pluginsUrl' => wprev_zillow_plugin_url
					)
				);
 				wp_enqueue_script('thickbox');
				wp_enqueue_style('thickbox');
				
				//add color picker here
				wp_enqueue_style( 'wp-color-picker' );
				//enque alpha color add-on wpzillow-wp-color-picker-alpha.js
				wp_enqueue_script( 'wp-color-picker-alpha', plugin_dir_url( __FILE__ ) . 'js/wpzillow-wp-color-picker-alpha.js', array( 'wp-color-picker' ), '2.1.2', false );

			}
		}
		
	}
	
	public function add_menu_pages() {

		/**
		 * adds the menu pages to wordpress
		 */

		$page_title = 'WP Zillow Reviews : Review List';
		$menu_title = 'WP Zillow';
		$capability = 'manage_options';
		$menu_slug = 'wp_zillow-reviews';
		
		// Now add the submenu page for the actual reviews list
		$submenu_page_title = 'WP Reviews Pro : Review List';
		$submenu_title = 'Review List';
		$submenu_slug = 'wp_zillow-reviews';
		
		add_menu_page($page_title, $menu_title, $capability, $menu_slug, array($this,'wp_zillow_reviews'),'dashicons-star-half');
		
		add_submenu_page($menu_slug, $submenu_page_title, $submenu_title, $capability, $submenu_slug, array($this,'wp_zillow_reviews'));
		
		
		//add_menu_page($page_title, $menu_title, $capability, $menu_slug, array($this,'wp_zillow_settings'),'dashicons-star-half');
		
		// We add this submenu page with the same slug as the parent to ensure we don't get duplicates
		//$sub_menu_title = 'Get FB Reviews';
		//add_submenu_page($menu_slug, $page_title, $sub_menu_title, $capability, $menu_slug, array($this,'wp_zillow_settings'));
		
		// Now add the submenu page for zillow
		$submenu_page_title = 'WP Zillow Reviews : Zillow';
		$submenu_title = 'Get Zillow Reviews';
		$submenu_slug = 'wp_zillow-get_zillow';
		add_submenu_page($menu_slug, $submenu_page_title, $submenu_title, $capability, $submenu_slug, array($this,'wp_zillow_getzillow'));
		

		
		// Now add the submenu page for the reviews templates
		$submenu_page_title = 'WP Zillow Reviews : Templates';
		$submenu_title = 'Templates';
		$submenu_slug = 'wp_zillow-templates_posts';
		add_submenu_page($menu_slug, $submenu_page_title, $submenu_title, $capability, $submenu_slug, array($this,'wp_zillow_templates_posts'));
		
		// Now add the submenu page for the reviews templates
		//$submenu_page_title = 'WP Zillow Reviews : Upgrade';
		//$submenu_title = 'Get Pro';
//$submenu_slug = 'wp_zillow-get_pro';
		//add_submenu_page($menu_slug, $submenu_page_title, $submenu_title, $capability, $submenu_slug, array($this,'wp_fb_getpro'));

	}
	//add link to menu
	public function wprev_zillow_add_external_link_admin_submenu() {
		global $submenu;

		$menu_slug = 'wp_zillow-reviews'; // used as "key" in menus
		$menu_pos = 1; // whatever position you want your menu to appear

		// add the external links to the slug you used when adding the top level menu
		$submenu[$menu_slug][] = array('<div id="wprev-660233">Go Pro!</div>', 'manage_options', 'https://wpreviewslider.com/');
	}
	public function wpse_660233_add_jquery() 
	{
		?>
		<script type="text/javascript">
			jQuery(document).ready( function($) {   
				$('#wprev-660233').parent().attr('target','_blank');  
			});
		</script>
		<?php
	}
	
	public function wp_zillow_reviews() {
		require_once plugin_dir_path( __FILE__ ) . '/partials/review_list.php';
	}
	
	public function wp_zillow_templates_posts() {
		require_once plugin_dir_path( __FILE__ ) . '/partials/templates_posts.php';
	}
	public function wp_zillow_getzillow() {
		require_once plugin_dir_path( __FILE__ ) . '/partials/get_zillow.php';
	}
	public function wp_fb_getpro() {
		require_once plugin_dir_path( __FILE__ ) . '/partials/get_pro.php';
	}

	/**
	 * custom option and settings on zillow page
	 */
	 //===========start zillow page settings===========================================================
	public function wpzillow_zillow_settings_init()
	{
	
		// register a new setting for "wp_zillow-get_zillow" page
		register_setting('wp_zillow-get_zillow', 'wpzillow_zillow_settings');
		
		// register a new section in the "wp_zillow-get_zillow" page
		add_settings_section(
			'wpzillow_zillow_section_developers',
			'',
			array($this,'wpzillow_zillow_section_developers_cb'),
			'wp_zillow-get_zillow'
		);
		
		//register zillow business url input field
		add_settings_field(
			'zillow_business_url', // as of WP 4.6 this value is used only internally
			'Zillow Write Review URL',
			array($this,'wpzillow_field_zillow_business_id_cb'),
			'wp_zillow-get_zillow',
			'wpzillow_zillow_section_developers',
			[
				'label_for'         => 'zillow_business_url',
				'class'             => 'wpzillow_row',
				'wpzillow_custom_data' => 'custom',
			]
		);

		//Turn on Zillow Reviews Downloader
		add_settings_field("zillow_radio", "Turn On Zillow Reviews", array($this,'zillow_radio_display'), "wp_zillow-get_zillow", "wpzillow_zillow_section_developers",
			[
				'label_for'         => 'zillow_radio',
				'class'             => 'wpzillow_row',
				'wpzillow_custom_data' => 'custom',
			]); 
	
	}
	//==== developers section cb ====
	public function wpzillow_zillow_section_developers_cb($args)
	{
		//echos out at top of section
		echo "<p>Use this page to download your newest 15 Zillow reviews and save them in your Wordpress database. The Pro version will allow you to grab all your reviews. They will show up on the Review List page once downloaded. Any new reviews you get are downloaded once a day. The Pro version can download from multiple Zillow pages.</p>";
	}
	
	//==== field cb =====
	public function wpzillow_field_zillow_business_id_cb($args)
	{
		// get the value of the setting we've registered with register_setting()
		$options = get_option('wpzillow_zillow_settings');

		// output the field
		?>
		<input id="<?= esc_attr($args['label_for']); ?>" data-custom="<?= esc_attr($args['wpzillow_custom_data']); ?>" type="text" name="wpzillow_zillow_settings[<?= esc_attr($args['label_for']); ?>]" placeholder="" value="<?php echo esc_url($options[$args['label_for']]); ?>">
		
		<p class="description">
			<?= esc_html__('Enter the Zillow Write Review URL for your page and click Save Settings.', 'wp_zillow-settings'); ?>
			</br>
			<a href="https://wpreviewslider.com/wp-content/uploads/2023/02/zillow_instr.mp4" target="_blank" style="text-decoration: none;"><?= esc_html__('Video Instructions', 'wp_zillow-settings'); ?></a>
			</br>
			<?= esc_html__('Ex: https://www.zillow.com/reviews/write/?s=X1-ZUvu3i2bzw4m4p_46au8', 'wp_zillow-settings'); ?>
			</br>
			<?= esc_html__('Note: If you are unable to retrieve reviews, please contact us and send us the page URL.', 'wp_zillow-settings'); ?>
			</br>
		</p>
		<?php
	}
	public function zillow_radio_display($args)
		{
		$options = get_option('wpzillow_zillow_settings');
		if(!isset($options[esc_attr($args['label_for'])])){
			$options[esc_attr($args['label_for'])]=='yes';
		}
		
		   ?>
				<input type="radio" name="wpzillow_zillow_settings[<?= esc_attr($args['label_for']); ?>]" value="yes" <?php checked('yes', $options[$args['label_for']], true); ?>>Yes&nbsp;&nbsp;&nbsp;
				<input type="radio" name="wpzillow_zillow_settings[<?= esc_attr($args['label_for']); ?>]" value="no" <?php checked('no', $options[$args['label_for']], true); ?>>No
		   <?php
		}
	//=======end zillow page settings========================================================

	
	
	/**
	 * replaces insert into post text on media uploader when uploading reviewer avatar
	 * @access  public
	 * @since   1.0.0
	 * @return  void
	 */	
	public function wpzillow_media_text() {
		global $pagenow;
		if ( 'media-upload.php' == $pagenow || 'async-upload.php' == $pagenow ) {
			// Now we'll replace the 'Insert into Post Button' inside Thickbox
			add_filter( 'gettext', array($this,'replace_thickbox_text') , 1, 3 );
		}
	}
	 
	public function replace_thickbox_text($translated_text, $text, $domain) {
		if ('Insert into Post' == $text) {
			$referer = strpos( wp_get_referer(), 'wp_zillow-reviews' );
			if ( $referer != '' ) {
				return __('Use as Reviewer Avatar', 'wp-zillow-review-slider' );
			}
		}
		return $translated_text;
	}
	

	/**
	 * download csv file of reviews
	 * @access  public
	 * @since   1.0.0
	 * @return  void
	 */	
	public function wpzillow_download_csv() {
      global $pagenow;
      if ($pagenow=='admin.php' && current_user_can('export') && isset($_GET['taction']) && $_GET['taction']=='downloadallrevs' && $_GET['page']=='wp_zillow-reviews') {
        header("Content-type: application/x-msdownload");
        header("Content-Disposition: attachment; filename=reviewdata.csv");
        header("Pragma: no-cache");
        header("Expires: 0");

		global $wpdb;
		$table_name = $wpdb->prefix . 'wpzillow_reviews';		
		$downloadreviewsrows = $wpdb->get_results(
				$wpdb->prepare("SELECT * FROM ".$table_name."
				WHERE id>%d ", "0"),'ARRAY_A'
			);
		$file = fopen('php://output', 'w');
		$delimiter=";";
		
		foreach ($downloadreviewsrows as $line) {
		    fputcsv($file, $line, $delimiter);
		}

        exit();
      }
    }	
	
	/**
	 * adds drop down menu of templates on post edit screen
	 * @access  public
	 * @since   1.0.0
	 * @return  void
	 */	
	//add_action('media_buttons','add_sc_select',11);
	public function add_sc_select(){
		//get id's and names of templates that are post type 
		global $wpdb;
		$table_name = $wpdb->prefix . 'wpzillow_post_templates';
		$currentforms = $wpdb->get_results("SELECT id, title, template_type FROM $table_name WHERE template_type = 'post'");
		if(count($currentforms)>0){
		echo '&nbsp;<select id="wprs_sc_select"><option value="select">Review Template</option>';
		foreach ( $currentforms as $currentform ){
			$shortcodes_list .= '<option value="[wpzillow_usetemplate tid=\''.$currentform->id.'\']">'.$currentform->title.'</option>';
		}
		 echo $shortcodes_list;
		 echo '</select>';
		}
	}
	//add_action('admin_head', 'button_js');
	public function button_js() {
			echo '<script type="text/javascript">
			jQuery(document).ready(function(){
			   jQuery("#wprs_sc_select").change(function() {
							if(jQuery("#wprs_sc_select :selected").val()!="select"){
							  send_to_editor(jQuery("#wprs_sc_select :selected").val());
							}
							  return false;
					});
			});
			</script>';
	}
	

	/**
	 * download zillow reviews when clicking the save button on Zillow page
	 * @access  public
	 * @since   1.0.0
	 * @return  void
	 */	
	public function wpzillow_download_zillow() {
      global $pagenow;
      if (isset($_GET['settings-updated']) && $pagenow=='admin.php' && current_user_can('export') && $_GET['page']=='wp_zillow-get_zillow') {
		$this->wpzillow_download_zillow_master();
      }
    }
	
	
	
	//for using curl instead of fopen
	private function file_get_contents_curl($url) {
		$ch = curl_init();

		curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);       

		$data = curl_exec($ch);
		curl_close($ch);

		return $data;
	}
	//fix stringtotime for other languages
	private function myStrtotime($date_string) { 
		$monthnamearray = array(
		'janvier'=>'jan',
		'février'=>'feb',
		'mars'=>'march',
		'avril'=>'apr',
		'mai'=>'may',
		'juin'=>'jun',
		'juillet'=>'jul',
		'août'=>'aug',
		'septembre'=>'sep',
		'octobre'=>'oct',
		'novembre'=>'nov',
		'décembre'=>'dec',
		'gennaio'=>'jan',
		'febbraio'=>'feb',
		'marzo'=>'march',
		'aprile'=>'apr',
		'maggio'=>'may',
		'giugno'=>'jun',
		'luglio'=>'jul',
		'agosto'=>'aug',
		'settembre'=>'sep',
		'ottobre'=>'oct',
		'novembre'=>'nov',
		'dicembre'=>'dec',
		'janeiro'=>'jan',
		'fevereiro'=>'feb',
		'março'=>'march',
		'abril'=>'apr',
		'maio'=>'may',
		'junho'=>'jun',
		'julho'=>'jul',
		'agosto'=>'aug',
		'setembro'=>'sep',
		'outubro'=>'oct',
		'novembro'=>'nov',
		'dezembro'=>'dec',
		'enero'=>'jan',
		'febrero'=>'feb',
		'marzo'=>'march',
		'abril'=>'apr',
		'mayo'=>'may',
		'junio'=>'jun',
		'julio'=>'jul',
		'agosto'=>'aug',
		'septiembre'=>'sep',
		'octubre'=>'oct',
		'noviembre'=>'nov',
		'diciembre'=>'dec',
		'januari'=>'jan',
		'februari'=>'feb',
		'maart'=>'march',
		'april'=>'apr',
		'mei'=>'may',
		'juni'=>'jun',
		'juli'=>'jul',
		'augustus'=>'aug',
		'september'=>'sep',
		'oktober'=>'oct',
		'november'=>'nov',
		'december'=>'dec',
		' de '=>''
		);
		return strtotime(strtr(strtolower($date_string), $monthnamearray)); 
	}
	
	
		
	private function getreviewurlfrommain($urlvalue, $limit=15, $page=1){
					$response = wp_remote_get( $urlvalue );
					if ( is_array( $response ) ) {
					  $header = $response['headers']; // array of http header lines
					  $fileurlcontents = $response['body']; // use the content
					} else {
						echo "Error finding reviews. Please contact plugin support.";
						die();
					}
					
					//$fileurlcontents =$this->file_get_contents_curl_browser($urlvalue,'');
					
					$html = wpzillow_str_get_html($fileurlcontents);

					//find zillow business name and add to db under pagename
					$id ='';
					/*
					if($html->find('div.write-a-review', 0)){
						if($html->find('div.write-a-review', 0)->find('a',0)){
							$id = $html->find('div.write-a-review', 0)->find('a',0)->href;
							$id = substr($id, strpos($id, "s=") + 2);
						}
					}
					*/
					if($html->find('section[id=reviews]', 0)){
						if($html->find('section[id=reviews]', 0)->find('a',0)){
							$id = $html->find('section[id=reviews]', 0)->find('a',0)->href;
							$id = substr($id, strpos($id, "s=") + 2);
						}
					}
					//use the key and the listing id to find review data					
					$rurl ="https://www.zillow.com/ajax/review/ReviewDisplayJSONGetPage.htm?id=".$id."&size=".$limit."&page=".$page."&page_type=received&moderator_actions=0&reviewee_actions=0&reviewer_actions=0&proximal_buttons=1&hasImpersonationPermission=0&service=&sort=1";

					$reviewurl['url'] = esc_url_raw($rurl);
					
					return $reviewurl;
		
	}
	
	
		//for using curl instead of fopen
	private function file_get_contents_curl_browser($url,$cookieval) {
		$agent= 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0';
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_VERBOSE, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_USERAGENT, $agent);
		curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
							'authority: nextdoor.com',
							'pragma: no-cache',
							'cache-control: no-cache',
							'upgrade-insecure-requests: 1',
							'user-agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
							'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 'accept-encoding: gzip, deflate, br',
							'accept-language: en-US,en;q=0.9',
							'cookie: '.$cookieval.''
					));
		curl_setopt($ch, CURLOPT_URL,$url);
		$result=curl_exec($ch);
		curl_close($ch);
		return $result;
	}
	
		
	/**
	 * download zillow reviews
	 * @access  public
	 * @since   1.0.0
	 * @return  void
	 */	
	public function wpzillow_download_zillow_master() {
		//make sure file get contents is turned on for this host
		$errormsg ='';

			global $wpdb;
			$table_name = $wpdb->prefix . 'wpzillow_reviews';
			$options = get_option('wpzillow_zillow_settings');
			//remove whitespaces
			$options['zillow_business_url'] = trim(esc_url($options['zillow_business_url']));
			
			//make sure you have valid url, if not display message
			if (filter_var($options['zillow_business_url'], FILTER_VALIDATE_URL)) {
			  // you're good
			  //echo "valid url";
			  if($options['zillow_radio']=='yes'){
				//echo "passed both tests";
				$stripvariableurl = strtok($options['zillow_business_url'], '?');
				$zillowurl[1] =$options['zillow_business_url'];
				
				//loop to grab pages
				$reviews = [];
				$n=1;
				foreach ($zillowurl as $urlvalue) {
					
					
					//check url to find out what kind of review page this is
					if (strpos($urlvalue, '/write/') !== false) {
						//$urldetails = $this->getreviewurlfrommain($stripvariableurl, $limit=15, $page=1);
						//$urlvalue = $urldetails['url'];
						//if this is a realtor page
						$reviews = $this->wpzillow_revfrompage_realtor($urlvalue);
					} else if(strpos($urlvalue, '/lender-profile/') !== false){
						//for lender profile
						$errormsg = $errormsg . ' Sorry, the free version of this plugin does not currently work for a lender profile url. The Pro version will however using the new Review Funnel feature.';
						$this->errormsg = $errormsg;
						//$reviews = $this->wpzillow_revfrompage_lender($stripvariableurl);
					} else {
						//for lender profile
						$errormsg = $errormsg . ' Please enter a correct write review URL.';
						$this->errormsg = $errormsg;
						//$reviews = $this->wpzillow_revfrompage_lender($stripvariableurl);
					}
				}
				
				//add all new zillow reviews to db
				$insertnum=0;
				if(is_array($reviews)){
					foreach ( $reviews as $stat ){
						$insertnum = $wpdb->insert( $table_name, $stat );
					}
				}
				//reviews added to db
				if($insertnum>0){
					$errormsg = $errormsg . ' Zillow reviews downloaded.';
					$this->errormsg = $errormsg;
				} else {
					$errormsg = $errormsg . ' Unable to find any new reviews.';
					$this->errormsg = $errormsg;
				}
				
			  }
			} else {
				$errormsg = $errormsg . ' Please enter a valid URL.';
				$this->errormsg = $errormsg;
			}
			
			if($options['zillow_radio']=='no'){
				$wpdb->delete( $table_name, array( 'type' => 'Zillow' ) );
				//cancel wp cron job
			}
			

		if($errormsg !=''){
			//echo $errormsg;
		}
	}


	/**
	 * for realtor specific page
	 * @access  public
	 * @since   1.0.0
	 * @return  void
	 */	
	private function wpzillow_revfrompage_realtor($urlvalue) {
		global $wpdb;
		$table_name = $wpdb->prefix . 'wpzillow_reviews';
		
		$reviews = Array();


		$url_components = parse_url($urlvalue);
		parse_str($url_components['query'], $urldetails);
		
		//print_r($urldetails);
		$id = $urldetails['s'];
		
		$pagenum = 1;
		
		//$rurl ="https://www.zillow.com/profile-page/api/public/v1/reviews?encodedZuid=".$id."&profileTypeIds=1%2C2%2C12%2C16&page=".$pagenum."&size=5&sortType=2&sortOrder=2";
				
		$urlval[1]="https://www.zillow.com/profile-page/api/public/v1/reviews?encodedZuid=".$id."&profileTypeIds=1%2C2%2C12%2C16&page=1&size=5&sortType=2&sortOrder=2";
		
		$urlval[2]="https://www.zillow.com/profile-page/api/public/v1/reviews?encodedZuid=".$id."&profileTypeIds=1%2C2%2C12%2C16&page=2&size=5&sortType=2&sortOrder=2";
		
		
		
			
		foreach ($urlval as $rurl) {
			
		$urlvalue = esc_url_raw($rurl);
					
		$data = wp_remote_get( $urlvalue );
				if ( is_wp_error( $data ) ) 
				{
					$response['error_message'] 	= $data->get_error_message();
					$reponse['status'] 		= $data->get_error_code();
					print_r($response);
					die();
				}
				if ( is_array( $data ) ) {
				  $header = $data['headers']; // array of http header lines
				  $body = $data['body']; // use the content
				}
					
				$pagedata = json_decode( $body, true );
				if(!is_array($pagedata) || count($pagedata)<1){
					$fileurlcontents =$this->file_get_contents_curl_browser($urlvalue,'');
					//echo $fileurlcontents;
					$html = wpzillow_str_get_html($fileurlcontents);
					$pagedata = json_decode( $html, true );
				}
				
				$reviewsarray = $pagedata['reviews'];


					foreach ($reviewsarray as $review) {
							$user_name='';
							$userimage='';
							$rating='';
							$datesubmitted='';
							$rtext='';
							$pagename='';
							//find what is reviewed
							if($review['reviewee']['screenName']){
								$pagename = $review['reviewee']['screenName'];
							}
							
							// Find user_name
							if($review['reviewer']['screenName']){
								$user_name = $review['reviewer']['screenName'];
							}
							
							// Find userimage ui_avatar
							$userimage = '';

							// find rating
							if($review['rating']){
								$rating = intval($review['rating']);
							}

							
						// find date created_at
						if($review['createDate']){
							//11/14/2018
							$datesubmitted = $review['createDate'];
						}
							
							// find text
						if($review['reviewComment']){
							$rtext = $review['reviewComment'];
						}
							
							if($rating>0){
								$review_length = str_word_count($rtext);
								$timestamp = $this->myStrtotime($datesubmitted);
								$unixtimestamp = $timestamp;
								$timestamp = date("Y-m-d H:i:s", $timestamp);
								
								//add check to see if already in db, skip if it is and end loop
								$reviewindb = 'no';
								$checkrow = $wpdb->get_var( "SELECT id FROM ".$table_name." WHERE created_time_stamp = '".$unixtimestamp."' AND reviewer_name = '".trim($user_name)."' " );
								if( empty( $checkrow ) ){
										$reviewindb = 'no';
								} else {
										$reviewindb = 'yes';
								}
								if( $reviewindb == 'no' )
								{
								$reviews[] = [
										'reviewer_name' => trim($user_name),
										'pagename' => trim($pagename),
										'userpic' => $userimage,
										'rating' => $rating,
										'created_time' => $timestamp,
										'created_time_stamp' => $unixtimestamp,
										'review_text' => trim($rtext),
										'review_length' => $review_length,
										'type' => 'Zillow'
								];
								}
								$review_length ='';
							}
					}
					//sleep for random 2 seconds
					sleep(rand(0,2));
					
					// clean up memory
					if (!empty($html)) {
						$html->clear();
						unset($html);
					}
					
					sleep(1);
		}
		
			return $reviews;
	}	

	
	/**
	 * for lender specific page
	 * @access  public
	 * @since   1.0.0
	 * @return  void
	 */	
	private function wpzillow_revfrompage_lender($urlvalue) {
		global $wpdb;
		$table_name = $wpdb->prefix . 'wpzillow_reviews';
		
	
			$response = wp_remote_get( $urlvalue );
					if ( is_array( $response ) ) {
					  $header = $response['headers']; // array of http header lines
					  $fileurlcontents = $response['body']; // use the content
					} else {
						echo "Error finding reviews. Please contact plugin support.";
						die();
					}
					
					$html = wpzillow_str_get_html($fileurlcontents);

					//find zillow business name and add to db under pagename
					$pagename ='';
					//different for lender
					if($pagename==''){
						if($html->find('h1[class=lender-name]',0)){
						$pagename = $html->find('h1[class=lender-name]',0)->plaintext;
						}
					}

					// Find 20 reviews
					$i = 1;
					
					
					
					foreach ($html->find('ul[class=zsg-content-component]')->children as $review) {
print_r($review);
							if ($i > 21) {
									break;
							}
							$user_name='';
							$userimage='';
							$rating='';
							$datesubmitted='';
							$rtext='';
							// Find user_name
							if($review->find('div.review-reviewer-info', 0)){
								$user_info = $review->find('div.review-reviewer-info', 0)->plaintext;
								//only use text
								$user_name = substr($user_info,13);
								$user_name = trim($user_name);
							}

							// Find userimage ui_avatar, need to pull from lazy load varible
							//not used for zillow
							$userimage ='';
				

							// find rating zsg-rating zsg-rating_200
							if($review->find('span.zsg-rating', 0)){
								$temprating = $review->find('span.zsg-rating', 0)->class;
								$int = filter_var($temprating, FILTER_SANITIZE_NUMBER_INT);
								$rating = str_replace(0,"",$int);
								$rating =str_replace("-","",$rating);
							}

							// find date
							if($review->find('div.review-reviewer-info', 0)){
								$user_info = $review->find('div.review-reviewer-info', 0)->plaintext;
								//only use text
								$datesubmitted = substr($user_info,0,11);

							}
							
							// find text
							if($review->find('span.preserve-whitespace', 0)){
							$rtext = $review->find('span.preserve-whitespace', 0)->plaintext;
							}
								

							if($rating>0){
								$review_length = str_word_count($rtext);
								//$timestamp = strtotime($datesubmitted);
								$timestamp = $this->myStrtotime($datesubmitted);
								$unixtimestamp = $timestamp;
								$timestamp = date("Y-m-d H:i:s", $timestamp);
								//check option to see if this one has been hidden
								
								//pull array from options table of zillow hidden
								$zillowhidden = get_option( 'wpzillow_hidden_reviews' );
								if(!$zillowhidden){
									$zillowhiddenarray = array('');
								} else {
									$zillowhiddenarray = json_decode($zillowhidden,true);
								}
								$this_zillow_val = trim($user_name)."-".strtotime($datesubmitted)."-".$review_length."-Zillow-".$rating;
								if (in_array($this_zillow_val, $zillowhiddenarray)){
									$hideme = 'yes';
								} else {
									$hideme = 'no';
								}
								
								//add check to see if already in db, skip if it is and end loop
								$reviewindb = 'no';
								$checkrow = $wpdb->get_var( "SELECT id FROM ".$table_name." WHERE created_time_stamp = '".$unixtimestamp."' AND reviewer_name = '".trim($user_name)."' " );
								if( empty( $checkrow ) ){
										$reviewindb = 'no';
								} else {
										$reviewindb = 'yes';
								}
								if( $reviewindb == 'no' )
								{
								$reviews[] = [
										'reviewer_name' => trim($user_name),
										'pagename' => trim($pagename),
										'userpic' => $userimage,
										'rating' => $rating,
										'created_time' => $timestamp,
										'created_time_stamp' => $unixtimestamp,
										'review_text' => trim($rtext),
										'hide' => $hideme,
										'review_length' => $review_length,
										'type' => 'Zillow'
								];
								}
								$review_length ='';
							}
					 
							$i++;
					}

					//sleep for random 2 seconds
					sleep(rand(0,2));
					$n++;
					
					// clean up memory
					if (!empty($html)) {
						$html->clear();
						unset($html);
					}

			return $reviews;
	}	
	
		/**
	 * displays message in admin if it's been longer than 30 days.
	 * @access  public
	 * @since   1.0.0
	 * @return  void
	 */
	public function wprp_admin_notice__success () {

		$activatedtime = get_option('wprev_activated_time_zillow');
		//if this is an old install then use 23 days ago
		if($activatedtime==''){
			$activatedtime= time() - (86400*23);
			update_option( 'wprev_activated_time_zillow', $activatedtime );
		}
		$thirtydaysago = time() - (86400*30);
		
		//check if an option was clicked on
		if (isset($_GET['wprevpronotice'])) {
		  $wprevpronotice = $_GET['wprevpronotice'];
		} else {
		  //Handle the case where there is no parameter
		   $wprevpronotice = '';
		}
		if($wprevpronotice=='mlater_zillow'){		//hide the notice for another 30 days
			update_option( 'wprev_notice_hide_zillow', 'later' );
			$newtime = time() - (86400*21);
			update_option( 'wprev_activated_time_zillow', $newtime );
			$activatedtime = $newtime;
			
		} else if($wprevpronotice=='notagain_zillow'){		//hide the notice forever
			update_option( 'wprev_notice_hide_zillow', 'never' );
		}
		
		$wprev_notice_hide = get_option('wprev_notice_hide_zillow');

		if($activatedtime<$thirtydaysago && $wprev_notice_hide!='never'){
		
			$urltrimmedtab = remove_query_arg( array('taction', 'tid', 'sortby', 'sortdir', 'opt') );
			$urlmayberlater = esc_url( add_query_arg( 'wprevpronotice', 'mlater_zillow',$urltrimmedtab ) );
			$urlnotagain = esc_url( add_query_arg( 'wprevpronotice', 'notagain_zillow',$urltrimmedtab ) );
			
			$temphtml = '<p>Hey, I noticed you\'ve been using my <b>WP Zillow Review Slider</b> plugin for a while now – that’s awesome! Could you please do me a BIG favor and give it a 5-star rating on WordPress? <br>
			Thanks!<br>
			~ Josh W.<br></p>
			<ul>
			<li><a href="https://wordpress.org/support/plugin/wp-zillow-review-slider/reviews/#new-post" target="_blank">Ok, you deserve it</a></li>
			<li><a href="'.$urlmayberlater.'">Not right now, maybe later</a></li>
			<li><a href="'.$urlnotagain.'">Don\'t remind me again</a></li>
			</ul>
			<p>P.S. If you\'ve been thinking about upgrading to the <a href="https://wpreviewslider.com/" target="_blank">Pro</a> version, here\'s a 10% off coupon code you can use! ->  <b>wprevpro10off</b></p>';
			
			?>
			<div class="notice notice-info">
				<div class="wprevpro_admin_notice" style="color: #007500;">
				<?php _e( $temphtml, $this->_token ); ?>
				</div>
			</div>
			<?php
		}

	}
	
		/**
	 * add dashboard widget to wordpress admin
	 * @access  public
	 * @since   9.1
	 * @return  void
	 */
	public function wpzillow_dashboard_widget() {
		global $wp_meta_boxes;
		//wp_add_dashboard_widget('custom_help_widget', 'Theme Support', 'custom_dashboard_help');
		add_meta_box( 'id', 'WP Zillow Review Slider Recent Reviews', array($this,'custom_dashboard_help'), 'dashboard', 'side', 'high' );
	}
	 
	public function custom_dashboard_help() {
		global $wpdb;
		$reviews_table_name = $wpdb->prefix . 'wpzillow_reviews';
		$tempquery = "select * from ".$reviews_table_name." ORDER by created_time_stamp Desc limit 4";
		$reviewrows = $wpdb->get_results($tempquery);
		$now = time(); // or your date as well
		
		echo '<style>
			img.wprev_dash_avatar {float: left;margin-right: 8px;border-radius: 20px;}
			.wprev_dash_stars {float: right;}
			p.wprev_dash_text {margin-top: -6px;}
			span.wprev_dash_timeago {font-size: 12px;font-style: italic;}
			.wprev_dash_revdiv {min-height: 50px;}
			</style>';
		echo '<ul>';
		foreach ( $reviewrows as $review ) 
		{
			$timesince = '';
			if(strlen($review->review_text)>130){
				$reviewtext = substr($review->review_text,0,130).'...';
			} else {
				$reviewtext = $review->review_text;
			}
			
			$your_date = $review->created_time_stamp;
			$datediff = $now - $your_date;
			$daysago = round($datediff / (60 * 60 * 24));
			if($daysago==1){
				$daysagohtml = $daysago.' day ago';
			} else {
				$daysagohtml = $daysago.' days ago';
			}
			if($review->rating<1){
				if($review->recommendation_type=='positive'){
					$review->rating=5;
				} else {
					$review->rating=2;
				}
			}

			$imgs_url = plugin_dir_url(__DIR__).'/public/partials/imgs/';
			$starfile = 'stars_'.$review->rating.'.png';
			$starhtml='<img src="'.$imgs_url."".$starfile.'" alt="'.$review->rating.' star rating" class="wprev_dash_stars">';
			
			$avatarhtml = '';
			if(isset($review->userpic) && $review->userpic!=''){
				$avatarhtml = '<img alt="" src="'.$review->userpic.'" class="wprev_dash_avatar" height="40" width="40">';
			}
			
			echo '<li><div class="wprev_dash_revdiv">'.$avatarhtml.'<div class="wprev_dash_stars">'.$starhtml.'</div><h4 class="wprev_dash_name">'.$review->reviewer_name.' - <span class="wprev_dash_timeago">'.$daysagohtml.'</span></h4><p class="wprev_dash_text">'.$reviewtext.'</p></div></li>';
			
		}
		echo '</ul>';
		
		echo '<div><a href="admin.php?page=wp_zillow-reviews">All Reviews</a> - <a href="https://wpreviewslider.com/" target="_blank">Go Pro For More Cool Features!</a></div>';
	}

 
}
