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

function play5() {
/**
 * ===============================
 * 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 = '5play.org/en/';
$demos   = 'https://5play.org/en/11448-minecraft-mod.html';
$demosx  = 'https://' . parse_url($demos)['host'];

/**
 * ===============================
 * 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-5play';
?>

	<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/5play.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_5play();
		// === 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 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">    
			<?php echo $sc->render_post_status_info($opt_themes); ?>
		</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>		
			
			<?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://5play.org/en/android/games/page/{$paged}/"
				: "https://5play.org/en/android/games/";

			$result = $sc->Code_5play($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 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://5play.org/en/android/apps/page/{$paged}/"
				: "https://5play.org/en/android/apps/"; 
			
			$result = $sc->Code_5play($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_app']; //total_page_game or total_page_app
			$current_page	= $result['current'];
			if ($is_ajax) ob_start();			
			?>

			<section id="apps-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>
	
<?php 
echo do_shortcode( '[ft_menu]' );
echo do_shortcode( '[ft_js]' ); 
}