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


function wp_liteapks(){
/**
 * ===============================
 * 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        = 'liteapks.com';
$demos          = 'https://liteapks.com/roblox.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-liteapks';
?>
	
    
	<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/liteapks.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_Liteapks();
		// === 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 );
 
		// 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'])) echo 'in active'; ?>">
		<div class="play_menu" style="text-transform:uppercase"><b>Search</b></div>
		
		<center>
		<ul style="list-style:none; padding:0; margin:20px 0;">
			<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($error)) : ?>
			<p style="color:red; margin-bottom:10px;"><?php echo $error; ?></p>
			<?php endif; ?>
			
			<input type="text" name="search_query" placeholder="example: whatsapp" 
			   value="<?php echo isset($_POST['search_query']) ? htmlspecialchars($_POST['search_query']) : ''; ?>" 
			   required />
			<input type="submit" name="submit" value="Search" />
		</form>
		</center>

		<?php
		if (isset($_POST['submit'])) {
		// Validasi input
		if (empty(trim($_POST['search_query']))) {
			$error = "* Please enter a keyword to search";
		} else {
			$search_query = trim($_POST['search_query']);
			$search_url = 'https://liteapks.com/?s=' . urlencode($search_query);

			// Fetch HTML dengan handling Cloudflare
			$status_code = $Go_Curl->http_responsex($search_url);
			$allowed_statuses = [200, 201];

			if (in_array($status_code, [301, 302, 303, 307, 308, 403])) {
			$html = $Go_Curl->scrapedox($search_url);
			} elseif (in_array($status_code, $allowed_statuses)) {
			$html = $Go_Curl->scrape_sitex($search_url);
			} else {
			$html = $Go_Curl->scrape_sitex($search_url);
			}

			// Jika gagal fetch atau terdeteksi protection
			if (empty($html) || stripos($html, 'Cloudflare') !== false || stripos($html, 'Just a moment') !== false) {
			echo '<div class="text-center p-5"><h4>Temporary protection detected. Please try again in a few moments.</h4></div>';
			} else {
			// === EXTRACTION HASIL SEARCH ===
			$container_html = $Go_Curl->match('/<div class="row">(.*?)(?:<nav class=\'nav-pagination\'|<\/main>)/ms', $html, 1);

			if (empty($container_html)) {
				echo '<div class="text-center p-5"><h4>No results found for "<strong>' . htmlspecialchars($search_query) . '</strong>"</h4></div>';
			} else {
				// Judul
				$judul = $Go_Curl->match_all('/<h3 class="h6 font-weight-semibold[^>]*">(.*?)<\/h3>/ms', $container_html, 1);

				// Link detail
				$links = $Go_Curl->match_all('/<a.*?href="(https:\/\/liteapks\.com\/[^"]*\.html)".*?class="[^"]*archive-post/ms', $container_html, 1);

				// Gambar (prioritas 150x150)
				$img = $Go_Curl->match_all('/<img[^>]+src="(https:\/\/liteapks\.com\/wp-content\/uploads\/[^"]+-150x150\.[a-z]+)"[^>]+class="[^"]*wp-post-image/ms', $container_html, 1);

				// Version + Size
				$versi_raw = $Go_Curl->match_all('/<div class="small text-truncate text-muted">\s*<svg[^>]+viewBox="0 0 576 512"[^>]*>.*?<\/svg>\s*<span class="align-middle">([^<]+)<\/span>\s*<span class="align-middle">\s*\+\s*<\/span>\s*<span class="align-middle">([^<]+)<\/span>/ms', $container_html, 1);

				$versi = []; $size = [];
				foreach ($versi_raw as $v) {
				$versi[] = trim($v[1] ?? '');
				$size[]  = trim($v[2] ?? '');
				}

				// Mods (jika ada)
				$mods = $Go_Curl->match_all('/<div class="small text-truncate text-muted">\s*<svg[^>]+viewBox="0 0 512 512"[^>]*>.*?<\/svg>\s*<span class="align-middle">([^<]+)<\/span>/ms', $container_html, 1);
				$mods = array_map('trim', $mods);

				$count = count($judul);

				echo '<div class="play_menu" style="text-transform:uppercase"><b>Result for "' . htmlspecialchars($search_query) . '" (' . $count . ' found)</b></div>';
				echo '<section><div class="row">';

				if ($count == 0) {
				echo '<div class="col-12 text-center p-5">No results found.</div>';
				} else {
				for ($i = 0; $i < $count; $i++) {
				$title   = $judul[$i] ?? 'Unknown App';
				$link    = $links[$i] ?? '#';
				$image   = $img[$i] ?? 'https://via.placeholder.com/64';
				$version = $versi[$i] ?? '?';
				$ukuran  = $size[$i] ?? '?';
				$mod     = $mods[$i] ?? '';
				?>
				<div class="col-12 col-md-6 mb-4">
					<span class="position-relative archive-post--remove app-container d-flex align-items-center">
						<div class="flex-shrink-0">
						<img src="<?php echo htmlspecialchars($image); ?>" 
						 class="app-logo rounded" width="64" height="64" alt="<?php echo htmlspecialchars($title); ?>">
						</div>
						<div class="app-info flex-grow-1 ml-3">
						<h3 class="h5 font-weight-semibold w-100 app-title mb-1">
						<?php echo htmlspecialchars($title); ?>
						</h3>
						<div class="text-truncate text-muted small">
						v<?php echo htmlspecialchars($version); ?> + <?php echo htmlspecialchars($ukuran); ?>
						</div>
						<?php if (!empty($mod)) : ?>
						<div class="text-success small font-weight-medium mt-1">
							<?php echo htmlspecialchars($mod); ?>
						</div>
						<?php endif; ?>
						</div>
						<div class="app-get ml-3">
						<form method="POST" action="" target="_blank">
						<input type="hidden" name="wp_url" value="<?php echo htmlspecialchars($link); ?>">
						<input type="submit" name="wp_sb" class="get-button" value="GET">
						</form>
						</div>
					</span>
				</div>
				<?php
				}
				}
				echo '</div></section>';
			}
			}
		}
		
		// Tampilkan error jika ada
		if (isset($error)) {
			echo '<div class="text-center mt-4"><p style="color:red;">' . htmlspecialchars($error) . '</p></div>';
		}
		}
		?>
		</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://liteapks.com/games/page/{$paged}"
		: "https://liteapks.com/games";		
		
		$result = $sc->Code_Liteapks($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) {
				//print_r($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'],
				'mods'             	=> $item['mods'],
				'size'             	=> $item['size'],
				'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['games'] ?? 1));
		$is_ajax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
			   strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';

		$base_url 	= $paged > 1
		? "https://liteapks.com/apps/page/{$paged}"
		: "https://liteapks.com/apps";		
		
		$result = $sc->Code_Liteapks($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="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'],
				'mods'             	=> $item['mods'],
				'size'             	=> $item['size'],
				'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]' ); 
}