<?php 

/**
 * Loading required functions to uploading poster via url.
 */
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/image.php';

if ( ! function_exists( 'dlpro_autopost_get_remote_html' ) ) {
	/**
	 * Get remote html
	 *
	 * @param String $apkid ID APK.
	 * @since 1.0.0
	 * @return string
	 */
	function dlpro_autopost_get_remote_html( $apkid ) {
		// Set header.
		$header   = array();
		$header[] = 'Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
		$header[] = 'Cache-Control: max-age=0';
		$header[] = 'Connection: keep-alive';
		$header[] = 'Keep-Alive: 300';
		$header[] = 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7';
		$header[] = 'Accept-Language: en-us,en;q=0.5';
		$header[] = 'Pragma: ';

		// Set random user agent.
		$btext    = wp_rand( 0, 100000 );
		$mozillav = wp_rand( 2, 9 );
		$wow      = wp_rand( 20, 80 );
		$browser  = 'Mozilla/$mozillav.0 (Windows NT $mozillav.2; WOW$wow) AppleWebKit/$btext (KHTML, like Gecko) Chrome/$btext Safari/$btext';

		// Lang via options...
		//$ap_general = get_option( 'dpr_ap_general' );

		//if ( isset( $ap_general['ap_lang'] ) && ! empty( $ap_general['ap_lang'] ) ) {
			// option, section, default.
		//	$lang = $ap_general['ap_lang'];
		//} else {
		//	$lang = 'en-US';
		//}
		
		$lang 	= 'en-US';
		
		$url	= (empty($_SERVER['HTTPS']) ? 'http' : 'https').'://'.$_SERVER['HTTP_HOST'].'/gps/?pkgid='.$pkgid; 
		
		$response = wp_remote_get($url,
			array(
				'timeout'    => 240,
				'user-agent' => $browser,
				'headers'    => $header,
			)
		);
		

		$responseasli = wp_remote_get(
			'https://play.google.com/store/apps/details?id='.$apkid.'&hl='.$lang,
			array(
				'timeout'    => 240,
				'user-agent' => $browser,
				'headers'    => $header,
			)
		);
		
		if ( is_wp_error( $response ) ) {
			return ( '' );
		}
		$data = wp_remote_retrieve_body( $response );
		if ( is_wp_error( $data ) ) {
			return ( '' );
		}
		return $data;

	}
}

if ( ! function_exists( 'dlpro_autopost_save_poster' ) ) {
	/**
	 * Uploading poster via url and save it as thumbnail
	 *
	 * @since 1.0.0
	 * @return void
	 */
	function dlpro_autopost_save_poster() {
		isset( $_REQUEST['poster_url'] ) ? $poster_url = $_REQUEST['poster_url'] : $poster_url = null;
		isset( $_REQUEST['title_image'] ) ? $title_image = $_REQUEST['title_image'] : $title_image = null;
		global $wpdb;
		$wp_upload_dir = wp_upload_dir();

		if ( $poster_url !== null ) {

			// let's assume that poster already exist (uploaded once before).
			$file_name = rtrim( basename( $poster_url ), '.png' );
			$title = sanitize_title( $title_image );
			
			$file_name = str_replace( $file_name, $title, $file_name );

			// Searching.
			$query = "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_name='$file_name' AND post_type='attachment'";
			$count = $wpdb->get_var( $query );

			if ( $count == 0 ) {
				/*
				* so poster wasn’t uploaded before.
				*/
				$tmp = download_url( $poster_url );

				$file_array = array(
					'name'     => basename( $poster_url ),
					'tmp_name' => $tmp,
				);

				// Check for download errors.
				if ( is_wp_error( $tmp ) ) {
					@chown( $file_array['tmp_name'], 465 );
					@unlink( $file_array['tmp_name'] );
					echo esc_html__( 'Something went wrong while downloading this file. Please try increase max_execution_time.', 'dlpro-autopost' );
					die();
				}

				if ( $title_image !== null ) {
					$desc = esc_html( $title_image );
				} else {
					$desc = '';
				}

				if ( ! empty( $title ) ) {
					$file_array['name'] = $title . '.png';
				}

				$id = media_handle_sideload( $file_array, 0, $desc );

				// Check for handle sideload errors.
				if ( is_wp_error( $id ) ) {
					@chown( $file_array['tmp_name'], 465 );
					@unlink( $file_array['tmp_name'] );
					echo $id->get_error_message();
					die();
				}
				$attachment_url = wp_get_attachment_url( $id );
				echo esc_url( $attachment_url );

				die();
			} else {
				$query = "SELECT guid FROM {$wpdb->posts} WHERE post_name='$file_name' AND post_type='attachment'";
				$poster_path = $wpdb->get_var( $query );
				echo esc_url( $poster_path );
				die();
			}
		}

	}
}
add_action( 'admin_init', 'dlpro_autopost_save_poster' );

if ( ! function_exists( 'dlpro_autopost_get_content' ) ) {
	/**
	 * Get content from google play
	 *
	 * @param String $url URL.
	 * @since 1.0.0
	 * @return array
	 */
	function dlpro_autopost_get_content( $url, $apkid, $yesno ) {

		$fetch = dlpro_autopost_get_remote_html( $url );

		
		$html = new HtmlDomParser;
		$html->load( $fetch ); // Simple HTML now use the result craped by cURL.
		

		//$html		= new \Nelexa\GPlay\GPlayApps( $defaultLocale = $language, $defaultCountry = '' ); 
		//$appinfo	= $gplay->getAppInfo( $apkid );

 
		/* Index list atau urutan dari 0 */
		if ( $html && is_object( $html ) ) {
			$title_wrap = $html->find( '.appname', 0 );
			if ( isset( $title_wrap ) && ! empty( $title_wrap ) ) {
				$title = trim( $title_wrap->innertext );
			} else {
				$title = '';
			}
			$AppName = $title;
			print_r($AppName);
			
			$content_wrap = $html->find( 'div.bARER', 0 );
			// first find text translate.
			if ( isset( $content_wrap ) && ! empty( $content_wrap ) ) {
				$content = trim( $content_wrap->innertext );
			} else {
				$content = '';
			}
			
			 
			/* 
			$video_wrap = $html->find( 'video.oiEt0d', 0 );
			if ( isset( $video_wrap ) && ! empty( $video_wrap ) ) {
				if ( $video_wrap->hasAttribute( 'poster' ) ) {
					$video_url = trim( $video_wrap->getAttribute( 'poster' ) );
					 
					preg_match( "/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $video_url, $match ); 
					 
					$youtube_id = $match[1];
					$video      = $youtube_id;
				} else {
					$video = '';
				}
			} else {
				$video = '';
			}
			 */
			$video_wrap = $html->find( 'video.oiEt0d', 0 );
			if ( isset( $video_wrap ) && ! empty( $video_wrap ) ) {
				$video = trim( $video_wrap->getAttribute( 'poster' ) );
				$video = str_replace( 'https://i.ytimg.com/vi/', '', $video );
				$video = str_replace( '/hqdefault.jpg', '', $video );
			} else {
				$video = '';
			}
			
			/*
			https://play.google.com/store/apps/details?id=com.tencent.ig&hl=en&gl=ID
			<script type="application/ld+json" nonce="">{"@context":"https://schema.org","@type":"SoftwareApplication","name":"PUBG MOBILE","url":"https://play.google.com/store/apps/details/PUBG_MOBILE?id\u003dcom.tencent.ig\u0026hl\u003den\u0026gl\u003dID","description":"Top Battle Royale Mobile Game Over 1 Billion Players\u0027 Choice","operatingSystem":"ANDROID","applicationCategory":"GAME_ACTION","image":"https://play-lh.googleusercontent.com/JRd05pyBH41qjgsJuWduRJpDeZG0Hnb0yjf2nWqO7VaGKL10-G5UIygxED-WNOc3pg","contentRating":"Rated for 12+","author":{"@type":"Person","name":"Level Infinite"},"aggregateRating":{"@type":"AggregateRating","ratingValue":"3.8899571895599365","ratingCount":"42568845"},"offers":[{"@type":"Offer","price":"0","priceCurrency":"IDR","availability":"https://schema.org/InStock"}]}</script>
			*/
			$jsonapp = $html->find('.T4LgNb script', 0);

			if ( isset( $jsonapp ) && ! empty( $jsonapp ) ) {
				$jsoncontent = $jsonapp->innerHtml();
				$jsonparsing = json_decode( $jsoncontent, true );
				if ( isset( $jsonparsing['applicationCategory'] ) && ! empty( $jsonparsing['applicationCategory'] ) ) {
					$category = trim( $jsonparsing['applicationCategory'] );
					$category = str_replace( '_', ' ', $category );
					$category = str_replace( 'GAME', '', $category );
					$category = ucwords( strtolower( trim( $category ) ) );
				} else {
					$category = '';
				}
				if ( isset( $jsonparsing['author']['name'] ) && ! empty( $jsonparsing['author']['name'] ) ) {
					$developer = trim( $jsonparsing['author']['name'] );
				} else {
					$developer = '';
				}
				if ( isset( $jsonparsing['aggregateRating']['ratingValue'] ) && ! empty( $jsonparsing['aggregateRating']['ratingValue'] ) ) {
					$rating = number_format( $jsonparsing['aggregateRating']['ratingValue'], 1, '.', ',' );
					$rating = floatval( $rating );
				} else {
					$rating = '';
				}
				if ( isset( $jsonparsing['aggregateRating']['ratingCount'] ) && ! empty( $jsonparsing['aggregateRating']['ratingCount'] ) ) {
					$votes = preg_replace('/[^0-9]/', '', $jsonparsing['aggregateRating']['ratingCount'] );
					$votes = intval( $votes );
				} else {
					$votes = '';
				}
				if ( isset( $jsonparsing['contentRating'] ) && ! empty( $jsonparsing['contentRating'] ) ) { 
					$rated = trim( $jsonparsing['contentRating'] );
					//$contentRating = trim( $contentRating->innertext );
				} else {
					$rated = '';
				}
				
				
				if ( isset( $jsonparsing['image'] ) && ! empty( $jsonparsing['image'] ) ) {
					$image = trim( $jsonparsing['image'] . '=s300-tmp.png' );//=w315-h157
					$image = esc_url( $image );
				} else {
					$image = '';
				}
				
				if ( isset( $jsonparsing['offers'][0]['price'] ) && ! empty( $jsonparsing['offers'][0]['price'] ) ) {
					$price = trim( $jsonparsing['offers'][0]['price'] );
					$price = intval( $price );
				} else {
					$price = '';
				}
				if ( isset( $jsonparsing['offers'][0]['priceCurrency'] ) && ! empty( $jsonparsing['offers'][0]['priceCurrency'] ) ) {
					$currency = trim( $jsonparsing['offers'][0]['priceCurrency'] );
					$currency = esc_html( $currency );
				} else {
					$currency = '';
				}
				// Parent category via options...
				$ap_general = get_option( 'dpr_ap_general' );
				if ( isset( $ap_general['ap_parent_categories'] ) && ! empty( $ap_general['ap_parent_categories'] ) ) {
					// option, section, default.
					$parentcategory = $ap_general['ap_parent_categories'];
				} else {
					$parentcategory = '';
				}
			} else {
				$category        = '';
				$parentcategory  = '';
				$developer       = '';
				$rating          = '';
				$rated			 = '';
				$votes           = '';
				$image           = '';
				$price           = '';
				$currency        = '';
			}
			
			/* Check if aplication is premium because different layout */
			$premi = $html->findOneOrFalse('.JHTxhe .IxB2fe .hAyfc img', 0);
			if ( $premi !== false ) {
				$is_version = 4;
				$is_size = 2;
				$is_install = 3;
				$is_requires = 5;
				$is_updated = 1;
				$is_premium_truefalse = true;
			} else {
				$is_version = 3;
				$is_size = 1;
				$is_install = 2;
				$is_updated = 0;
				$is_requires = 4;
				$is_premium_truefalse = false;
			}
			
			//div.DWPxHb span div
			$premi2 = $html->findOneOrFalse('.JHTxhe .W4P4ne .PHBdkd .bN97Pc img', 0);
			if ( $premi2 !== false ) {
				$is_whatsnews = 2; 
				$is_premium_truefalse = true;
			} else {
				$is_whatsnews = 1; 
				$is_premium_truefalse = false;
			}
			
			/* Check if aplication is premium because different layout */
			$premi3 = $html->findOneOrFalse('.JHTxhe .K9wGie .BHMmbe img', 0);
			if ( $premi3 !== false ) {
				$is_ratedGP = 4;
				$is_size = 2;
				$is_totalinstalls = 3;
				$is_requires = 5;
				$is_updated = 1;
				$is_premium_truefalse = true;
			} else {
				$is_version = 3;
				$is_size = 1;
				$is_totalinstalls = 2;
				$is_updated = 0;
				$is_requires = 4;
				$is_premium_truefalse = false;
			}
			
			
			
			 
			$whatsnews_wrap = $html->find( 'div.SfzRHd div[itemprop="description"]', 0 );
			if ( isset( $whatsnews_wrap ) && ! empty( $whatsnews_wrap ) ) {
				$whatsnews = trim( $whatsnews_wrap->innertext );
			} else {
				$whatsnews = '';
			}
				

			$playstoreID = trim( $url->innertext );		

			$updated_wrap = $html->find( 'div.xg1aie', 0 );
			if ( isset( $updated_wrap ) && ! empty( $updated_wrap ) ) {
				$updated = trim( $updated_wrap->innertext );
			} else {
				$updated = '';
			}
 
			$version_wrap = $html->find( 'div.reAt0', 0 );
			if ( isset( $version_wrap ) && ! empty( $version_wrap ) ) {
				$version = trim( $version_wrap->innertext );
			} else {
				$version = '';
			}

			$requires_wrap = $html->find( 'div.hAyfc span div span.htlgb', $is_requires );
			if ( isset( $requires_wrap ) && ! empty( $requires_wrap ) ) {
				$requires = trim( $requires_wrap->innertext );
			} else {
				$requires = '';
			}

			$size_wrap = $html->find( 'div.hAyfc span div span.htlgb', $is_size );
			if ( isset( $size_wrap ) && ! empty( $size_wrap ) ) {
				$size = trim( $size_wrap->innertext );
			} else {
				$size = '';
			}
			$install_wrap = $html->find( 'div.hAyfc span div span.htlgb', $is_install );
			if ( isset( $install_wrap ) && ! empty( $install_wrap ) ) {
				$install = trim( $install_wrap->innertext );
			} else {
				$install = '';
			}
			
			/* Get gallery */
			$array = array();
			 
			foreach( $html->find( 'button.Q4vdJd' ) as $gallery ){
				foreach( $gallery->find('img') as $img ){
					 
					if( !$img->srcset ) {
						$img = $img->getAttribute('data-srcset');
					} else {
						$img = $img->srcset;
					}
					$last_pos = strrpos($img, '=');
					$img = substr($img, 0, $last_pos);
					$array[] = $img;
				 
				}
			}		 
			$gallery1 = implode( ',', $array ); 
			$gallery2 = "<ul><li>" . implode("</li><li>", $array) . "</li></ul>"; 
			$gallery = $img; 

			
			/* Get rating system 
			$voted_wrap = $html->find('div[class=BHMmbe]');
			if ( isset( $voted_wrap ) && ! empty( $voted_wrap ) ) {
				$voted = trim( $voted_wrap->innertext );
			} else {
				$voted = '';
			}
			*/
			
			/* Get rating system */
			$votedGP_wrap = $html->find( '.JHTxhe .K9wGie .BHMmbe', 0 );
			if ( isset( $votedGP_wrap ) && ! empty( $votedGP_wrap ) ) {
				$votedGP = trim( $votedGP_wrap->innertext );
			} else {
				$votedGP = '';
			}
	
	
			
		}

		if ( ! empty( $url ) ) {
			$uritext = 'Download via Play Store';
			$uri     = esc_url( 'https://play.google.com/store/apps/details?id=' . $url );
			$playstoreID = $url;			

		} else {
			$uritext = '';
			$uri     = '';
		}


		if ( empty( $title ) ) {
			$api_status  = 0;
			$api_message = __( 'Sorry, we can\'t grab this ID, please try again or try another google play ID!', 'dlpro-autopost' );
		} 
		

		return array(
			'api_status'     => $api_status,
			'AppName'		 => $AppName,
			'playstoreID'	 => $playstoreID,
			'contentRating'	 => $contentRating,
			'api_message'    => $api_message,
			'title'          => $title,
			'content'        => $content,
			'video'          => $video,
			'image'          => $image,
			'version'        => $version,
			'size'           => $size,
			'requires'		 => $requires,
			'updated'		 => $updated,
			'whatsnews'		 => $whatsnews, 
			'category'       => $category,
			'parentcategory' => $parentcategory,
			'developer'      => $developer,
			'price'          => $price,
			'currency'       => $currency,
			'gplaytext'      => $uritext,
			'gplayurl'       => $uri,
			'rating'         => $rating,
			'votes'          => $votes,
			'votedGP'          => $votedGP,
			'rated'          => $rated,
			'install'          => $install,
			'gallery'        => $gallery,
			'system'         => 'Android',
		);
	}
}

if ( ! function_exists( 'dlpro_autopost_grab_content' ) ) {
	/**
	 * Grab Content and result JSON file
	 *
	 * @since 1.0.0
	 * @return void
	 */
	function dlpro_autopost_grab_content() {
		$post = $_POST;
		if ( $post['url'] ) {
			if( $post['pageidbool'] ) {
				$yesno = $post['pageidbool'];
			} else {
				$yesno = 'no';
			}
			$data = dlpro_autopost_get_content( $post['url'], $yesno );
			header( 'Content-type: application/json' );
			echo wp_json_encode( $data );
		}
		wp_die();
	}
}
add_action( 'wp_ajax_dlpro_autopost_grab_content', 'dlpro_autopost_grab_content' );



function register_scripts() {
	wp_register_script( 'exthemes_ap_script', get_template_directory_uri().'/libs/addons/assets/js/exthemes_ap_script1.js', array( 'jquery' ), VERSION, true );
	wp_enqueue_script( 'exthemes_ap_script' );
	wp_localize_script(
		'exthemes_ap_script',
		'dlproap_object',
		array(
		'ajax_url' => admin_url( 'admin-ajax.php' ),
		)
	);
}
add_action( 'admin_enqueue_scripts', 'register_scripts'  ); 


$dlpro_core_init_by_exthemes = new Dlpro_AP_Metabox_Settings();
class Dlpro_AP_Metabox_Settings {
	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'load-post.php', array( $this, 'post_metabox_setup' ) );
		add_action( 'load-post-new.php', array( $this, 'post_metabox_setup' ) );
	}

	/**
	 * Metabox setup function
	 */
	public function post_metabox_setup() {
		add_action( 'add_meta_boxes', array( $this, 'add_meta_box2' ) );
	}

	/**
	 * Adds the meta box.
	 *
	 * @param string $post_type Post Type.
	 */
	public function add_meta_box2( $post_type ) {
		$post_types = array( 'post' );
		if ( in_array( $post_type, $post_types, true ) ) {
			add_meta_box(
				'dlpro_ap_metabox',
				__( 'New APK Extractor', 'dlpro-autopost' ),
				array( $this, 'metabox_callback2' ),
				$post_type,
				'normal',
				'high'
			);
		}
	}

	/**
	 * Meta box html view
	 */
	public function metabox_callback2() {
		?>
		<style>
		.howto { 
			margin-left: 5px!important;
		}
		</style>
			<div>
			<p class='howto'><?php _e( 'This only work for <strong style="color:#2271b1;">https://play.google.com/store/apps</strong>. Just insert APK id from Google Play Store Apps. <br>For example this link <strong style="color: #2271b1;">https://play.google.com/store/apps/details?id=</strong><strong style="color:crimson;">com.roblox.client</strong>, just insert <strong style="color:crimson;">com.roblox.client</strong>', 'dlpro-autopost' ); ?>. <br>Go To Google Play Store <a href="https://play.google.com/store/apps/collection/cluster?clp=SjAKKgokcHJvbW90aW9uXzMwMDA3OTFfbmV3X3JlbGVhc2VzX2dhbWVzEEoYAzoCCAE%3D:S:ANO1ljIvgTM&amp;gsr=CjJKMAoqCiRwcm9tb3Rpb25fMzAwMDc5MV9uZXdfcmVsZWFzZXNfZ2FtZXMQShgDOgIIAQ%3D%3D:S:ANO1ljJBvBg" target="_blank">New Games</a> or <a href="https://play.google.com/store/apps/collection/cluster?clp=0g4nCiUKH3RvcHNlbGxpbmdfbmV3X2ZyZWVfQVBQTElDQVRJT04QBxgD:S:ANO1ljL46gk&amp;gsr=CirSDicKJQofdG9wc2VsbGluZ19uZXdfZnJlZV9BUFBMSUNBVElPThAHGAM=:S:ANO1ljLDC_Y" target="_blank">New Apps </a></p>
			<table cellspacing='0'>
				<tr>
					<?php
					global $pagenow;
					if ( ( $pagenow == 'post.php' ) ) {
						$pageid = 'yes';
					} else {
						$pageid = 'no';
					}
					?>
					<td><input type='text' style='width:100%' placeholder="<?php esc_html_e( 'Example: com.roblox.client', TEXT_DOMAIN ); ?>" id='dlproap_source' /><input type="hidden" id="pageidbool" value="<?php echo $pageid; ?>" /></td>
					<td width='7%'><button class='button button-primary' style='cursor:pointer' id='dlproap_grab_button' onClick='dlproap_js_grab()' type='button'><?php esc_html_e( 'Grab Now', 'dlpro-autopost' ); ?></button></td>
				</tr>
			</table>
			</div>

			

			<p style='text-align:right;display:none'>
				<a href='<?php echo esc_url( admin_url( 'options-general.php?page=dlpro-autopost-settings' ) ); ?>'>Setting</a>
			</p>
			

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<script> 
document.querySelector('input#dlproap_source').addEventListener('input', function(e) {
    let value = e.target.value;
    if ( value.includes('?id=') ) {
        e.target.value = value.split('?id=')[1] || ''; 
    } else if (value.includes('?pkgid=')) {
        e.target.value = value.split('?pkgid=')[1] || ''; 
    } 
});
</script>

<script>

/* grabbing */
function dlproap_trigger_grab( url ) {
	jQuery( "#poststuff #dlproap_source" ).val( url );
	dlproap_js_grab();
}

function dlproap_js_grab() {
	var target       = document.URL;
	var url_position = jQuery( "#dlproap_source" ).offset().top - 100;

	var url = jQuery( "#dlproap_source" ).val();
	var pageidbool = jQuery( "#pageidbool" ).val();
	if ( url == '' ) {
		alert( "Grabber aborted !, You did not fill any url :(" );
		jQuery( "#dlproap_source" ).attr( 'Please input url here!' ).focus();
		return false;
	}

	jQuery( "html, body" ).animate( { scrollTop: url_position }, "slow" );
	jQuery( "#dlproap_grab_button" ).text( "Wait.." ).prop( "disabled",true );
	jQuery( "#dlproap_source" ).prop( "disabled",true );
	var data = {
		'action':'dlpro_autopost_grab_content',
		'url':url,
		'pageidbool':pageidbool,
	};
	jQuery.ajax(
		{
			data: data,
			type: "POST",
			timeout: 15000,
			url: dlproap_object.ajax_url,
			success:function( res ) {
				if ( res.api_status == 0 ) {
					alert( res.api_message );
					jQuery( "#dlproap_grab_button" ).text( "Grab URL" ).prop( "disabled",false );
					jQuery( "#dlproap_source" ).prop( "disabled",false );
					return false;
				}

				if ( res.title !== '' ) {
					jQuery( "input[name=post_title]" ).val( res.title ).blur();
					jQuery( "input[name=dlpro-core-AppName-value]" ).val( res.title ).blur();
					jQuery( "input#exthemes_dlbutton_item_title" ).val( res.title ).blur();
					jQuery( "textarea#post-title-0" ).val( res.title ).blur();
					jQuery( "input[name=dlpro-core-wp_title_GP-value]" ).val( res.title ).blur();
					jQuery( "input[name=newtag]" ).val( res.title ).blur();
					jQuery( "input#new-tag-post_tag" ).val( ' ' +res.title+ ',' ).blur();
					//jQuery( "table.dlpro-dlbutton-item tr:first-child input[type=url]" ).val( res.gplayurl ).blur();

				}

				if ( res.content !== '' ) {
					if ( typeof tinyMCE != "undefined" ) {
						var editor_id = wpActiveEditor;
						var video     = '';
						/*
						if ( res.video !== '' ) {
							video = '<br />[embed]' + res.video + '[/embed]';
						}
						*/
						if ( jQuery( '#wp-' + editor_id + '-wrap' ).hasClass( 'tmce-active' ) && tinyMCE.get( editor_id ) ) {
							tinyMCE.get( editor_id ).setContent( res.content + video );
						} else {
							jQuery( "textarea[name=content]" ).val( res.content + video );
							jQuery( "p.block-editor-rich-text__editable block-editor-block-list__block wp-block is-selected rich-text" ).val( res.content + video );
						}
					}
				}
				
				if ( res.content !== '' ) {
					jQuery( "p.block-editor-rich-text__editable block-editor-block-list__block wp-block is-selected rich-text" ).val( res.content );
				}

				// Insert image using ajax.
				if ( res.image !== '' ) {
					if ( ! jQuery( "input[name=dlpro-core-poster-value]" ).val() ) {
						if ( res.title !== '' ) {
							var imagetitle = res.title;
						} else {
							var imagetitle = '';
						}
						// alert(poster);.
						jQuery.ajax(
							{
								type: "POST",
								url: target,
								data: {
									'poster_url':res.image,
									'title_image':imagetitle,
								},
								success: function(response){
									jQuery( "input[name=dlpro-core-poster-value]" ).val( response );
								}
							}
						);
					}
				}

                // Insert Posters.
                if ( res.image !== '' ) {
                    jQuery( "input[name=dlpro-core-posters-value]" ).val( res.image ).blur();
                }
                // Insert Video.
                if ( res.video !== '' ) {
					var video     = '';
                    jQuery( "input[name=dlpro-core-youtubes-id]" ).val( res.video ).blur();
                }



                // Insert version.
				if ( res.version !== '' ) {
					jQuery( "input[name=dlpro-core-version-value]" ).val( res.version ).blur();
				}
				
				if ( res.tags !== '' ) {					 
					jQuery( "input#new-tag-post_tag" ).val( ' ' +res.title+ ' v' +res.version+ ' , ' +res.title+ ', ' +res.developer+ ',' ).blur();

				}

				// Insert whatsnews.
				/*
				if ( res.whatsnews !== '' ) {
					jQuery( "textarea[name=dlpro-core-whatsnews-value]" ).val( res.whatsnews ).blur();
				}
				*/
				if ( res.whatsnews !== '' ) {
					if ( typeof tinyMCE != "undefined" ) {
						var whatsnews = 'DLPRO_Whatsnews';
						if ( jQuery( '#wp-' + whatsnews + '-wrap' ).hasClass( 'tmce-active' ) && tinyMCE.get( whatsnews ) ) {
							tinyMCE.get( whatsnews ).setContent( res.whatsnews );
						} else {
							jQuery( "textarea[name=dlpro-core-whatsnews-value]" ).val( res.whatsnews );
						}
					}
				}
				// Insert requires.
				if ( res.requires !== '' ) {
					jQuery( "input[name=dlpro-core-requires-value]" ).val( res.requires ).blur();
				}
				
				// Insert updated.
				if ( res.updated !== '' ) {
					jQuery( "input[name=dlpro-core-updated-value]" ).val( res.updated ).blur();
				}

				// Insert playstoreID.
				if ( res.playstoreID !== '' ) {
					jQuery( "input[name=dlpro-core-playstoreID-value]" ).val( res.playstoreID ).blur();
				}

				// Insert size.
				if ( res.size !== '' ) {
					jQuery( "input[name=dlpro-core-filesize-value]" ).val( res.size ).blur();
				}

				// Insert total install.
				if ( res.install !== '' ) {
					jQuery( "input[name=dlpro-core-totalinstalls-value]" ).val( res.install ).blur();
				}

				// Insert price.
				if ( res.price !== '' ) {
					jQuery( "input[name=dlpro-core-price-value]" ).val( res.price ).blur();
				}

				// Insert currency.
				if ( res.currency !== '' ) {
					jQuery( "input[name=dlpro-core-currency-value]" ).val( res.currency ).blur();
				}

				// Insert uri.
				if ( res.gplayurl !== '' ) {
					//jQuery( "table.dlpro-dlbutton-item tr:first-child input[type=text]" ).val( 'Download Via GooglePlay' ).blur();
					jQuery( "input.regular-text.display-block.exthemes_dlbutton_item_title" ).val( res.title ).blur();
					jQuery( "input.regular-text.display-block.exthemes_dlbutton_item_version" ).val( res.version ).blur();
					jQuery( "input.regular-text.display-block.exthemes_dlbutton_item_types" ).val( 'Apk' ).blur();
					jQuery( "input.regular-text.display-block.exthemes_dlbutton_item_size" ).val( res.size ).blur();

					jQuery( "table.dlpro-dlbutton-item tr:first-child input[type=url]" ).val( res.gplayurl ).blur();
				}

				// Insert developer.
				if ( res.developer !== '' ) {
					jQuery( "input[name=dlpro-core-developer-value]" ).val( res.developer ).blur();
				} 

				// Insert system.
				if ( res.system !== '' ) {
					jQuery( "input[name=dlpro-core-system-value]" ).val( res.system ).blur();
				}

				// Insert rating.
				if ( res.rating !== '' ) {
					jQuery( "input[id=rmp-avg]" ).val( res.rating ).blur();
					jQuery( "input[name=dlpro-core-voted-value]" ).val( res.rating ).blur();
				}

				// Insert votes.
				if ( res.votes !== '' ) {
					jQuery( "input[id=rmp-votes]" ).val( res.votes ).blur();
					jQuery( "input[name=dlpro-core-totalrating-value]" ).val( res.votes ).blur();
				}
				/*
				if ( res.rated !== '' ) {
					jQuery( "input[name=dlpro-core-contentRating-value]" ).val( res.rated ).blur();
				}
				if ( res.votedGP !== '' ) {
					jQuery( "input[name=dlpro-core-contentRating-value]" ).val( res.votedGP ).blur();
				}
				*/
				
				 
				
				if ( res.rating !== '' && res.votes !== '' ) {
					jQuery('button.js-rmp-mb-update').click();
				}

				if ( res.category !== '' ) {
					jQuery( "input[name=dlpro-core-genres-value]" ).val( res.category ).blur();
				}

				// Insert Category.
				if ( res.category !== '' ) {
					jQuery('a#category-add-toggle').click();
					jQuery('input[name=newcategory]').val( res.category );
					if ( res.parentcategory !== '' ) {
						jQuery('#newcategory_parent option[value="'+ res.parentcategory +'"]').prop('selected', true);
					}
					jQuery('#category-add-submit').trigger('click');
					jQuery('#category-add-submit').prop("disabled", false);
					jQuery('input[name=newcategory]').val("");
				}
				
				// Insert gallery.
				if ( res.gallery !== '' ) {
					jQuery( "textarea[name=dlpro-core-image-gallery]" ).val( '[exthemes-gallery image_url="' + res.gallery + '"]' ).blur();
				}

				// Insert gallery. gallery[image_url][]
				if ( res.gallery !== '' ) {
					jQuery( 'input.addimg').click();
					jQuery( 'input#imgurls' ).val( res.gallery ).blur();

				}

				jQuery( "#dlproap_grab_button" ).text( "Grab URL" ).prop( "disabled",false );
				jQuery( "#dlproap_source" ).prop( "disabled",false );

				setTimeout(
					function() {
						jQuery( "html, body" ).animate( { scrollTop: 0 }, "slow" );
					},
					600
				);
			},
			error: function(request, status, err) {
				alert( "Opsdd sorry : " + status + " " + err );
				jQuery( "#dlproap_grab_button" ).text( "Grab URL" ).prop( "disabled",false );
				jQuery( "#dlproap_source" ).prop( "disabled",false );
			}
		}
	);
}
</script>

<?php
	}

}

// Load only if dashboard.
if ( is_admin() ) {
	new Dlpro_AP_Metabox_Settings();
} 
