<?php

/**
 * Provide a admin area view for the plugin
 *
 * This file is used to markup the admin-facing aspects of the plugin.
 *
 * @link       http://ljapps.com
 * @since      1.0.0
 *
 * @package    WP_Google_Reviews
 * @subpackage WP_Google_Reviews/admin/partials
 */

    // check user capabilities
    if (!current_user_can('manage_options')) {
        return;
    }
 
    // add error/update messages
 
    // check if the user have submitted the settings
    // wordpress will add the "settings-updated" $_GET parameter to the url
    if (isset($_GET['settings-updated'])) {
        // add settings saved message with the class of "updated"
        add_settings_error('wpfbr_messages', 'wpfbr_message', __('Settings Saved', 'wp-google-reviews'), 'updated');
    }
    // show error/update messages
    settings_errors('wpfbr_messages');
	
	//get previous crawls
	
	if ( 'not-exists' === get_option( 'wprev_google_crawls', 'not-exists' ) ) {
		update_option('wprev_google_crawls',json_encode(array(array())));
	}
	$googlecrawlsarray = json_decode(get_option('wprev_google_crawls'),true);
	
	// Helper function to limit text to 200 characters
	function limit_text($text, $limit = 100) {
		if (strlen($text) > $limit) {
			return substr($text, 0, $limit) . '...';
		}
		return $text;
	}
	
//echo '<pre>';
//print_r($googlecrawlsarray);
//echo '</pre>';


	//get previous apis if set.
	
	if ( 'not-exists' === get_option( 'wprev_google_apis', 'not-exists' ) ) {
		update_option('wprev_google_apis',json_encode(array(array())));
	}
	$googleapisarray = json_decode(get_option('wprev_google_apis'),true);
	

	//check if we need to delete a source here
	if ( isset( $_GET['ract'] ) && $_GET['ract'] === 'del' ) {
		// CSRF protection — mirrors template delete (tdel_) pattern.
		check_admin_referer( 'wprev_del_google_source' );

		// Preserve exact option-array keys (do not use sanitize_text_field — it
		// collapses whitespace and would break deletes for multi-word crawl keys).
		$delplace = isset( $_GET['place'] ) ? wp_unslash( $_GET['place'] ) : '';
		$delplace = is_string( $delplace ) ? wp_strip_all_tags( $delplace ) : '';
		$delplaceid = isset( $_GET['placeid'] ) ? wp_unslash( $_GET['placeid'] ) : '';
		$delplaceid = is_string( $delplaceid ) ? wp_strip_all_tags( $delplaceid ) : '';
		$deltype = isset( $_GET['type'] ) ? sanitize_text_field( wp_unslash( $_GET['type'] ) ) : '';

		if ( $deltype === 'crawl' && $delplace !== '' ) {
			unset( $googlecrawlsarray[ $delplace ] );
			update_option( 'wprev_google_crawls', json_encode( $googlecrawlsarray ) );
		} elseif ( $deltype === 'api' && $delplaceid !== '' ) {
			unset( $googleapisarray[ $delplaceid ] );
			update_option( 'wprev_google_apis', json_encode( $googleapisarray ) );
		}
		//remove all reviews from this place id and delete from total and avg table.
		//==========================
		global $wpdb;

		if ( $delplaceid !== '' ) {
			$table_name_revs = $wpdb->prefix . 'wpfb_reviews';
			$wpdb->delete( $table_name_revs, array( 'pageid' => $delplaceid ) );

			$table_name_tots = $wpdb->prefix . 'wpfb_total_averages';
			$wpdb->delete( $table_name_tots, array( 'btp_id' => $delplaceid ) );
		}

		$googlecrawlsarray = json_decode( get_option( 'wprev_google_crawls' ), true );
	}

//echo $googlecrawlsarray;
//print_r($googlecrawlsarray);
?>

<div class="">
<h1></h1>
<div class="wrap" id="wp_rev_maindiv">
<img class="wprev_headerimg" src="<?php echo plugin_dir_url( __FILE__ ) . 'logo.png'; ?>">
<?php 
include("tabmenu.php");
?>	
<div class="wpfbr_margin10">

<?php

//if(!isset($googlecrawlsarray[0])){
?>
<div id='currentsources'>
<style>
#currentsources table {
	max-width: 100%;
	table-layout: fixed;
	word-wrap: break-word;
}
#currentsources table td {
	word-wrap: break-word;
	word-break: break-all;
	overflow-wrap: break-word;
	max-width: 0;
}
#currentsources table td:first-child {
	width: 30%;
}
#currentsources table td:nth-child(2) {
	width: 25%;
}
#currentsources table td:nth-child(3) {
	width: 20%;
}
#currentsources table td:last-child {
	width: 25%;
}
</style>
	  <table class="w3-table-all wpfbr_mb15 welcomediv w3-container w3-white w3-border w3-border-light-gray2 w3-round-small">
    <tr>
	  <th>Business Name</th>
	  <th>Google Place ID</th>
      <th>Download Type</th>
	  <th>Action</th>
    </tr>
<?php
$crawlcount = 0;
foreach ($googlecrawlsarray as $key =>$savedplace) {
//echo "<br>key:".$key;
   // if(isset($key) && $key!=0 && $key!=""){
	if(isset($savedplace['crawl_check']) && is_array($savedplace['crawl_check']) && !isset($savedplace['task_id'])){
		$crawlcount++;
		$tempbusines ="";
		$tempfoundplaceid ="";
		$nhful="";
		
				$tempbusiness = stripslashes($savedplace['crawl_check']['businessname'] ?? '');
				$tempfoundplaceid = stripslashes($savedplace['crawl_check']['foundplaceid'] ?? '');
				$nhful = $savedplace['nhful'];

		// Apply character limit to place ID before creating link
		$tempfoundplaceid = limit_text($tempfoundplaceid);
		$placeid_link = '';
		if($tempfoundplaceid != '' && strpos($tempfoundplaceid, 'ChIJ') === 0) {
			$placeid_link = '<a href="https://search.google.com/local/reviews?placeid='.urlencode($tempfoundplaceid).'" target="_blank" style="color: #1976d2; text-decoration: none;">'.esc_html($tempfoundplaceid).'</a>';
		} else {
			$placeid_link = esc_html($tempfoundplaceid);
		}
		
		$delete_url = wp_nonce_url(
			add_query_arg(
				array(
					'page'    => 'wp_google-googlesettings',
					'ract'    => 'del',
					'place'   => $key,
					'placeid' => $tempfoundplaceid,
					'type'    => 'crawl',
				),
				admin_url( 'admin.php' )
			),
			'wprev_del_google_source'
		);
		echo "<tr><td> ".esc_html(limit_text($tempbusiness)) ."</td><td>".$placeid_link."</td><td> Crawl : ".esc_html($savedplace['nhful']) ."</td><td> 
		<a class='w3-button w3-red w3-padding-small' href='".esc_url( $delete_url )."'>Delete</a>
		<a class='w3-button w3-green w3-padding-small' href='".$urlgooglegooglecrawl."&ract=edit&place=".urlencode($key)."&placeid=".urlencode($tempfoundplaceid)."'>Get Reviews</a>
		&nbsp;<img class='buttonloader2 loadinggifchoosepage' width='20' height='20' src='".plugin_dir_url( __FILE__ )."loading.gif' style='display:none;'><span class='googletestresults2'></span>
		</td></tr>";
	}
}

// Display DataForSEO entries (those with enteredidorterms but no crawl_check)
foreach ($googlecrawlsarray as $key => $savedplace) {
	if(isset($savedplace['enteredidorterms']) && isset($savedplace['task_id'])){
		$crawlcount++;
		$tempbusiness = '';
		$tempfoundplaceid = '';
		
		// Check if crawl_check exists before accessing it
		if(isset($savedplace['crawl_check']) && is_array($savedplace['crawl_check'])) {
			$tempbusiness = stripslashes($savedplace['crawl_check']['businessname'] ?? '');
			$tempfoundplaceid = stripslashes($savedplace['crawl_check']['foundplaceid'] ?? '');
		}
		
		// Fallback to enteredidorterms if business name is empty
		if($tempbusiness == ''){
			$tempbusiness = stripslashes($savedplace['enteredidorterms']); // Use the place ID as business name for now
		}
		
		// Fallback to enteredidorterms if place ID is empty
		if($tempfoundplaceid == ''){
			$tempfoundplaceid = stripslashes($savedplace['enteredidorterms']);
		}
		$nhful = isset($savedplace['nhful']) ? $savedplace['nhful'] : 'relevant';
		$task_id = isset($savedplace['task_id']) ? $savedplace['task_id'] : '';
		$task_status = isset($savedplace['task_status']) ? $savedplace['task_status'] : '';
		

			$button_text = 'Get Reviews';
			$button_class = 'w3-button w3-green w3-padding-small';
			$button_action = 'download-reviews';

		// Apply character limit to place ID before creating link
		$tempfoundplaceid = limit_text($tempfoundplaceid);
		$placeid_link = '';
		if($tempfoundplaceid != '' && strpos($tempfoundplaceid, 'ChIJ') === 0) {
			$placeid_link = '<a href="https://search.google.com/local/reviews?placeid='.urlencode($tempfoundplaceid).'" target="_blank" style="color: #1976d2; text-decoration: none;">'.esc_html($tempfoundplaceid).'</a>';
		} else {
			$placeid_link = esc_html($tempfoundplaceid);
		}
		
		$delete_url = wp_nonce_url(
			add_query_arg(
				array(
					'page'    => 'wp_google-googlesettings',
					'ract'    => 'del',
					'place'   => $key,
					'placeid' => $tempfoundplaceid,
					'type'    => 'crawl',
				),
				admin_url( 'admin.php' )
			),
			'wprev_del_google_source'
		);
		echo "<tr><td> ".esc_html(limit_text($tempbusiness)) ."</td><td>".$placeid_link."</td><td> Crawl Method : ".esc_html($nhful) ."</td><td> 
		<a class='w3-button w3-red w3-padding-small' href='".esc_url( $delete_url )."'>Delete</a>
		<a class='w3-button w3-green w3-padding-small' href='".$urlgooglegooglecrawl."&ract=edit&place=".urlencode($key)."&placeid=".urlencode($tempfoundplaceid)."'>Get Reviews</a>
		&nbsp;<img class='buttonloader2 loadinggifchoosepage' width='20' height='20' src='".plugin_dir_url( __FILE__ )."loading.gif' style='display:none;'><span class='googletestresults2'></span>
		</td></tr>";
	}
}

// Display old format entries (those with only nhful and no crawl_check or task_id)
foreach ($googlecrawlsarray as $key => $savedplace) {
	if(isset($savedplace['nhful']) && !isset($savedplace['crawl_check']) && !isset($savedplace['task_id']) && $key != 0 && $key != ''){
		$crawlcount++;
		$tempbusiness = stripslashes($key); // Use the key as business name for old format
		$tempfoundplaceid = stripslashes($key); // Use the key as place ID for old format
		$nhful = $savedplace['nhful'];
		
		// Apply character limit to place ID before creating link
		$tempfoundplaceid = limit_text($tempfoundplaceid);
		$placeid_link = '';
		if($tempfoundplaceid != '' && strpos($tempfoundplaceid, 'ChIJ') === 0) {
			$placeid_link = '<a href="https://search.google.com/local/reviews?placeid='.urlencode($tempfoundplaceid).'" target="_blank" style="color: #1976d2; text-decoration: none;">'.esc_html($tempfoundplaceid).'</a>';
		} else {
			$placeid_link = esc_html($tempfoundplaceid);
		}
		
		$delete_url = wp_nonce_url(
			add_query_arg(
				array(
					'page'    => 'wp_google-googlesettings',
					'ract'    => 'del',
					'place'   => $key,
					'placeid' => $tempfoundplaceid,
					'type'    => 'crawl',
				),
				admin_url( 'admin.php' )
			),
			'wprev_del_google_source'
		);
		echo "<tr><td> ".esc_html(limit_text($tempbusiness)) ."</td><td>".$placeid_link."</td><td> Old Crawl Method : ".esc_html($nhful) ."</td><td> 
		<a class='w3-button w3-red w3-padding-small' href='".esc_url( $delete_url )."'>Delete</a>
		<a class='w3-button w3-green w3-padding-small' href='".$urlgooglegooglecrawl."&ract=edit&place=".urlencode($key)."&placeid=".urlencode($tempfoundplaceid)."'>Get Reviews</a>
		&nbsp;<img class='buttonloader2 loadinggifchoosepage' width='20' height='20' src='".plugin_dir_url( __FILE__ )."loading.gif' style='display:none;'><span class='googletestresults2'></span>
		</td></tr>";
	}
}
?>
<?php
foreach ($googleapisarray as $key =>$savedplace) {

        //echo "$key => $savedplace\n <br>";
	if(isset($savedplace['google_location_set'])){
	if(is_array($savedplace['google_location_set']) && $savedplace['google_location_set']['place_id']!=""){
		$tempbusines ="";
		$tempfoundplaceid ="";
		$nhful="";

				$tempbusiness = stripslashes($savedplace['google_location_set']['location'] ?? '');
				$tempfoundplaceid = stripslashes($savedplace['google_location_set']['place_id'] ?? '');
				

		$nhful = $savedplace['google_location_sort'];
		// Apply character limit to place ID before creating link
		$tempfoundplaceid = limit_text($tempfoundplaceid);
		$placeid_link = '';
		if($tempfoundplaceid != '' && strpos($tempfoundplaceid, 'ChIJ') === 0) {
			$placeid_link = '<a href="https://search.google.com/local/reviews?placeid='.urlencode($tempfoundplaceid).'" target="_blank" style="color: #1976d2; text-decoration: none;">'.esc_html($tempfoundplaceid).'</a>';
		} else {
			$placeid_link = esc_html($tempfoundplaceid);
		}
		
		$delete_url = wp_nonce_url(
			add_query_arg(
				array(
					'page'    => 'wp_google-googlesettings',
					'ract'    => 'del',
					'place'   => $key,
					'placeid' => $tempfoundplaceid,
					'type'    => 'api',
				),
				admin_url( 'admin.php' )
			),
			'wprev_del_google_source'
		);
		echo "<tr><td> ".esc_html(limit_text($tempbusiness)) ."</td><td>".$placeid_link."</td><td> Places API : ".esc_html($savedplace['google_location_sort']) ."</td><td> 
		<a class='w3-button w3-red w3-padding-small' href='".esc_url( $delete_url )."'>Delete</a>
		<a class='w3-button w3-dark-grey w3-padding-small' href='".$urlgoogleapi."&ract=edit&placeid=".urlencode($key)."'>Edit</a>
		<a onclick='getgooglereviewsfunction(\"".esc_js($key)."\")' class='w3-button w3-green w3-padding-small' data-type='api' data-placeid='".esc_attr($key)."' data-place='".urlencode($tempbusiness)."' data-nhful='".urlencode($nhful)."'>Download Reviews</a>&nbsp;<img class='buttonloader2 loadinggifchoosepage' width='20' height='20' src='".plugin_dir_url( __FILE__ )."loading.gif' style='display:none;'><span class='googletestresults2'></span>
		</td></tr>";

		}
	}
}


?>


  </table>
</div>
<?php
//} else {
	//echo '	<div class="w3-white">
	//<div class="w3-container">
	//<h6>Use the button below to download Google reviews from one or more locations.</h6>
	//</div>
	//</div><br>';
//}
?>
	<div class="w3-padding-8">
		<button id="shownewsourceoption" type="button" class="mt20 w3-btn w3-padding-small2 w3-green">Add New Google Source</button><br><br>
	</div>



<div id="chooseoption" style="display:none;" class="w3-col wpfbr_mb15 welcomediv w3-container w3-white w3-border w3-border-light-gray2 w3-round-small">

	<div class="w3-container w3-padding-16">
	<h4 class="">Choose one or both of these options to download reviews...</h3>
	</div>
<div class="w3-row-padding wppro_choose wpfbr_mb25">
	<div class="w3-col l6">
	<div class="w3-card-4 w3-white">
	<header class="w3-container w3-light-grey">
	  <h4><i class="fa fa-cogs" aria-hidden="true"></i> Crawl Google Review Page</h4>
	</header>
	<div class="w3-container">
	<h5>Pros:</h5>
	  <p>- Will download your Newest 20 or Most Relevant 20 reviews.</p>
	  <p>- Will also download user images on reviews.</p>
	  <p>- No API Key required.</p>
	  <p>- Can also work for service area businesses.</p>
	  <hr>
	  <h5>Cons:</h5>
	  <p>- Limited to only 15 locations allowed.</p>
	  <p>- Can not automatically check for new reviews.</p>
	  <p>- Date must be inferred, since Google does not list exact dates on reviews.</p>
	</div>
	<?php
	if($crawlcount<15){
	?>
	<a class="w3-button w3-block w3-dark-grey" href="<?php echo $urlgooglegooglecrawl; ?>">+ Select</a>
	<?php
	} else {
		
	?>
	<div class="w3-container">
	<p><b>You have reached your max amount of crawl locations. The Pro version has no limit and can download over 90 different review types!</b></p></div>
	<?php
	}
		
	?>
	</div>
	</div>

	<div class="w3-col l6 ">
	<div class="w3-card-4 w3-white">
	<header class="w3-container w3-light-grey">
	  <h4><i class="fa fa-map-o" aria-hidden="true"></i> Google Places API</h4>
	</header>
	<div class="w3-container">
	<h5>Pros:</h5>
	<p>- Official Google Places API Method.</p>
	  <p>- Can download your Newest 5 and/or Most Relevant 5 reviews.</p>
	  <p>- Can automatically check for reviews daily.</p>
	  <hr>
	  <h5>Cons:</h5>
	  <p>- Must have a physical address on Google Maps.</p>
	  <p>- Requires you to obtain Google Places API Key from Google.</p>
	  <p>- Can not download user images on reviews.</p>
	  <p>- Limited to 5 Newest or 5 Most Relevant.</p>
	</div>
	<a class="w3-button w3-block w3-dark-grey" href="<?php echo $urlgoogleapi; ?>&newplace=yes">+ Select</a>
	</div>
	</div>

</div>
<div class="w3-container w3-padding-16"><span class="small_message">
	The Free version is limited to 15 locations. The <a href="https://wpreviewslider.com/">Pro Version</a> of this plugin can download all of your Google reviews from multiple locations and keep them updated automatically!</span></div>
</div>



</div>


<div class="small_message"><p>Do you like this plugin? If so please take a moment to leave a review <a href="https://wordpress.org/plugins/wp-google-reviews/" target="blank">here!</a> If it's missing something then please contact me <a href="https://wpreviewslider.com/contact/" target="blank">here</a>. Thanks!</p><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br></div>

<?php
	/*
echo "googlecrawlsarray:";
print "<pre>";
print_r($googlecrawlsarray);
print "</pre>";	
echo "googleapisarray:";
print "<pre>";
print_r($googleapisarray);
print "</pre>";	

$options = get_option('wpfbr_google_options');

print "<pre>";
print_r($options);
print "</pre>";

//echo $options;
*/
?>

	<div id="popup" class="popup-wrapper wpfbr_hide">
	  <div class="popup-content">
		<div class="popup-title">
		  <button type="button" class="popup-close">&times;</button>
		  <h3 id="popup_titletext"></h3>
		</div>
		<div class="popup-body">
		  <div id="popup_bobytext1"></div>
		  <div id="popup_bobytext2"></div>
		</div>
	  </div>
	</div>
</div>
</div>