<?php
/**
 * module return as json_encode
 * http://www.aa-team.com
 * =======================
 *
 * @author		Andrei Dinca, AA-Team
 * @version		1.0
 */

global $psp;

function PSP_SERP_load_inc__( $what='' ) {
	$ret = array();

	require( 'list.inc.php' );

	if ( 'google_locations' == $what ) {
		$ret = $google_locations;
	}
	return $ret;
}

function PSP_SERP_app_access_key() {
	$ipc = get_option( 'psp_register_key', '' );
	$url = get_site_url();

	// validate ipc
	if ( '' == $ipc ) {
		return '';
	}

	$code = $url . $ipc;
	//var_dump('<pre>', $code , '</pre>'); echo __FILE__ . ":" . __LINE__;die . PHP_EOL;
	$code = md5( $code );
	return $code;
}

function pspAccessKeyHtml( $action='default', $istab = '', $is_subtab='' ) {
	global $psp;

	$req = array();
	$req['action'] = $action;

	if ( $req['action'] == 'getStatus' ) {
		$notifyStatus = $psp->get_theoption('psp_serp_api');
		if ( $notifyStatus === false || !isset($notifyStatus["genkey"]) )
			return '';

		return $notifyStatus["genkey"]['msg_html'];
	}

	$html = array();

	$html[] = '<div class="panel-body psp-panel-body psp-form-row psp-serp-api ' . ($istab!='' ? ' '.$istab : '') . ($is_subtab!='' ? ' '.$is_subtab : '') . '" style="">';

	$html[] = '	<div class="psp-form-item large" style="margin-left: 0px; margin-bottom: 7px;">';
	$html[] = '		<label for="site-items" style="margin-bottom: 0px; width: 18rem;">' . __('SERP API', 'psp') . ':</label>';

	if (1) {
		//$html[] = '<div style="padding-bottom: 8px;">' . '' . '</div>';
	}
	
	$current_recurrency = $psp->get_theoption('psp_serp_api');
	$current_recurrency = isset($current_recurrency['api_status']) ? (string) $current_recurrency['api_status'] : 'disabled';

	ob_start();
?>
		<select id="api_status" name="api_status" style="width: 160px;">
			<?php
            $sync_recurrence = array(
                'enabled' 	=> __('API Enabled', $psp->localizationName),
                'disabled' 	=> __('API Disabled', $psp->localizationName),
            );
			foreach ($sync_recurrence as $kk => $vv){
				echo '<option value="' . ( $kk ) . '" ' . ( $kk == $current_recurrency ? 'selected="true"' : '' ) . '>' . ( $vv ) . '</option>';
			} 
			?>
		</select>&nbsp;&nbsp;
<?php
	$selectSitemap = ob_get_contents();
	ob_end_clean();
	$html[] = $selectSitemap;
	
	$html[] = '<input type="button" class="psp-form-button psp-form-button-info psp-button blue" style="width: 280px;" id="psp-serp-api-genkey" value="' . ( __('Generate Key', 'psp') ) . '">
	<span style="margin:0px 0px 0px 10px" class="response">' . pspAccessKeyHtml( 'getStatus' ) . '</span>';

	$html[] = '<div style="">' . __('Access KEY:', 'psp') . '<input type="text" style="margin-left: 10px; width: 460px;" name="remote_username" id="remote_username" value=""></div>';
	
	$html[] = '<div style=""><span class="psp-form-note">' . sprintf( __('With recurrency you can set the "timeout" for our cached video meta data (info about the videos we found in each post content).<br/> You can also use the "Delete video metas for all posts NOW" button, to delete all video meta data we\'ve cached till now, so they will be rebuild.<br/> Then, if you don\'t have too many videos (let\'s say - around maximum 1000 videos in all your posts), you can can access the link %s, because it will search through all your posts, find the videos and generate the coresponding videos meta data.<br/> The video meta data are also generated (if it isn\'t done yet) when you access a post details page on website frontend.', 'psp'), '<a id="site-items" target="_blank" href="' . ( home_url('/sitemap-videos.xml') ) . '" style="position: relative;">' . ( home_url('/sitemap-videos.xml') ) . '</a>' ) . '</span></div>';

	$html[] = '	</div>';
	$html[] = '</div>';

	// view page button
	ob_start();
?>
	<script>
	(function($) {
		var ajaxurl = '<?php echo admin_url('admin-ajax.php');?>';

		$("body").on("click", "#psp-serp-api-genkey", function() {

			$.post(ajaxurl, {
				'action' 		: 'pspSerpApi',
				'sub_action'	: 'genkey',
			}, function(response) {

				var $box = $('.psp-serp-api'), $res = $box.find('.response');
				$res.html( response.msg_html );
				if ( response.status == 'valid' )
					return true;
				return false;
			}, 'json');
		});
   	})(jQuery);
	</script>
<?php
	$__js = ob_get_contents();
	ob_end_clean();
	$html[] = $__js;

	return implode( "\n", $html );
}

echo json_encode(
	array(
		$tryed_module['db_alias'] => array(
			/* define the form_messages box */
			'serp' => array(
				'title' 	=> 'SERP',
				'icon' 		=> '{plugin_folder_uri}assets/menu_icon.png',
				'size' 		=> 'grid_4', // grid_1|grid_2|grid_3|grid_4
				'header' 	=> true, // true|false
				'toggler' 	=> false, // true|false
				'buttons' 	=> array(
					'save' => array(
						'value' => __('Save settings', 'psp'),
						'color' => 'success',
						'action'=> 'psp-saveOptions'
					)
				), // true|false
				'style' 	=> 'panel', // panel|panel-widget

				// create the box elements array
				'elements'	=> array(
				
					/*array(
						'type' 		=> 'html',
						'html' 		=> '<div class="panel-heading psp-panel-heading">
											<h2>SERP Settings</h2>
										</div>'
					),*/

	                '__help_serp_google_api' => array(
	                    'type' => 'message',
	                    'status' => 'info',
	                    'html' => 'Google SERP Documentation - <a href="http://docs.aa-team.com/premium-seo-pack/documentation/serp-tracking/" target="_blank">Click Here</a>'
	                ),
					
					'nbreq_max_limit' 	=> array(
						'type' 		=> 'text',
						'std' 		=> 100,
						'size' 		=> 'small',
						'title' 	=> __('Max nb requests (daily):', 'psp'),
						'force_width'=> '100',
						'desc' 		=> __('Max number of daily requests to Google API. If you need more, please verify <a href="https://developers.google.com/custom-search/json-api/v1/overview?csw=1#pricing" target="_blank">Google price list</a><br/>
							<span style="color: red;">For CSE users, the API provides 100 search queries per day for free. <br/>If you need more, you may sign up for billing in the API Console. <br/>Additional requests cost $5 per 1000 queries, up to 10k queries per day.</span>', 'psp'),
					),

					/*'top_type' 	=> array(
						'type' 		=> 'select',
						'std' 		=> 100,
						'size' 		=> 'large',
						'title' 	=> __('Top Size:', 'psp'),
						'force_width'=> '100',
						'desc' 		=> __('Check if first X google results', 'psp'),
						'options'	=> $psp->doRange( range(10, 100, 10) )
					),*/
					
					'custom_search_id' 	=> array(
						'type' 		=> 'text',
						'std' 		=> '',
						'size' 		=> 'large',
						'force_width'=> '350',
						'title' 	=> __('Custom Search Engine ID:', 'psp'),
						'desc' 		=> __('Custom Search Engine ID', 'psp')
					),

					/*'developer_key' 	=> array(
						'type' 		=> 'text',
						'std' 		=> '',
						'size' 		=> 'large',
						'force_width'=> '400',
						'title' 	=> __('API Key:', 'psp'),
						'desc' 		=> __('API Key', 'psp')
					),*/

					'developer_key' 	=> array(
						'type' 		=> 'textarea',
						'std' 		=> '',
						'size' 		=> 'small',
						//'force_width'=> '400',
						'title' 	=> __('API Key(s):', 'psp'),
						'desc' 		=> __('you can add multiple keys, separated by a new line, but each one must belong to a different Google account.', 'psp'),
						'height'	=> '100px',
						'width'		=> '100%'
					),
					
					/*'google_country' 	=> array(
						'type' 		=> 'select',
						'std' 		=> '',
						'size' 		=> 'large',
						'force_width'=> '170',
						'title' 	=> __('Google locations', 'psp'),
						'desc' 		=> __('All possible locations.', 'psp'),
						'options' 	=> PSP_SERP_load_inc__( 'google_locations' )
					),*/
					
					'last_status' 	=> array(
						'type' 		=> 'textarea-array',
						'std' 		=> '',
						'size' 		=> 'large',
						'force_width'=> '400',
						'title' 	=> __('Request Last Status:', 'psp'),
						'desc' 		=> __('Last Status retrieved from Google, for the SERP request operation', 'psp')
					),
					
					/*'cron_email' 	=> array(
						'type' 		=> 'text',
						'std' 		=> '',
						'size' 		=> 'large',
						'title' 	=> __('Email:', 'psp'),
						'desc' 		=> __('Your email where you will receive cron notifications', 'psp')
					),*/
					
					/*
					array(
						'type' 		=> 'html',
						'html' 		=> '<div style="margin: 20px 0px 20px 20px;">
							<h2>How to setup the Cron Job</h2>
							<p>WordPress comes with its own cron job utility, that allows you to schedule your posts and events. However, in many situations, the WP-Cron is not working properly and this can lead to posts missing their publication schedule and/or scheduled events not getting executed.<br>
							<span id="more-74"></span><br>
							To understand why this happens, we need to know that the WP-Cron is not a real cron job. It is in fact a virtual cron that only works when a page is loaded. In short, when a page is requested on the frontend/backend, WordPress will first load WP-Cron, followed by the necessary page to display to your reader. The loaded WP-Cron will then check the database to see if there is any thing that needs to be done.</p>
							<p>Reasons for WP-Cron to fail could be:</p>
							<ul>
								<li>DNS issues in the server.</li>
								<li>Plugin(s) conflict(s)</li>
								<li>Heavy load in the server which results in WP-Cron not executed fully</li>
								<li>WordPress bug</li>
								<li>Using of cache plugins that prevent the WP-Cron from loading</li>
								<li>And many other reasons</li>
							</ul>
							<p>There are many ways to solve the WP-Cron issue, but the one that I am going to propose here is to disable the virtual WP-Cron and use a real cron job instead.</p>
							<h3>Why use a real cron job?</h3>
							<p>By using a real cron job, you can be sure that all your scheduled items are executed. For popular blogs with high traffic, using a real cron job can also reduce the server bandwidth and reduce the chances of your server crashing, especially when you are experiencing Digg/Slashdot effect.</p>
							<h3>Scheduling a real cron job</h3>
							<p>To configure a real cron job, you will need access to your cPanel or Admin panel (we will be using cPanel in this tutorial).</p>
							<p>1. Log into your cPanel.</p>
							<p>2. Scroll down the list of applications until you see the “<em>cron jobs</em>" link. Click on it.</p>
							<p><img width="510" height="192" class="aligncenter size-full wp-image-81" alt="wpcron-cpanel" src="{plugin_folder_uri}assets/wpcron-cpanel.png"></p>
							<p>3. Under the <em>Add New Cron Job</em> section, choose the interval that you want it to run the cron job. I have set it to run every 15minutes, but you can change it according to your liking.</p>
							<p><img width="470" height="331" class="aligncenter size-full wp-image-82" alt="wpcron-add-new-cron-job" src="{plugin_folder_uri}/assets/wpcron-add-new-cron-job.png"></p>
							<p>4. In the Command field, enter the following:</p>
						
							<div class="wp_syntax"><div class="code">wget -q -O - ' . ( $psp->cfg["paths"]["plugin_dir_url"] ) . 'do-cron.php &gt; /dev/null 2&gt;&amp;1</div></div>
						
							<p>5. Click the “Add New Cron Job“ button. You should now see a message like this:</p>
							<p><img width="577" height="139" class="aligncenter size-full wp-image-83" alt="wpcron-current-cron-job" src="{plugin_folder_uri}/assets/wpcron-current-cron-job.png"></p>
							<p>6. Next, using a FTP program, connect to your server and download the <code>wp-config.php</code> file.</p>
							<p>7. Open the <code>wp-config.php</code> file with a text editor and paste the following line:</p>
						
							<div class="wp_syntax"><div class="code">define(\'DISABLE_WP_CRON\', true);</div></div>
						
							<p>8. Save and upload (and replace) this file back to the server. This will disable WordPress\' internal cron job.</p>
							<p>That’s it.</p>
						
						
							<a href="http://wpdailybits.com/blog/replace-wordpress-cron-with-real-cron-job/74"> Credits </a></div>'
					)
					*/

					/*'app_access_key' 	=> array(
						'type' 		=> 'text',
						'std' 		=> PSP_SERP_app_access_key(),
						'size' 		=> 'large',
						'force_width'=> '350',
						'title' 	=> __('Serp App Access Key:', 'psp'),
						'desc' 		=> sprintf( __('the app access key is generated based on <span class="app_access_key">your website address</span> and <span class="app_access_key">PSP plugin IPC (Item Purchase Code)</span> which you\'ve used to register it - <span class="app_access_key">both are mandatory, otherwise the key cannot be generated</span> <br/>the app access key is necessary if you want to use our desktop psp application. <br/>your website address: <span class="app_access_key">%s</span> <br/>PSP plugin IPC: <span class="app_access_key">%s</span>', 'psp'), get_site_url(), get_option( 'psp_register_key', '' ) )
					),
					'access_key_html' => array(
						'type' => 'html',
						'html' => pspAccessKeyHtml( 'default' )
					),*/

				)
			)
		)
	)
);