<?php
if ( ! defined( 'ABSPATH' ) ) exit;  

function an1() {
global $opt_themes;
@ini_set('display_errors', ERRORS);   
@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');
echo do_shortcode( '[css]' );	
$Go_Curl 	= new Go_Curl();
$types		= 'post';
$sources	= 'an1.com';
$demos		= 'https://an1.com/7488-truck-simulator-big-rigs-mod.html';  
$demosx			= 'https://'.parse_url($demos)['host']; 

$checkx			= $Go_Curl->http_responsex($demosx); 
$keyz			= $opt_themes['api_key_scrape'];
//if($keyz){
//$rand_apikey 	= array_rand($keyz);
//$apikey 		= $keyz[$rand_apikey]; 
//}

$protocol 		= 'https://'.$sources;
$status 		= $Go_Curl->http_responsex($demos); 


?>

	<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		
	
	$status_code = $Go_Curl->http_responsex($demos);
 
	$allowed_statuses = [200, 201]; // or whatever indicates success

	if (in_array($status_code, [301, 302, 303, 307, 308, 403])) {
	?> 
	<div class="wrap">
	<div class="containerX">
	<h2></h2>
	<h3></h3>	 
	<!--<h5 style="text-align: center;">because its blocked by cloudflare</h5>-->
	<?php		
	if($keyz) {
	?>
	<div style="position:fixed; top:70px; right:20px; background:#333; color:#fff; padding:12px 20px; border-radius:8px; box-shadow:0 4px 12px rgba(0,0,0,0.2); z-index:9999; animation:toast 30s forwards;">
	<p style="text-align: center;">because <?php echo parse_url($protocol)['host']; ?>  blocked by cloudflare</p>
	<p style="text-align: center;">Your using by Api Key</p>
	<input onclick="this.select()" readonly type="text" id="api_key_scrape" name="api_key_scrape" value="<?php echo api_rand(); ?>" class="regular-text" style="text-align: center;display: block;margin-right: auto;margin-left: auto;"/>
	</div>   
	<?php } else { ?>	
	<div style="position:fixed; top:70px; right:20px; background:#333; color:#fff; padding:12px 20px; border-radius:8px; box-shadow:0 4px 12px rgba(0,0,0,0.2); z-index:9999; animation:toast 30s forwards;">
	<p style="text-align: center;">Sorry.... scraping from <?php echo parse_url($demos)['host']; ?> blocked by cloudflare</p>
	<p style="text-align: center;">Please add your API key</p>
	<p style="text-align: center;"><a href="<?php echo apikey_page; ?>" target="_blank">Click HERE to add API key </a></p>
	</div>
 
	<?php } 
	
	$errorcode = $Go_Curl->http_responsex($demos); 
 
	if($errorcode === 403 && !$keyz) {
	echo '<h5 style="text-align: center;">Status : '.$errorcode.' Forbidden (blocked by cloudflare)</h5> ';

	} elseif($errorcode === 400) {
	echo '<h5 style="text-align: center;">Status : '.$errorcode.' Bad Request </h5> ';
		
	} elseif($errorcode === 404) {
	echo '<h5 style="text-align: center;">Status : '.$errorcode.' Not Found </h5> ';
		
	} elseif($errorcode === 500) {
	echo '<h5 style="text-align: center;">Status : '.$errorcode.' Internal Server Error </h5> ';
		
	} elseif($errorcode === 502) {
	echo '<h5 style="text-align: center;">Status : '.$errorcode.' Bad Gateway </h5> ';
		
	} elseif($errorcode === 503) {
	echo '<h5 style="text-align: center;">Status : '.$errorcode.' Service Unavailable </h5> ';
		
	} elseif($errorcode === 200) {
	echo '<h5 style="text-align: center;">Status : '.$errorcode.' OK </h5> ';
		
	}
	?>
	
	</div>
	</div>
	<?php 
	} elseif (in_array($status_code, $allowed_statuses)) {
	?> 
	 
	<?php 
	} else {
	?> 
	 
	<?php 
	}
	?>
 
	<?php 
	if(isset($_POST['wp_sb'])) {
		@ini_set('display_errors', ERRORS);
		if(isset($_POST['wp_url'])) {
		$url		= trim(strip_tags($_POST['wp_url']));
		if(stristr($url, $sources)) {
		require_once get_template_directory().'/libs/addons/includes/class/an1.class.php'; 
		
		$getslinks		= new scrapes;
		$gets_data		= $getslinks->scrape_web_info($url, false);
			
		require_once get_template_directory().'/libs/addons/includes/inc/top.php';
			
		if(count($gets_data) AND !isset($gets_data['error'])) {
		require_once get_template_directory().'/libs/addons/includes/inc/post_content.php';	
		require_once get_template_directory().'/libs/addons/includes/inc/img_gallery.php';	
 
		/*
		start from playstore
		*/
		require_once get_template_directory().'/libs/addons/includes/inc/playstore.php';	
			
		/*
		start from sources
		*/ 
		require_once get_template_directory().'/libs/addons/includes/inc/gma.php';	
			
		/*
		for apkmody metabox	
		*/
		require_once get_template_directory().'/libs/addons/includes/inc/dlpro.php';	
			
		if ( !empty($gets_data['title_GP']) ) { 
			wp_set_object_terms( $post_id, $gets_data['title_GP'], 'post_tag', true ); 
		} else {
			wp_set_object_terms( $post_id, $gets_data['app_name'], 'post_tag', true ); 
		}

		/* 
		$download_info_link = array();
		
		$count		= count($gets_data['downloadlinks_gma']);
		for ($i = 0; $i < $count; $i++) { 
		if ( !empty($gets_data['sizes_GP']) ) {
			$size_dw = $gets_data['sizes_GP'];
		} else {
			$size_dw = $gets_data['size_sc'];
		}

		preg_match('#^(.)* (\w*)$#', $gets_data['types_downloadlinks_gma'][$i], $matches); 
		$types_dw = end($matches); 
		
		if($opt_themes['import_apk']){	 
		$linkapkzURL	= esc_url($gets_data['downloadlinks_gma'][$i]); 
		$attach_id		= upload_remote_file_apk( $linkapkzURL );
		$link_urlz		= esc_url(wp_get_attachment_url($attach_id));
			
		if ( is_wp_error( $attach_id ) ) {
			echo 'Error: ' . $attach_id->get_error_message();
		} else {
			echo 'File uploaded! Attachment ID: ' . $attach_id . '<br>';
			echo 'URL: ' . wp_get_attachment_url( $attach_id );
		}
			
		} else {
			$link_urlz 		= esc_url($gets_data['downloadlinks_gma'][$i]); 
		}
		 
		
		if($opt_themes['ouo']){ 
		$link_urlz88 		= ouo_io_user(esc_url($gets_data['downloadlinks_gma'][$i])); 
			
		} else if($opt_themes['shrinkearn']){ 
		$link_urlz88 		= shrinkearn_user(esc_url($gets_data['downloadlinks_gma'][$i])); 
			 
		} else if($opt_themes['adurl']){ 
		$link_urlz88 		= adurl_user(esc_url($gets_data['downloadlinks_gma'][$i])); 
			
		} else { 
		$link_urlz88 		= esc_url($gets_data['downloadlinks_gma'][$i]); 
		}
		
		if ( !empty($gets_data['downloadlinks_gma']) ) { 
		$download_info_link_data = [
			'name'		=> $gets_data['name_downloadlinks_gma'][$i],
			'title' 	=> $gets_data['name_downloadlinks_gma'][$i],
			'url'		=> $link_urlz88,
			'links' 	=> $link_urlz88,
			'sizes'		=> wp_strip_all_tags($gets_data['size_downloadlinks_gma'][$i]),
			'sizes1' 	=> wp_strip_all_tags($gets_data['size_downloadlinks_gma'][$i]),
			'size'		=> wp_strip_all_tags($gets_data['size_downloadlinks_gma'][$i]),
			//'tipes'	=> $gets_data['types_downloadlinks_gma'][$i],
			'tipes' 	=> $types_dw,
			'notes' 	=> $gets_data['notes_downloadlinks_gma'][$i],
		]; 
		array_push($download_info_link, $download_info_link_data);
		update_post_meta($post_id, "repeatable_fields", $download_info_link);
		update_post_meta($post_id, "group_downloads_links", $download_info_link);
		}
 
		}
		*/

		$download_info_link = array(); // Atau [] untuk array kosong

		// Pastikan ada data download links
		/* if (empty($gets_data['downloadlinks_gma']) || !is_array($gets_data['downloadlinks_gma'])) {
			// Hapus meta jika tidak ada data
			delete_post_meta($post_id, 'repeatable_fields');
			delete_post_meta($post_id, 'group_downloads_links');
			return;
		} */

		$count = count($gets_data['downloadlinks_gma']);

		for ($i = 0; $i < $count; $i++) {
			// Lewati jika link utama kosong
			$original_url = trim($gets_data['downloadlinks_gma'][$i] ?? '');
			if (empty($original_url)) {
				continue;
			}

			// Sanitasi URL awal
			$original_url = esc_url_raw($original_url);

			// === Penentuan File Size ===
			// Prioritas: sizes_GP (mungkin dari Google Play), fallback ke size_sc atau per-index
			if (!empty($gets_data['size_downloadlinks_gma'])) {
				$size_display = wp_strip_all_tags($gets_data['size_downloadlinks_gma'][$i]);
			} elseif (!empty($gets_data['size_sc'])) {
				$size_display = wp_strip_all_tags($gets_data['size_sc']);
			} elseif (!empty($gets_data['sizes_GP'])) {
				$size_display = wp_strip_all_tags($gets_data['sizes_GP']);
			} else {
				$size_display = wp_strip_all_tags($gets_data['sizes_GP'] ?? '');
			}

			// === Penentuan Tipe File (ekstensi) === 
			// Ganti ini:
			// preg_match('#^(.)* (\w*)$#', $gets_data['types_downloadlinks_gma'][$i], $matches);
			// $types_dw = end($matches);

			// Dengan ini (REKOMENDASI):
			$full_url_or_path 	= $gets_data['types_downloadlinks_gma'][$i] ?? $gets_data['downloadlinks_gma'][$i] ?? '';

			$filename 			= basename(parse_url($full_url_or_path, PHP_URL_PATH));
			$extension 			= pathinfo($filename, PATHINFO_EXTENSION);

			$types_dw 			= !empty($extension) ? strtoupper($extension) : '';

			//preg_match('#^(.)* (\w*)$#', $gets_data['types_downloadlinks_gma'][$i], $matches);  // Ambil ekstensi terakhir (misal: APK, ZIP)
			//$types_dw = end($matches); 
			//$type_full = $gets_data['types_downloadlinks_gma'][$i] ?? '';
			//preg_match('#^(.)* (\w*)$#', $type_full, $matches); // Ambil ekstensi terakhir (misal: APK, ZIP)
			
			//$types_dw = !empty($matches) ? strtoupper(end($matches)) : '';

			// === Proses Upload APK ke Media Library (jika fitur aktif) ===			 

			if($opt_themes['import_apk']){	 
			
			$attach_id		= upload_remote_file_apk( $original_url, $post_id ); 
				
			if ( is_wp_error( $attach_id ) ) {
				echo 'Error: ' . $attach_id->get_error_message();
				error_log( 'APK Upload Failed [' . $post_id . ']: ' . $attach_id->get_error_message() );
				$final_url 	= esc_url_raw( $original_url );
			} else {
				error_log( 'File uploaded! Attachment ID [' . $post_id . ']: ' . wp_get_attachment_url( $attach_id ) );
				echo 'File uploaded! Attachment ID: ' . $attach_id . '<br>';
				echo 'URL: ' . wp_get_attachment_url( $attach_id );
				$final_url 	= wp_get_attachment_url( $attach_id );
			}
				
			} else {
				$final_url = esc_url_raw( $original_url );
			}

			// Ambil setting dari Redux
			$enable_auto = isset( $opt_themes['enable_shortlinks'] ) ? $opt_themes['enable_shortlinks'] : false;
			$service     = isset( $opt_themes['auto_shortlink'] ) ? $opt_themes['auto_shortlink'] : 'ouo_sl';

			// Jika fitur Automatic Short Links MATI → langsung pakai URL asli
			if ( ! $enable_auto ) {
				$shortened_url = $final_url;
			} else {
				// Fitur AKTIF → proses sesuai service yang dipilih
				switch ( $service ) {
					case 'ouo_sl':
						$shortened_url = ouo_io_user( $original_url );
						break;

					case 'shrinkearn_sl':
						$shortened_url = shrinkearn_user( $original_url );
						break;

					case 'paid4link_sl':
						$shortened_url = paid4link_user( $original_url );
						break;

					case 'adurl_sl':
						$shortened_url = adurl_user( $original_url );
						break;

					default:
						$shortened_url = $final_url; // fallback jika service tidak dikenali
						break;
				}
			}
			 
			// Pastikan URL akhir valid
			$link_url = esc_url($shortened_url) ?: $final_url;

			// === Bangun data link ===
			$download_info_link[] = array(
				'name'   => sanitize_text_field($gets_data['name_downloadlinks_gma'][$i] ?? ''),
				'title'  => sanitize_text_field($gets_data['name_downloadlinks_gma'][$i] ?? ''),
				'url'    => $link_url,
				'links'  => $link_url,
				'size'   => $size_display,           // Cukup satu field size
				'tipes'  => $types_dw,
				'notes'  => sanitize_text_field($gets_data['notes_downloadlinks_gma'][$i] ?? ''),
			);
		}

		// === Simpan ke post meta (HANYA SEKALI di luar loop!) ===
		if (!empty($download_info_link)) {
			update_post_meta($post_id, 'repeatable_fields', $download_info_link);
			update_post_meta($post_id, 'group_downloads_links', $download_info_link);
		} else {
			// Hapus meta jika akhirnya kosong
			//delete_post_meta($post_id, 'repeatable_fields');
			//delete_post_meta($post_id, 'group_downloads_links');
		}


		if ( !empty($gets_data['sizes_GP']) ) {
			$size_dwz = $gets_data['sizes_GP'];
		} else {
			$size_dwz = $gets_data['size_sc'];
		}

		if ( !empty($gets_data['title_GP']) ) { 
			$title_dwz = $gets_data['title_GP'].' Apk'; 
		} else {
			$title_dwz = $gets_data['app_name'].' Apk'; 
		}

		/* 
		if ($opt_themes['ouo']) {
		$linkapkz	= ouo_io_exhemes('https://exthem.es/apk.php?pkg='.$gets_data['GP_ID']);
		} else {
		$linkapkz	= ouo_io_exhemes('https://exthem.es/apk.php?pkg='.$gets_data['GP_ID']);
		}

		if ($opt_themes['shrinkearn']) {
		$linkapkz	= shrinkearn_exhemes('https://exthem.es/apk.php?pkg='.$gets_data['GP_ID']);
		} else {
		$linkapkz	= shrinkearn_exhemes('https://exthem.es/apk.php?pkg='.$gets_data['GP_ID']);
		} 
		*/

		$linkapkz	= ouo_io_exhemes('https://exthem.es/apk.php?pkg='.$gets_data['GP_ID']);
		$linkapkz1	= adurl_exhemes('https://exthem.es/apk.php?pkg='.$gets_data['GP_ID']);
		$linkapkz2	= ouo_io_exhemes('https://play.google.com/store/apps/details?id='.$gets_data['GP_ID']);


		$download_info_link_data_gps = [
			'name'	=> $title_dwz,
			'title' 	=> $title_dwz,
			'url'	=> $linkapkz,
			'links' 	=> $linkapkz,
			'sizes1' 	=> $size_dwz,
			'sizes' 	=> $size_dwz,
			'size'	=> $size_dwz,
			'tipes' 	=> '',
			'notes' 	=> '',
		]; 

		array_push($download_info_link, $download_info_link_data_gps);
		update_post_meta($post_id, "repeatable_fields", $download_info_link);
		update_post_meta($post_id, "group_downloads_links", $download_info_link);			

		require_once get_template_directory().'/libs/addons/includes/inc/dw_apt.php';	
		require_once get_template_directory().'/libs/addons/includes/inc/dw_apkgk.php';	

		wp_set_object_terms( $post_id, $gets_data['title_GP'], 'post_tag', true ); 

		if($post_id)
		$urlX			= get_permalink( $post_id );
		require_once get_template_directory().'/libs/addons/includes/result.php'; 
		}
		} else {
		echo '<div class="play_menu" style="text-transform:uppercase!important;color:#00a0d2"><h3 style="color:#00a0d2">Please check your link.. your link is <b style="color:red">'.$url.'</b></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 data-tab="tab2"><a><i class="fa fa-search"></i> Search </a></li>  	
		<li 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">   
			<ul class="play_menu" >
				<li>Your Status Post is <?php if($opt_themes['apk_status'] != 'draft') { ?> <blink><strong class="blink blink-one" style="color:green"><?php echo $opt_themes['apk_status']; ?></strong></blink> You ready to Make auto posting now <?php } else { ?><blink><strong class="blink blink-one" style="color:red"><?php echo $opt_themes['apk_status']; ?></strong></blink>. Please Change to <blink><strong class="blink" style="color:green">publish</strong></blink> to make Auto Posting,  you can go to Setting Page <?php } ?> </li>
			</ul>
		</div>     

		<div id="tab2" class="tab-pane fade">

			<div class="play_menu" style="text-transform:uppercase"><b>Search</b></div>     

			<center> 
			<?php 
			// === MAIN LOGIC ===
			$error = '';
			$results = [];
			$search_query = '';

			if (isset($_POST['submit'])) {
				if (empty(trim($_POST['search_query']))) {
					$error = "Please enter a search keyword";
				} else {
					$search_query = trim($_POST['search_query']);
					$query_encoded = urlencode($search_query);
					$search_url = "https://5play.org/index.php?lang=en&do=search&subaction=search&full_search=0&story={$query_encoded}";

					$html = get_url($search_url);

					if (!$html || strpos($html, 'sys-page-sect') === false) {
						$error = "No results found or site blocked the request.";
					} else {
						$block = matchx('/<section class="sys-page-sect">(.*?)<section class="sect sect-more">/ms', $html, 1);
						if (empty($block)) {
							$error = "No results found.";
						} else { 
							$judul = match_all('/<a.*?><span>(.*?)<\/span><\/a>/msi', $block, 1);
							$links = match_all('/<a.*?href="(.*?)\".*?>/msi', $block, 1);
							$img   = match_all('/<img.*?src="(.*?)".*?>/msi', $block, 1);
							$versi = match_all('/<div class="search-item-cat">(.*?)<\/div>/ms', $block, 1);

							for ($i = 0; $i < count($judul); $i++) {
								$results[] = [
									'title' => htmlspecialchars($judul[$i] ?? 'Unknown'),
									'link'  => $links[$i] ?? '#',
									'img'   => $img[$i] ?? 'https://via.placeholder.com/64/333/fff?text=APP',
									'versi' => htmlspecialchars($versi[$i] ?? 'N/A')
								];
							}
						}
					}
				}
			}
			?>
			<ul style=" ">
			<li>Just add your <b>keyword</b> on form and click <b><?php echo postnow; ?></b></li> 
			</ul>	
			
			<form id="form1" method="post" action="" class='f'> 

			<input type="text" name="search_query" placeholder="example : whatsapp" value="<?= htmlspecialchars($search_query) ?>"/>  
			<input type="submit" name="submit" value="Search"/> 
			</form> 
			</center> 
			
			<?php if (!empty($results)): ?>
			<div class="play_menu" style="text-transform:uppercase;"><b><?= count($results) ?> Results for "<strong><?= htmlspecialchars($search_query) ?></strong>"</b></div>  
			
			<section>
			<div class="row"> 
			 
			<?php 
			$counter = 1;
			foreach ($results as $index => $app): 
			
			if (empty($app['img']) || !strpos($app['img'], 'cdn.5play.org')) {
				$image  	= 'https://5play.org'.$app['img'] ?? 'https://via.placeholder.com/64/333/fff?text=APP';
			} else {
				$image  	= $app['img'] ?? 'https://via.placeholder.com/64/333/fff?text=APP';
			}
			?>
			 
			<div class="col-12 col-md-6 mb-4">
			<span class="position-relative archive-post--remove app-container">
			 
			<div class="flex-shrink-0" style="position:relative;">
			<img src="<?= $image ?>" 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;">
			<?= $counter++ ?>
			</span>
			</div>

			<div class="app-info">
			<h3 class="h5 font-weight-semibold w-100 app-title"><?= $app['title'] ?></h3>	

			<div class="text-truncate text-muted app-desc">
			<span class="clamp-1 w-100">
			<?= $app['versi'] ?>
			</span>			
			</div>
			</div>

			<div class="app-get">
			<form method="POST" target="_blank">
			<input style="display:none" type="text" name="wp_url" value="<?= $app['link'] ?>">
			<input type="submit" id="submit" name="wp_sb" class="get-button" value="<?php echo postnow; ?>" />
			</form>
			</div>

			</span>
			</div>	

			<?php endforeach; ?>

			</div>
			</section>	
			<?php endif; ?>

		</div>

		<div id="tab3" class="tab-pane fade">
			
			<div class="play_menu" style="text-transform:uppercase"><b>Latest Games </b></div>	
		 
	<section>
	<div class="row">	
	<?php  	 
	// Fungsi untuk fetch HTML via proxy scrape.do (rotating proxy anti-block)
function scrapedo21($url) {
    // Ganti dengan API token/key scrape.do milikmu
    // Daftar di https://scrape.do/ untuk mendapatkan token (biasanya disebut "token")
    $apikey = "2ee8833b5f8f4e2d8e5ece5da8e04ac51e2f1659ce6"; // <<< WAJIB ISI !!!
    
    if (empty($apikey) || $apikey === "YOUR_SCRAPE_DO_TOKEN_HERE") {
        die("Error: Masukkan token scrape.do di variabel \$apikey");
    }
    
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADER         => false,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0,
        CURLOPT_CUSTOMREQUEST  => 'GET',
        CURLOPT_PROXY          => "http://{$apikey}:@proxy.scrape.do:8080",
        CURLOPT_HTTPHEADER     => [
            "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36"
        ],
        CURLOPT_TIMEOUT        => 60
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    
    if ($err) {
        die("cURL Error: " . $err);
    }
    
    return $response;
}

// Pagination
$paged = isset($_GET['games']) ? max(1, (int)$_GET['games']) : 1;
$base_url = ($paged > 1) ? "https://an1.com/games/page/{$paged}/" : "https://an1.com/games/";

// Fetch HTML
$html = scrapedo($base_url);

if (!$html || strlen($html) < 1000) {
    die("Gagal mengambil konten atau halaman diblokir. Cek token scrape.do atau coba lagi nanti.");
}

// Ekstrak judul game dengan regex yang lebih akurat & updated (per Januari 2026)
$judul = [];

preg_match_all('/<a\s+href="https:\/\/an1\.com\/\d+-[^"]+\.html"[^>]*>(.+?)<\/a>/i', $html, $matches);

if (!empty($matches[1])) {
    foreach ($matches[1] as $title) {
        $title = html_entity_decode(trim(strip_tags($title)), ENT_QUOTES, 'UTF-8');
        if (!empty($title)) {
            $judul[] = $title;
        }
    }
}

// Fallback jika regex di atas tidak match (struktur berubah lagi)
if (empty($judul)) {
    preg_match_all('/<h[1-3][^>]*class=["\']title["\'][^>]*>\s*<a[^>]*>(.+?)<\/a>\s*<\/h[1-3]>/i', $html, $matches2);
    if (!empty($matches2[1])) {
        foreach ($matches2[1] as $title) {
            $title = html_entity_decode(trim(strip_tags($title)), ENT_QUOTES, 'UTF-8');
            $judul[] = $title;
        }
    }
}

// Output
echo "<pre>";
print_r($judul);
echo "</pre>";

echo "<p><strong>Total game ditemukan di halaman {$paged}: " . count($judul) . "</strong></p>";
echo "<p>URL: <a href=\"{$base_url}\" target=\"_blank\">{$base_url}</a></p>";

	$links	= match_all('/<a.*?href="(.*?)\".*?>/ms', matchx('/<div class="ap-loop-wrap">(.*?)<nav id="ap-pagination">/ms', $html, 1), 1);
	 
	$img	= match_all('/<img.*?src="(.*?)".*?>/ms', matchx('/<div class="ap-loop-wrap">(.*?)<nav id="ap-pagination">/ms', $html, 1), 1);
	 	
	$mods	= match_all('/<div class="entry-excerpt">(.*?)<\/div>/ms', matchx('/<div class="ap-loop-wrap">(.*?)<nav id="ap-pagination">/ms', $html, 1), 1);
	
	
	$count	= count($judul);
	for ($i = 0; $i < $count; $i++) {   
	?>	
	 
	<div class="col-12 col-md-6 mb-4">
	<span class="position-relative archive-post--remove app-container">
	<?php 	 
	$path	=$img[$i];
	$type 	= pathinfo($path, PATHINFO_EXTENSION);
	$data 	= file_get_contents($path);
	$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);  
	?>
	<div class="flex-shrink-0">
	<img src="<?php echo $base64; ?>" class="app-logo " width="64" height="64"> 
	</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" target="_blank">
	<input style="display:none" type="text" name="wp_url" value="<?php echo $links[$i]; ?>">
	<input type="submit" id="submit" name="wp_sb" class="get-button" value="<?php echo postnow; ?>" />
	</form>
	</div>
	 
	</span>
	</div>	
    	 
	<?php } ?> 
	 
	
	
	</div>
	</section>

 
		</div> 

		<div id="tab4" class="tab-pane fade">
			<div class="play_menu" style="text-transform:uppercase"><b>Latest Apps </b></div>		
 
		</div> 
		
		<div id="tab5" class="tab-pane fade">
			<div class="play_menu" style="text-transform:uppercase" ><i class="fa fa-pencil-square-o" aria-hidden="true"></i>&nbsp;<b>Paste your link post here</b></div>

			<div class="play_menu" >		 
			<form name="myForm" id="myForm" method="POST" CLASS='f'>
			<input type="text" name="wp_url" placeholder="example : <?php echo $demos; ?>"  >
			<input type="submit" id="Submit" name="wp_sb" value="<?php echo postnow; ?>" />
			</form>
			</div> 
			
			<div class="play_menu" style="text-transform:uppercase"><b>Add manual</b></div>

			<div class="play_menu" style="text-transform:uppercase">
			<ol style="paddiing-right: 20px !important;margin: 20px;">
			<li>Open website <a style="color:var(--color_link_h)!important;font-weight: 700;" href="https://<?php echo parse_url($demos)['host']; ?>" target="_blank"><?php echo parse_url($demos)['host']; ?></a></li>
			<li>Copy link post and paste to form</li>
			<li>use the url into this format:  <strong style="color:var(--color_link_h)!important;font-weight: 700;text-transform:lowercase!important"><?php echo $demos; ?></strong> </li>
			</ol>		
			</div>
		
		</div>
		
		<?php if(isset($_POST['wp_sb'])) { ?>
		<div id="tab6" class="tab-pane fade in active"> 		
		<?php require_once get_template_directory().'/libs/addons/includes/debug.php'; ?>
		</div>
		<?php } ?>
		
		</div>
    </div>
	
<?php 
echo do_shortcode( '[ft_menu]' );
echo do_shortcode( '[ft_js]' ); 
}