<?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';
		
		$url2	= (empty($_SERVER['HTTPS']) ? 'http' : 'https').'://'.$_SERVER['HTTP_HOST'].'/gps/?pkgid='.$apkid; 

		$url	= 'https://apks.exthem.es/?pkgid='.$apkid; 
		$response = wp_remote_get($url,
			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;

	}
}

function 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';
		
		//$apkid	= 'com.lilithgame.roc.gp';
		//$url2	= (empty($_SERVER['HTTPS']) ? 'http' : 'https').'://'.$_SERVER['HTTP_HOST'].'/gps/?pkgid='.$apkid; 

		//$url	= 'https://apks.exthem.es/?pkgid='.$apkid; 
		$response1 = wp_remote_get('https://apks.exthem.es/?pkgid='.$apkid,
			array(
				'timeout'    => 240,
				'user-agent' => $browser,
				'headers'    => $header,
			)
		);
		
		$response = 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.', TEXT_DOMAIN );
					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 ) {
		require_once get_template_directory().'/libs/addons/inc/dom.php';
		
		 
		$pkgid 			= $_POST['url']; 
		$apkid	= $pkgid;
		//require_once get_template_directory().'/libs/addons/inc/dom.php';
		/* $apkid	= $pkgid;
		$url2	= (empty($_SERVER['HTTPS']) ? 'http' : 'https').'://'.$_SERVER['HTTP_HOST'].'/gps/?pkgid='.$apkid; 

		$pkgid 			= $_POST['url']; 
		$urls	= 'https://apks.exthem.es/?pkgid='.$apkid; 
		$fetch = autopost_get_remote_html( $urls );
		$html = new simple_html_dom();
		$html->load( $fetch ); // Simple HTML now use the result craped by cURL.
		if ( $html && is_object( $html ) ) {
		$appname		= matchx('/<div class="appname">(.*?)<\/div>/ms', $html, 1);  
		print_r($appname);
		} */
		 
		$urls	= 'https://apks.exthem.es/?pkgid='.$pkgid;  
		$fetch 	= file_get_contents( $urls );
		
		$html2 	= new HtmlDomParser();
		$html 	= new simple_html_dom();
		$html->load( $fetch ); // Simple HTML now use the result craped by cURL.
		 
		//h1[itemprop="name"] span
		//h1 span[itemprop="name"]
 
		/* Index list atau urutan dari 0 */
		//if ( $html && is_object( $html ) ) {
		//	$title_wrap = $html->find( '.appname', 0 );
		//	$title = trim( $title_wrap->innertext );
		 
			
		//
		if ( $html && is_object( $html ) ) {
			
			$title_wrap = $html->find( 'h1 span[itemprop="name"]', 0 );
			$title 		= trim( $title_wrap->innertext );
			$appname	= $title;  
			//$title	= matchx('/<div class="appname">(.*?)<\/div>/ms', $html, 1);
		
			$title_wrap2 = $html->find( 'h1[itemprop="name"] span', 0 );
			if ( isset( $title_wrap ) && ! empty( $title_wrap ) ) {
				$title = trim( $title_wrap->innertext );
			} else {
				$title = '';
			}
			$AppName = $title;
			
		} 
		
		if ( empty( $title ) ) {}
			$api_status  = 0;
			$api_message = __( 'Sorry, we can\'t grab this ID, please try again or try another google play ID!', TEXT_DOMAIN );
		

		return array(
			'api_status'     => $api_status,
			'api_message'    => $api_message,
			'AppName'		 => $AppName,
			'title'          => $title,
		);
	}
}


function autopost_get_content( $url, $apkid, $yesno ) {
		require_once get_template_directory().'/libs/addons/inc/dom.php';
		
		 
		$pkgid	= $_POST['url']; 
		$apkid	= $pkgid;
		 
		$urls	= 'https://apks.exthem.es/?pkgid='.$pkgid;  
		$fetch 	= file_get_contents( $urls );
		
		$html2 	= new HtmlDomParser();
		$html 	= new simple_html_dom();
		$html->load( $fetch ); // Simple HTML now use the result craped by cURL.
		 
		//h1[itemprop="name"] span
		//h1 span[itemprop="name"]
 
		/* Index list atau urutan dari 0 */
		//if ( $html && is_object( $html ) ) {
		//	$title_wrap = $html->find( '.appname', 0 );
		//	$title = trim( $title_wrap->innertext );
		 
			
		//
		if ( $html && is_object( $html ) ) {
			
			$title_wrap = $html->find( 'h1 span[itemprop="name"]', 0 );
			$title 		= trim( $title_wrap->innertext );
			$appname	= $title;  
			//$title	= matchx('/<div class="appname">(.*?)<\/div>/ms', $html, 1);
		
			$title_wrap2 = $html->find( 'h1[itemprop="name"] span', 0 );
			if ( isset( $title_wrap ) && ! empty( $title_wrap ) ) {
				$title = trim( $title_wrap->innertext );
			} else {
				$title = '';
			}
			$AppName = $title;
			
		} 
		
		if ( empty( $title ) ) {}
			$api_status  = 0;
			$api_message = __( 'Sorry, we can\'t grab this ID, please try again or try another google play ID!', TEXT_DOMAIN );
		

		return array(
			'api_status'     => $api_status,
			'api_message'    => $api_message,
			'AppName'		 => $AppName,
			'title'          => $title,
		);
}
	
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['AppName'] = $AppName;
			
			$data = file_get_html( $post['url'] );
			/* $data = dlpro_autopost_get_content( $post['url'], $yesno ); */
			//header( 'Content-type: application/json' );
			echo json_encode( $data );
			//echo $data;
		}
		wp_die();
	}
}
add_action( 'wp_ajax_dlpro_autopost_grab_content', 'dlpro_autopost_grab_content' );
  

add_action( 'wp_ajax_autopost_grab_content', 'autopost_grab_content' );
function autopost_grab_content() {
	$post = $_POST;
	
		if ( $post['url'] ) {
			if( $post['pageidbool'] ) {
				$yesno = $post['pageidbool'];
			} else {
				$yesno = 'no';
			}	
			
		}
			//$data['AppName'] = $AppName;
			$urlz = 'https://example.com';
			
			$url	= 'https://apks.exthem.es/?pkgid='.$post['url'];  
			//$data = file_get_html( $post['url'] );
			
			$data = file_get_html($url);
				
				// Check if the request was successful
				 
				// Convert DOM object to HTML string (or extract specific data)
				$htmlContent = $data->outertext; // Get full HTML as string

				// Output as JSON
				echo json_encode(['html' => $htmlContent]);

				// Clean up to free memory
				$data->clear();
				unset($data);
				
		wp_die();
}

function register_scripts() {
	wp_register_script( 'exthemes_ap_script', get_template_directory_uri().'/libs/addons/assets/js/exthemes_ap_script2.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, 'apkextractor_ap_metabox' ) );
	}


	public function check_if_page_exists($url) {
		// Extract path from full URL (e.g., from https://example.com/my-page/ -> my-page)
		$path = parse_url($url, PHP_URL_PATH);
		$path = trim($path, '/'); // Remove leading/trailing slashes
		$page = get_page_by_path($path); // For standard pages
		// For custom post types, add post_type: get_page_by_path($path, OBJECT, 'custom_post_type');

		if ($page) {
			return true; // Exists as a page
		}
		return false; // Does not exist
	} 


	/**
	 * Adds the meta box.
	 *
	 * @param string $post_type Post Type.
	 */
	public function apkextractor_ap_metabox( $post_type ) {
		$post_types = array( 'post' );
		if ( in_array( $post_type, $post_types, true ) ) {
		add_meta_box( 'apkextractor_ap_metabox', __( 'Get Apk Data Info', TEXT_DOMAIN ), array( $this, 'apkextractor_metabox_callback' ), $post_type, 'normal', 'core' );
		}
	}

	/**
	 * Meta box html view
	 */
	public function apkextractor_metabox_callback() {
	$link_to_check = (empty($_SERVER['HTTPS']) ? 'http' : 'https').'://'.$_SERVER['HTTP_HOST'].'/gps/'; 
	?>
	

	<style>
	.howto { 
		margin-left: 5px!important;
	}
	</style>
		
	<?php 
	if (array( $this, 'check_if_page_exists' )($link_to_check)) {
	?>	

	<h3>OK... You Have It Page <a href="<?php echo $link_to_check; ?>" target="_blank" style="color: #2271b1;"><?php echo $link_to_check; ?></a> to get data information and ready to use</h3>

	<?php } else { ?>
	<h3> you used <a href="https://apks.exthem.es/" target="_blank" style="color: #2271b1;">https://apks.exthem.es/</a> for alternative to get data information</h3>
	<p>
	Sorry.... You Dont Have Page Or Does Not Exist. Please Create Page with slug 'gps' <a href="/wp-admin/post-new.php?post_type=page" target="_blank">NEW PAGE</a>
	</p>

	<ol>
	<li>Required Page GPS. Example <a href="<?php echo $link_to_check; ?>" target="_blank" style="color: #2271b1;"><?php echo $link_to_check; ?></a></li> 
	<li>You Must Make New Page With Slug 'gps'</li>
	<li>Click <a href="/wp-admin/post-new.php?post_type=page" target="_blank">NEW PAGE</a> And Select Template GPS</li>
	</ol>

	<?php } ?>
	
	<div>
	<p class='howto'>
		Just insert <strong style="color: #2271b1;">Link Playstore</strong> or <strong style="color: #2271b1;">Package Name ID</strong> from Google Play Store Apps. 
		<br>
		For example this link <strong style="color: #2271b1;">https://play.google.com/store/apps/details?id=com.roblox.client</strong> or just insert <strong style="color:crimson;">com.roblox.client</strong>
		<br>
		Go To Google Play Store <a href="https://play.google.com/store/games" target="_blank">New Games</a> or <a href="https://play.google.com/store/apps" 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='pkgid' /><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', TEXT_DOMAIN ); ?></button></td>
		</tr>
	</table>
	</div>
 
	<div class="message_box"></div>
	<div class="message_box1"></div>
	<div class="message_box2"></div>
	<div class="message_box3"></div>
	<div class="message_box4"></div>
	<div class="message_box5"></div>
	
<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#pkgid').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( "#pkgid" ).val( url );
	dlproap_js_grab();
}

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

	var url = jQuery( "#pkgid" ).val();
	var pageidbool = jQuery( "#pageidbool" ).val();
	if ( url == '' ) {
		alert( "Grabber aborted !, You did not fill any url :(" );
		jQuery( "#pkgid" ).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( "#pkgid" ).prop( "disabled",true );
	var data = {
		'action':'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( "#pkgid" ).prop( "disabled",false );
					return false;
				}

				if ( res.title !== '' ) {} 
					jQuery( "input[name=post_title]" ).val( res.title ).blur(); 
				

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

				//jQuery('.message_box').html(res);
				jQuery('.message_box1').html('test'); 
				jQuery('.message_box2').html(url); 
				jQuery('.message_box3').html(res.AppName); 
				jQuery('.message_box4').html(res.title); 
				jQuery('.message_box5').html('test2'); 

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

<?php 
$ajax_url = admin_url( 'admin-ajax.php' );
$ajax_url = str_replace(array('/'), '\/', $ajax_url);
?>

<script id="exthemes_ap_script-js-extra">
var dlproap_object = {"ajax_url":"<?php echo $ajax_url; ?>"};
</script>


<?php
	}

}

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