<?php
if ( ! defined( 'ABSPATH' ) ) exit;   
  
function wp_getmodsapk() { 
/**
 * ===============================
 * PHP & REQUEST CONFIG
 * Ambil option/theme global WordPress
 * Tampilkan error sesuai konstanta ERRORS
 * ===============================
*/ 
global $opt_themes;
@ini_set('display_errors', ERRORS);
 
/**
 * ===============================
 * LOAD CSS VIA SHORTCODE
 * ===============================
*/
echo do_shortcode('[css]');

/**
 * ===============================
 * INIT CLASS
 * Class untuk HTTP / CURL
 * Class utama struktur & scraper
 * ===============================
*/
$Go_Curl = new Go_Curl();
$sc = new StructurCode();

/**
 * ===============================
 * BASIC CONFIG
 * Post type yang akan digunakan
 * Source website target
 * Contoh URL demo (single post)
 * Ambil host saja dari URL demo
 * ===============================
*/ 
$types	= 'post';
$sources	= 'getmodsapk.com';
$demos	= 'https://getmodsapk.com/whatsapp-messenger-mod-apk/'; 
$demosx	= 'https://'.parse_url($demos)['host']; 
$checkx	= $Go_Curl->http_responsex($demosx); 

/**
 * ===============================
 * CONNECTION CHECK
 * Cek apakah domain source bisa diakses
 * ===============================
*/
$checkx = $Go_Curl->http_responsex($demosx);

/**
 * ===============================
 * API KEY SCRAPER
 * Ambil API key scraper dari option theme
 * ===============================
*/
$keyz = $opt_themes['api_key_scrape'];
 

/**
 * ===============================
 * URL & STATUS CHECK
 * Base protocol + source
 * Cek status HTTP URL demo (200 / 403 / 404)
 * ===============================
*/
$protocol = 'https://' . $sources;
$status = $Go_Curl->http_responsex($demos);
$sc_page     = 'sc-getmodsapk';
 
?>
 
  
	<div class="wrap">
	<div class="play_menu" style="text-transform:uppercase">
        <b>Add sources from <?php echo parse_url($protocol)['host']; ?></b>
	</div> 
	</div> 
	
	
	<?php 
	$demo    = $demos;
	$source  = $sources;
	$api_keys = !empty($opt_themes['api_key_scrape']) ? (array)$opt_themes['api_key_scrape'] : []; 
	$checker = new Check_Status_Cloudflare($Go_Curl, $demo, $source, $api_keys);
	$checker->check_and_display();
	?>
	
	
	<?php
	if (isset($_POST['wp_sb']) && isset($_POST['wp_url'])) {
		@ini_set('display_errors', ERRORS);

		$url = trim(strip_tags($_POST['wp_url']));

		if (!stristr($url, $sources)) {
		echo '<div class="play_menu" style="text-transform:uppercase!important;color:#00a0d2">
				<h3 style="color:#00a0d2">Link not supported: <b style="color:red">' . esc_html($url) . '</b></h3>
			  </div>';
		return;
		}

		require_once get_template_directory() . '/libs/addons/includes/class/getmodsapk.class.php';

		$getslinks = new scrapes;
		$data = $getslinks->scrape_web_info($url, false);

		if (empty($data) || isset($data['error'])) {
		echo '<div class="play_menu" style="text-transform:uppercase!important;color:#00a0d2">
				<h3 style="color:#00a0d2">Failed to retrieve data from the link</h3>
			  </div>';
		return;
		}	 

		$importer = new APK_Importer($data);

		// Jalankan proses import utama (create/update post, gambar, meta, taxonomy, dll)
		$result = $importer->import();
 
		$post_id = (int) $result;		
		
		// === Start Source download ===
		$importer->List_Download_Getmodsapk();
		// === Stop Source download ===
		
		$importer->add_direct_apk_download();	
		
		$thumb_id = get_post_thumbnail_id( $post_id );
		
		$img_id 	= $importer->get_featured_image_attachment_id();
		$image_url 	= wp_get_attachment_url( $img_id );

		/* 
		echo '<pre>';		
		print_r($img_id);
		echo '</pre>';	
	 
		echo '<pre>';		
		print_r($thumb_id);
		echo '</pre>';	 
		*/
	 
		// Jika semuanya berhasil → tampilkan hasil
		if ($post_id > 0) {
		$urlX = get_permalink($post_id);

		// File result.php biasanya menampilkan pesan sukses + link post
		echo $sc->render_result_post(
			$data,
			$post_id,
			$urlX,
			$image_url
		); 
		
		} else {
		echo '<div class="play_menu error" style="color:#dc3232">
				<h3>Post ID is invalid after import process</h3>
			  </div>';
		}
	}
	?>
	

    <div style="clear:both"></div>
	
	 
	<div class="wrap" id="play_fixed" >
	<div class=" play_menu" style="margin-bottom: 10px;">
		<ul id="menunya" class="play_menus" style="text-transform:capitalize">
			<li data-tab="tab1"><a><i class="fa fa-home"></i> Home</a></li> 
			<li <?php if(isset($_POST['submit'])) { ?> class="active" <?php } ?> data-tab="tab2"><a><i class="fa fa-search"></i> Search</a></li>  	
			<li <?php if (!isset($_POST["submit"]) && !isset($_POST["wp_sb"])) { ?>class="active" <?php } ?>data-tab="tab3"><a><i class="fa fa-rss"></i> Latest Games</a></li>
			<li data-tab="tab4"><a><i class="fa fa-rss"></i> Latest Apps</a></li>
			<li data-tab="tab5"><a><i class="fa fa-pencil-square-o"></i> add manual</a></li>
			<?php if(isset($_POST['wp_sb'])) { ?>
			<li <?php if(isset($_POST['wp_sb'])) { ?>class="active" <?php } ?>data-tab="tab6"><a><i class="fa fa-bullhorn"></i> Debugs</a></li>
			<?php } ?>	 
		</ul>
		<div style="clear:both"></div>
	</div>
    </div>
	 
   
    <div class="containerX">
        <div class="tab-content">
		
		<div id="tab1" class="tab-pane fade">
			<?php echo $sc->render_post_status_info($opt_themes); ?>
		</div>     

		<div id="tab2" class="tab-pane fade <?php if(isset($_POST['submit'])) { ?>in active <?php } ?>">
			<div class="play_menu" style="text-transform:uppercase"><b>Search</b></div>     

			<center> 

			<?php 
			if (isset($_POST['submit']))  { 
			if ((!isset($_POST['search_query'])) ) { 
			$error = "*" . "Please fill all the required fields"; 
			} else { 
			$search_query = $_POST['search_query'];  
			} 
			} 
			?>
			<ul style=" ">
			<li>Just add your <b>keyword</b> on form and click <b>Search</b></li> 
			</ul>		
			<form id="form1" method="post" action="" class='f'> 
			<?php 
			if (isset($_POST['submit'])) { if (isset($error)) { 
			echo "<p style='color:red;'>" 
			. $error . "</p>"; 
			} } 
			?>  
			
			<input type="text" name="search_query" placeholder="example : whatsapp"/>  
			<input type="submit" name="submit" value="Search"/> 
			</form> 
			</center> 

			<?php
			if(isset($_POST['submit'])) { 
			if(!isset($error)) {   
			require_once get_template_directory().'/libs/addons/inc/ssl.php';
			@ini_set('user_agent', 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)');  
			@ini_set('user_agent', 'My-Application/2.5');	 
			$search_query	= strtolower($_POST['search_query']); 
			$base_url		= 'https://getmodsapk.com/search?query=';
			$search_url		= $base_url.html_entity_decode( $search_query, ENT_COMPAT, 'UTF-8' );
			$link_cari		= $search_url;  
			//print_r($link_cari);
			
			$status 		= $Go_Curl->http_responsex($link_cari); 
			if($status === 403) {
			//$html			= scraperapi($link_cari);	
			$html			= $Go_Curl->scrapedox($link_cari);  
			} else {
			$html			= $Go_Curl->scrape_sitex($link_cari);	
			} 
			 
			// <h3 class="font-semibold text-gray-900 dark:text-white truncate">(.*?)<\/h3>
			$judul		= $Go_Curl->match_all('/<h3.*?>(.*?)<\/h3>/ms', $Go_Curl->match('/<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">(.*?)<\/section>/ms', $html, 1), 1);  
					
			$links		= $Go_Curl->match_all('/<a.*?href="(.*?)\".*?/ms', $Go_Curl->match('/<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">(.*?)<\/section>/ms', $html, 1), 1);  
			 
			$img		= $Go_Curl->match_all('/<img.*?src="(.*?)\".*?>/ms', $Go_Curl->match('/<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">(.*?)<\/section>/ms', $html, 1), 1);  
			
			$versi		= $Go_Curl->match_all('/<span class="text-xs text-gray-600 dark:text-gray-300">(.*?)<\/span>/ms', $Go_Curl->match('/<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">(.*?)<\/section>/ms', $html, 1), 1);  
			
			$mods		= $Go_Curl->match_all('/<span class="inline-flex items-center gap-1 text-xs".*?>.*?<\/svg>(.*?)<\/span>/ms', $Go_Curl->match('/<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">(.*?)<\/section>/ms', $html, 1), 1);  
			?> 
			
			<div class="play_menu" style="text-transform:uppercase;display:none;"><b> Result for "<?php echo $search_query; ?>"</b></div>  
			
			<section>
			<div class="row"> 
			 
			<?php 
			$count		= count($judul);
			$counter = 0;
			for ($i = 0; $i < $count; $i++) {  
			$counter++;		
			?>		

			<div class="col-12 col-md-6 mb-4">
			<span class="position-relative archive-post--remove app-container">
			<?php 	 
			$path1	= 'https://getmodsapk.com/'.$img[$i];
			$path	= $img[$i];
			$type 	= pathinfo($path, PATHINFO_EXTENSION);
			$data 	= get_url($path);
			$base64 = 'data:image/'.$type.';base64,'.base64_encode($data);  
			?>
			<div class="flex-shrink-0" style="position:relative;">
			<img src="<?php echo $path; ?>" class="app-logo " width="64" height="64"> 
			<span style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);background:rgba(0,0,0,0.8);color:white;padding:6px 10px;border-radius:6px;font-weight:bold;border:2px solid white;">
			<?php echo $counter; ?>
			</span>			
			</div>
				
			
			<div class="app-info">
			<h3 class="h5 font-weight-semibold w-100 app-title"><?php echo $judul[$i]; ?></h3>
			<div class="text-truncate text-muted app-desc">			
			<span class="clamp-1 w-100"><?php echo $mods[$i]; ?></span> 
			</div>
			</div>
			<div class="app-get">			
			<form method="POST">
			<input style="display:none" type="text" name="wp_url" value="<?php echo $links[$i]; ?>">
			<input type="submit" id="submit_<?php echo $count; ?>" name="wp_sb" class="get-button" value="<?php echo postnow; ?>" />
			</form>
			 
			<span class="app-version text-truncate"> <svg class="mr-1" xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="currentColor" viewBox="0 0 16 16">
			<path fill-rule="evenodd" d="M1 8a7 7 0 1 0 14 0A7 7 0 0 0 1 8zm15 0A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-7.5 3.5a.5.5 0 0 1-1 0V5.707L5.354 7.854a.5.5 0 1 1-.708-.708l3-3a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 5.707V11.5z"></path>
			</svg><?php echo $versi[$i]; ?></span>
			
			</div>
			</span>
			</div>
			 
			<?php } ?> 
			
			</div>
			</section>	
			<?php }} ?>	
		</div> 

		<div id="tab3" class="tab-pane fade <?php if (!isset($_POST["submit"]) && !isset($_POST["wp_sb"])) { ?>in active <?php } ?>">
		
			<div class="play_menu" style="text-transform:uppercase"><b>Latest Uploads Games </b></div>		
	
			<?php  	   
			$paged   = max(1, intval($_GET['games'] ?? 1));

			$is_ajax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
					   strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
					   
			$base_url 	= $paged > 1
			? "https://getmodsapk.com/games/?page={$paged}/"
			: "https://getmodsapk.com/games/";				
			
			$result = $sc->Code_Getmodsapk($base_url, $Go_Curl, $paged);

			if (!empty($result['error'])) {
				echo '<div class="alert alert-danger">'.$result['message'].'</div>';
				return;
			}

			$items       	= $result['items']; 
			$total_pages	= $result['total_page_game']; //total_page_game or total_page_app
			$current_page	= $result['current'];
			if ($is_ajax) ob_start();
			?>
			
			<section id="games-content">			
				<div class="row">		
				
				<?php				
				$counter = ($paged - 1) * 24 + 1;
				
				foreach ($items as $item) {

					$appId = $Go_Curl->get_playstore_id_by_title_google($item['title']);

					echo $sc->render_app_item([
						'title'           => $item['title'],
						'versi'         => $item['versi'],
						'link'            => $item['link'],
						'img'             => $item['image'],
						'appId'           => $appId,
						'getAppsPoster'   => $appId ? $Go_Curl->getAppsPoster($appId) : '',
						'getAppsCategory' => $appId ? $Go_Curl->getAppsCategory($appId) : '',
						'counter'         => $counter++,
					]);
				}
				?>
				
				</div>				 

			</section>

			<?php 
			$paged       = max(1, (int)($current_page ?? 1));
			$total_pages = max(1, (int)($total_pages ?? 1)); 
			echo $sc->games_page_navi(   // games_page_navi or apps_page_navi
				$result['current'],
				$result['total_page_game'],//total_page_game or total_page_app
				$sc_page
			);
			?>

			
		</div> 

		<div id="tab4" class="tab-pane fade">
			<div class="play_menu" style="text-transform:uppercase"><b>Latest Post Apps</b></div>
			
			 		 
			<?php     
			$paged		= max(1, intval($_GET['apps'] ?? 1));
			$is_ajax 	= !empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
					   strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
			
			$base_url 	= $paged > 1
			? "https://getmodsapk.com/apps/?page={$paged}/"
			: "https://getmodsapk.com/apps/";	
			
			$result = $sc->Code_Getmodsapk($base_url, $paged);

			if (!empty($result['error'])) {
				echo '<div class="alert alert-danger">'.$result['message'].'</div>';
				return;
			}

			$items       	= $result['items']; 
			$total_pages	= $result['total_page_app']; //total_page_game or total_page_app
			$current_page	= $result['current'];
			if ($is_ajax) ob_start();
			?>
			
			<section id="games-content">			
				<div class="row">		
				
				<?php				
				$counter = ($paged - 1) * 24 + 1;
				
				foreach ($items as $item) {

					$appId = $Go_Curl->get_playstore_id_by_title_google($item['title']);

					echo $sc->render_app_item([
						'title'           => $item['title'],
						'versi'         => $item['versi'],
						'link'            => $item['link'],
						'img'             => $item['image'],
						'appId'           => $appId,
						'getAppsPoster'   => $appId ? $Go_Curl->getAppsPoster($appId) : '',
						'getAppsCategory' => $appId ? $Go_Curl->getAppsCategory($appId) : '',
						'counter'         => $counter++,
					]);
				}
				?>
				
				</div>				 

			</section>

			<?php 
			$paged       = max(1, (int)($current_page ?? 1));
			$total_pages = max(1, (int)($total_pages ?? 1)); 
			echo $sc->apps_page_navi(  // games_page_navi or apps_page_navi
				$result['current'],
				$result['total_page_app'],//total_page_game or total_page_app
				$sc_page
			);
			?>
			 
		</div> 

		
		<div id="tab5" class="tab-pane fade">
			<?php echo $sc->render_manual_post_form($demos); ?> 
		</div> 
		
		
		<?php if(isset($_POST['wp_sb'])) { ?>
		<div id="tab6" class="tab-pane fade in active">
		<?php /* $sc->render_debug_app( $data, $url ); */ ?>
		<?php /* require_once get_template_directory().'/libs/addons/includes/debug.php';  */?>
		<?php echo $sc->render_debug_app( $data, $url );; ?> 
		</div>
		<?php } ?>
      
		</div>
	</div>
  
	
    <div style="clear:both"></div> 
<?php  
echo do_shortcode( '[ft_menu]' );
echo do_shortcode( '[ft_js]' ); 
}