<?php
/**
 * Plugin Name:       Google Play App Info (Nelexa) Pro
 * Description:       Fetch real-time Google Play app details with stunning animated UI + icon reveal
 * Version:           2.0.0
 * Author:            Your Name
 * License:           GPL-2.0+
 * Text Domain:       gplay-nelexa
 * Requires PHP:      7.4+
 */

if (!defined('ABSPATH')) exit;

define('GPLAY_NELEXA_PATH', get_template_directory().'/libs/addons/');
define('GPLAY_NELEXA_URL', plugin_dir_url(__FILE__));
require_once get_template_directory().'/libs/addons/vendor/autoload.php';

// Safe autoloader
if ( ! function_exists( 'gplay_nelexa_autoload' ) ) 
{
	function gplay_nelexa_autoload() 
	{	
		$file = GPLAY_NELEXA_PATH . 'vendor/autoload.php';
		if (file_exists($file)) {
			require_once $file;
			return true;
		}
		return false;
	}
}

// Admin notice if missing
add_action('admin_notices', function () {
    if (current_user_can('manage_options') && !gplay_nelexa_autoload() && (!empty($_GET['page']) && $_GET['page'] === 'gplay-nelexa')) {
        echo '<div class="notice notice-error"><p>
            <strong>Google Play App Info Pro:</strong> Library missing!<br>
            Run: <code>composer require nelexa/google-play-scraper</code> in plugin folder.
        </p></div>';
    }
});

// Menu
add_action('admin_menu', function () {
    add_menu_page(
        'Google Play App Info Pro',
        'Play Store Pro',
        'manage_options',
        'gplay-nelexa',
        'gplay_nelexa_page',
        'dashicons-google',
        82
    );
});
 
// AJAX Handler untuk Import Post

if ( ! function_exists( 'gplay_handle_import_post' ) ) 
{
	add_action('wp_ajax_gplay_import_post', 'gplay_handle_import_post');
	function gplay_handle_import_post() 
	{
		check_ajax_referer('gplay_import_nonce', 'nonce');

		if (!current_user_can('manage_options')) {
			wp_send_json_error(['message' => 'Permission denied.']);
		}

		$raw = stripslashes($_POST['app_data'] ?? '');
		$app_data = json_decode($raw, true);

		if (!$app_data || empty($app_data['id'])) {
			wp_send_json_error(['message' => 'Invalid app data.']);
		}
		// Tambah post_status dari data
		$post_status = in_array($app_data['post_status'], ['draft', 'publish' ]) 
			? $app_data['post_status'] 
			: 'draft';
			
		// Sanitasi semua data
		$package         = sanitize_text_field($app_data['id']);
		$playstore       = sanitize_text_field($app_data['playstore']);
		$title           = sanitize_text_field($app_data['name']);
		$appname         = sanitize_text_field($app_data['name']);
		$developer       = sanitize_text_field($app_data['developer']);
		$p_category      = sanitize_text_field($app_data['parent_category']);
		$category        = sanitize_text_field($app_data['category']);
		$os	             = sanitize_text_field($app_data['os']);
		$summary	     = wp_kses_post($app_data['summary']);
		$description     = wp_kses_post($app_data['description']);
		$recent_changes  = wp_kses_post($app_data['recent_changes'] ?? '');
		$icon_url        = esc_url_raw($app_data['icon']);
		$cover_url    	 = esc_url_raw($app_data['cover']);
		$screenshots     = array_filter(array_map('esc_url_raw', $app_data['screenshots'] ?? []));
		$version         = sanitize_text_field($app_data['version'] ?? 'Varies with device');
		$updated         = sanitize_text_field($app_data['updated'] ?? '');
		$installs        = sanitize_text_field($app_data['installs'] ?? '');
		$rating          = floatval($app_data['rating'] ?? 0);
		$ratings_count   = intval($app_data['ratings_count'] ?? 0);
		$price           = sanitize_text_field($app_data['price'] ?? 'Free');
		$contains_ads    = !empty($app_data['contains_ads']);

		// Cek apakah sudah pernah di-import (berdasarkan package name)
		$existing = get_posts([
			'post_type'      => 'post',
			'post_status'    => 'any',
			'meta_key'       => 'wp_GP_ID',
			'meta_value'     => $package,
			'posts_per_page' => 1,
			'fields'         => 'ids',
		]);

		if (!empty($existing)) {
			$edit_link = get_edit_post_link($existing[0], '');
			wp_send_json_error([
				'message' => "This app has been previously imported. <a href='$edit_link' target='_blank'>Edit existing posts</a>"
			]);
		}

		// Buat post draft baru
		$post_id = wp_insert_post([
			'post_title'   	=> $title,
			'post_content' 	=> $description,
			'post_status'	=> $post_status, 
			'post_type'    	=> 'post',
			'post_author'  	=> get_current_user_id(),
		]);

		if (is_wp_error($post_id)) {
			wp_send_json_error(['message' => 'Failed to create new post.']);
		}

		// Upload icon sebagai featured image
		/* if ($icon_url) {
			$icon_id = gplay_upload_image_from_url($icon_url, $post_id, $title . ' - App Icon');
			if ($icon_id) {
				set_post_thumbnail($post_id, $icon_id);
			}
		} */

		if ( !empty($icon_url) ) { 
			$image_url		= $icon_url;
			$image			= $icon_url;
			//$title_image	= sanitize_title($gets_data['title_GP']);
			//$title_image	= sanitize_title_with_dashes(ex_themes_clean($gets_data['GP_ID']));
			//$title		= $title_image.'-'.$post_id;
			
			$title_image	= sanitize_title_with_dashes_and_no_special_chars($title);
			//$title_image2	= sanitize_title_with_dashes($gets_data['title_GP']); 
			$title			= $post_id.'-'.$title_image;
					
			$uploaddir		= wp_upload_dir();
			$filename		= "{$title}.webp"; 
			$uploadfile		= $uploaddir['path'] . '/' . $filename;
			$contents		= file_get_contents($image);
			$savefile		= fopen($uploadfile, 'w');
			fwrite($savefile, $contents);
			fclose($savefile);
			$wp_filetype	= wp_check_filetype(basename($filename), null );
			$attachment		= array(
				'post_mime_type'	=> $wp_filetype['type'],
				'post_title'		=> $filename,
				'post_content'		=> '',
				'post_status'		=> 'inherit'
			);
			$attach_id		= wp_insert_attachment( $attachment, $uploadfile );
			require_once(ABSPATH . 'wp-admin/includes/image.php');
			$attach_data	= wp_generate_attachment_metadata( $attach_id, $uploadfile );
			wp_update_attachment_metadata( $attach_id, $attach_data );
			set_post_thumbnail( $post_id, $attach_id );
			$image_url = wp_get_attachment_url( $attach_id );
			
			update_post_meta( $post_id, 'wp_poster_GP', $icon_url ); 
		}
		
			
		if ( !empty($cover_url) ) { 
			$image_bg		= $cover_url;
			//$title_image	= sanitize_title_with_dashes(ex_themes_clean($gets_data['GP_ID']));
			//$title			= $title_image.'-'.$post_id; 
			$title_bg		= sanitize_title_with_dashes_and_no_special_chars($title); 
			$title_bg		= $post_id.'-'.$title_bg;
			$uploaddir		= wp_upload_dir();
			$filename_bg	= "{$title_bg}-bg.webp";
			$uploadfile_bg	= $uploaddir['path'] . '/' . $filename_bg;
			$contents_bg	= file_get_contents($image_bg);
			$savefile_bg	= fopen($uploadfile_bg, 'w');
			fwrite($savefile_bg, $contents_bg);
			fclose($savefile_bg);
			$wp_filetype_bg	= wp_check_filetype(basename($filename_bg), null );
			$attachment_bg	= array(
				'post_mime_type'	=> $wp_filetype_bg['type'],
				'post_title'		=> $filename_bg,
				'post_content'		=> '',
				'post_status'		=> 'inherit'
			);
			$attach_id_bg	= wp_insert_attachment( $attachment_bg, $uploadfile_bg );
			require_once(ABSPATH . 'wp-admin/includes/image.php');
			$attach_data_bg	= wp_generate_attachment_metadata( $attach_id_bg, $uploadfile_bg );
			wp_update_attachment_metadata( $attach_id_bg, $attach_data_bg ); 
			update_post_meta( $post_id, '_background_image_id', $attach_id_bg );
			update_post_meta( $post_id, 'background_images', $attach_id_bg );
			$image_bg_url = wp_get_attachment_url( $attach_id_bg );
			update_post_meta( $post_id, 'wp_backgrounds_GP', $cover_url );
		}

		
		if (!empty($screenshots) && is_array($screenshots)) {
			// Batasi maksimal 5 screenshot pertama
			$limited_screenshots = array_slice((array)$screenshots, 0, 5);

			// Struktur gallery_data yang konsisten
			$gallery_image = [
				'image_url' => array_values($limited_screenshots) // re-index agar bersih
			];

			update_post_meta($post_id, 'gallery_data', $gallery_image);
		}
		 
		// Simpan semua metadata
		update_post_meta( $post_id, 'wp_GP_ID', $package);
		update_post_meta( $post_id, 'wp_playstore_link', $playstore);
		update_post_meta( $post_id, 'wp_title_GP', $appname);
		update_post_meta( $post_id, 'wp_developers_GP', $developer);
		update_post_meta( $post_id, 'wp_version_GP', $version);
		update_post_meta( $post_id, 'wp_updates_GP', $updated);
		update_post_meta( $post_id, 'wp_installs_GP', $installs);
		update_post_meta( $post_id, 'wp_rated_GP', $rating);
		update_post_meta( $post_id, 'wp_ratings_GP', $ratings_count); 
		update_post_meta( $post_id, 'wp_whatnews_GP', $recent_changes); 
		update_post_meta( $post_id, 'wp_desck_GP', $summary );
		update_post_meta( $post_id, 'wp_requires_GP', $os );
		
		wp_set_post_terms( $post_id, str_replace(array('.', ',' ), ' ', $developer), 'developer' );
		wp_set_object_terms( $post_id, str_replace(array('.', ',' ), ' ', $developer), 'developer', true ); 
	 
		// Optional: kategori & tag
			
		$parent_cat_name 	= $p_category;
		$child_cat_name 	= $category;
		$parent_cat_slug 	= $parent_cat_name;
		$child_cat_slug 	= $child_cat_name;


		$parent_category = get_term_by("slug", $parent_cat_slug, "category");

		if ($parent_category) {
			$categories['parent_id'] = $parent_category->term_id;  
		} else {
			$parent_id = wp_insert_term($parent_cat_name, "category", ['slug' => $parent_cat_slug]);
			if (!is_wp_error($parent_id)) {
			$categories['parent_id'] = $parent_id["term_id"];
			}
		}
		wp_set_object_terms( $post_id, array( $categories['parent_id'] ), 'category', true );

		$child_category = get_term_by("slug", $child_cat_slug, "category");

		if ($child_category) {
			$categories['child_id'] = $child_category->term_id;
		} else {
			$child_id = wp_insert_term($child_cat_name, "category", ["parent" => $categories['parent_id'], "slug" => $child_cat_slug]);

			if (!is_wp_error($child_id)) {
			$categories['child_id'] = $child_id["term_id"];
			}
		}
		wp_set_object_terms( $post_id, array( $categories['child_id'] ), 'category', false );


		//wp_set_post_terms($post_id, ['Android Apps'], 'category', true);
		//wp_set_post_terms($post_id, ['android', 'mobile-app', 'google-play'], 'post_tag', true);

		// Kirim link edit post untuk redirect
		wp_send_json_success([
			'edit_link' => get_edit_post_link($post_id, ''),
		]);
	}
}
 

if ( ! function_exists( 'gplay_nelexa_page' ) ) 
{
	function gplay_nelexa_page() 
	{
		if (!current_user_can('manage_options')) {
			wp_die(esc_html__('You do not have permission to access this page.', 'text-domain'));
		}

		$app_info = null;
		$error = null;

		if (isset($_POST['nonce']) && wp_verify_nonce($_POST['nonce'], 'gplay_fetch')) {
			$package = trim(sanitize_text_field($_POST['package'] ?? ''));
			$locale = sanitize_text_field($_POST['lang'] ?? 'en_US');
			$country = sanitize_text_field($_POST['country'] ?? 'us');
			$post_status = sanitize_text_field($_POST['post_status'] ?? 'draft'); // ambil dari form

			if ($package) {
				$result = gplay_nelexa_get_app($package, $locale, $country);
				$app_info = is_object($result) ? $result : null;
				$error = is_string($result) ? $result : null;
			} else {
				$error = 'Package name required.';
			}
		}
		?>
		<div class="wrap">
			<h1>Google Play App Info <span style="font-size:16px;color:#666;">Pro v2.0</span></h1>

			<!-- Cinematic Progress UI -->
			<div id="gplay-progress" style="display:none;position:fixed;inset:0;background:linear-gradient(135deg,#0f0c29,#302b63,#24243e);z-index:99999;color:#fff;overflow:hidden;">
				<div style="position:absolute;inset:0;opacity:0.15;background:radial-gradient(circle at 20% 80%,#00ff88,transparent 50%),radial-gradient(circle at 80% 20%,#00ffff,transparent 50%);"></div>
				<div style="position:relative;z-index:2;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;">
					<div id="gplay-icon-box" style="width:120px;height:120px;background:#ffffff18;border-radius:28px;backdrop-filter:blur(10px);margin-bottom:40px;display:flex;align-items:center;justify-content:center;overflow:hidden;">
						<div class="spinner"></div>
					</div>
					<div id="gplay-text" style="font-size:24px;font-weight:600;margin-bottom:20px;text-shadow:0 2px 10px #000;">Connecting to Google Play...</div>
					<div style="width:520px;max-width:90vw;height:18px;background:#ffffff18;border-radius:50px;overflow:hidden;box-shadow:inset 0 4px 15px #0004;">
						<div id="gplay-fill" style="width:0%;height:100%;background:linear-gradient(90deg,#00c9ff,#92fe9d,#00c9ff);background-size:200%;border-radius:50px;animation:shimmer 4s infinite;box-shadow:0 0 30px rgba(0,201,255,0.6);transition:width .6s ease;"></div>
					</div>
					<div style="margin-top:18px;font-size:14px;opacity:0.8;" id="gplay-percent">0%</div>
				</div>
			</div>

			<style>
				@keyframes spin {to{transform:rotate(360deg)}}
				@keyframes shimmer {0%{background-position:-200%}100%{background-position:200%}}
				.spinner {width:80px;height:80px;border:6px solid #fff3;border-top-color:#00c9ff;border-radius:50%;animation:spin 1.2s cubic-bezier(0.4,0,0.2,1) infinite;}
				.gplay-card {background:#fff;padding:30px;border-radius:16px;box-shadow:0 10px 40px rgba(0,0,0,.12);margin:25px 0;max-width:720px;}
				.gplay-card input {font-size:15px;padding:12px;width:100%;max-width:420px;box-sizing:border-box;}
				img.screenshot {width:220px;margin:8px;border-radius:12px;box-shadow:0 8px 25px rgba(0,0,0,.15);transition:transform .2s;}
				img.screenshot:hover {transform:scale(1.05);}
				#import-btn {font-size:18px;padding:14px 32px;background:#1da1f2;color:white;border:none;border-radius:12px;cursor:pointer;box-shadow:0 6px 20px rgba(29,161,242,.3);transition:all .3s;}
				#import-btn:hover {transform:translateY(-2px);box-shadow:0 10px 30px rgba(29,161,242,.4);}
				#import-btn:disabled {opacity:0.6;cursor:not-allowed;transform:none;}
			</style>

			<form method="post" id="gplay-form" class="gplay-card">
				<?php wp_nonce_field('gplay_fetch', 'nonce'); ?>
				<table class="form-table">
					<tr>
						<th><label for="package">Package Name</label></th>
						<td>
							<input type="text" name="package" id="package" class="regular-text" required placeholder="com.whatsapp"
								   value="<?php echo esc_attr($_POST['package'] ?? ''); ?>">
							<p class="description">example: com.instagram.android • com.mojang.minecraftpe</p>
						</td>
					</tr>			
					<tr>
						<th><label for="lang">Language</label></th>
						<td><input type="text" name="lang" id="lang" value="<?php echo esc_attr($_POST['lang'] ?? 'en_US'); ?>" placeholder="en_US"></td>
					</tr>
					<tr>
						<th><label for="country">Country</label></th>
						<td><input type="text" name="country" id="country" value="<?php echo esc_attr($_POST['country'] ?? 'us'); ?>" placeholder="us"></td>
					</tr>
					<tr>
						<th><label for="post_status">Post Status</label></th>
						<td>
							<select name="post_status" id="post_status">
								<option value="draft" <?php selected($_POST['post_status'] ?? 'draft', 'draft'); ?>>Draft</option>
								<option value="publish" <?php selected($_POST['post_status'] ?? '', 'publish'); ?>>Publish</option> 
							</select>
							<p class="description">Status post saat di-import (default: Draft)</p>
						</td>
					</tr>
				</table>
				
				<?php submit_button('Fetch App Info', 'primary large'); ?>
			</form>

			<?php if ($error): ?>
				<div class="notice notice-error" style="padding:20px;font-size:16px;margin-top:20px;">
					<strong>Error:</strong> <?php echo esc_html($error); ?>
				</div>
			<?php endif; ?>
			

			<?php if ($app_info): ?>
				
			<?php
			if ($app_info->getCategory()) {
				// Ambil ID kategori (contoh: "GAME_ACTION", "PRODUCTIVITY", "GAME_CASUAL", dll)
				$category_id = $app_info->getCategory()->getId();

				// Simpan kategori mentah (dengan format asli dari Google Play)
				//$arr['parent_category'] = ucwords(strtolower(str_replace('_', ' ', $category_id)));

				// Tentukan parent category: Games atau Apps
				if (strpos($category_id, 'GAME_') === 0) {
					$p_category = 'Games';
				} else {
					$p_category = 'Apps';
				}
			}
			?>
				<script>
					// Success animation
					document.addEventListener('DOMContentLoaded', function() {
						const box = document.getElementById('gplay-icon-box');
						const fill = document.getElementById('gplay-fill');
						const text = document.getElementById('gplay-text');
						const percent = document.getElementById('gplay-percent');
						const progress = document.getElementById('gplay-progress');
						fill.style.width = '100%';
						percent.textContent = '100%';
						text.textContent = 'Success! Loaded <?php echo esc_js(addslashes($app_info->getName())); ?>';
						const img = new Image();
						img.onload = function() {
							box.innerHTML = `<img src="${this.src}" style="width:100%;height:100%;object-fit:cover;border-radius:24px;">`;
						};
						img.src = <?php echo wp_json_encode($app_info->getIcon()?->getUrl() ?: ''); ?>;
						setTimeout(() => {
							progress.style.opacity = '0';
							setTimeout(() => { progress.style.display = 'none'; }, 600);
						}, 1200);
					});
					// Fungsi Import dengan REDIRECT
					function gplayImportPost() {
						const status = document.getElementById('post_status')?.value || 'draft';
						if (!confirm(`Import this app as a WordPress Post (${status.charAt(0).toUpperCase() + status.slice(1)})?\n\n• Title: Nama app\n• Content: Description + What's New\n• Featured Image: Icon\n• Gallery: Screenshots\n• All technical data is stored as meta`)) {
							return;
						}
						const appData = {
							playstore: "https://play.google.com/store/apps/details?id=<?php echo esc_js($app_info->getId()); ?>",
							id: "<?php echo esc_js($app_info->getId()); ?>",
							name: "<?php echo esc_js($app_info->getName()); ?>",
							summary: "<?php echo esc_js($app_info->getSummary()); ?>",
							developer: "<?php echo esc_js($app_info->getDeveloperName()); ?>",
							parent_category: "<?php echo esc_js($p_category); ?>",
							category: "<?php echo esc_js($app_info->getCategory()->getName()); ?>",
							os: "<?php echo esc_js($app_info->getAndroidVersion()); ?>",
							description: <?php echo wp_json_encode($app_info->getDescription() ?: ''); ?>,
							recent_changes: <?php echo wp_json_encode($app_info->getRecentChanges() ?: ''); ?>,
							icon: "<?php echo esc_js($app_info->getIcon()?->getUrl() ?: ''); ?>",
							cover: "<?php echo esc_js($app_info->getCover()?->getUrl() ?: ''); ?>",
							screenshots: [
								<?php foreach ($app_info->getScreenshots() ?? [] as $ss): ?>
									"<?php echo esc_js($ss->getUrl()); ?>",
								<?php endforeach; ?>
							],
							version: "<?php echo esc_js($app_info->getAppVersion() ?: 'Varies with device'); ?>",
							updated: "<?php echo esc_js($app_info->getUpdated()?->format('d M Y') ?: ''); ?>",
							installs: "<?php echo esc_js($app_info->getInstalls()); ?>",
							rating: <?php echo number_format($app_info->getScore(), 1); ?>,
							ratings_count: <?php echo intval($app_info->getNumberVoters() ?: 0); ?>,
							price: "<?php echo $app_info->isFree() ? 'Free' : esc_js($app_info->getPrice() . ' ' . $app_info->getCurrency()); ?>",
							contains_ads: <?php echo $app_info->isContainsAds() ? 'true' : 'false'; ?>,
							post_status: status
						};
						const btn = document.getElementById('import-btn');
						const original = btn.innerHTML;
						btn.disabled = true;
						btn.innerHTML = 'Importing...';
						fetch(ajaxurl, {
							method: 'POST',
							headers: {'Content-Type': 'application/x-www-form-urlencoded'},
							body: new URLSearchParams({
								action: 'gplay_import_post',
								nonce: '<?php echo wp_create_nonce("gplay_import_nonce"); ?>',
								app_data: JSON.stringify(appData)
							})
						})
						.then(r => r.json())
						.then(res => {
							if (res.success) {
								window.location.href = res.data.edit_link;
							} else {
								alert('Error: ' + res.data.message);
								btn.disabled = false;
								btn.innerHTML = original;
							}
						})
						.catch(err => {
							alert('Request gagal: ' + err.message);
							btn.disabled = false;
							btn.innerHTML = original;
						});
					}
				</script>

				<!-- Tombol Import -->
				<div style="text-align:center;margin:40px 0;">
					<button type="button" id="import-btn" onclick="gplayImportPost()">
						Import as WordPress Post (<?php echo ucfirst($post_status); ?>)
					</button>
				</div>

				<h2 style="color:#1da1f2;font-size:28px;">
					<?php echo esc_html($app_info->getName()); ?>
					<small style="color:#666;font-size:16px;">by <?php echo esc_html($app_info->getDeveloperName()); ?></small>
				</h2>

				<table class="widefat fixed striped" style="font-size:15px;">
					<tr><th width="180">Package</th><td><?php echo esc_html($app_info->getId()); ?></td></tr>
					<tr><th>Version</th><td><?php echo esc_html($app_info->getAppVersion() ?: 'Varies'); ?></td></tr>
					<tr><th>developer</th><td><?php echo esc_html($app_info->getDeveloperName() ?: 'Varies'); ?></td></tr>
					<tr><th>os</th><td><?php echo esc_html($app_info->getAndroidVersion() ?: 'Unknow'); ?>
					<tr><th>parent category</th><td><?php echo esc_html($p_category); ?></td></tr>
					<tr><th>category</th><td><?php echo esc_html($app_info->getCategory()->getName()); ?></td></tr>
					<tr><th>Updated</th><td><?php echo $app_info->getUpdated()?->format('d M Y'); ?></td></tr>
					<tr><th>Installs</th><td><?php echo esc_html($app_info->getInstalls()); ?></td></tr>
					<tr><th>Rating</th><td><?php echo number_format($app_info->getScore(), 1); ?> / 5 (<?php echo number_format_i18n($app_info->getNumberVoters()); ?>)</td></tr>
					<tr><th>Price</th><td><?php echo $app_info->isFree() ? 'Free' : esc_html($app_info->getPrice() . ' ' . $app_info->getCurrency()); ?></td></tr>
					<tr><th>Contains Ads</th><td><?php echo $app_info->isContainsAds() ? 'Yes' : 'No'; ?></td></tr>
					<?php if ($icon = $app_info->getIcon()): ?>
					<tr><th>Icon</th><td><img src="<?php echo esc_url($icon->getUrl()); ?>" style="max-width:144px;border-radius:24px;"></td></tr>
					<?php endif; ?>
					<?php if ($screenshots = $app_info->getScreenshots()): ?>
					<tr>
						<th>Screenshots</th>
						<td style="padding:20px 0;">
							<?php foreach ($screenshots as $ss): ?>
								<img src="<?php echo esc_url($ss->getUrl()); ?>" class="screenshot" loading="lazy">
							<?php endforeach; ?>
						</td>
					</tr>
					<?php endif; ?>
					<?php if ($desc = $app_info->getDescription()): ?>
					<tr><th>Description</th><td><?php echo wp_kses_post(wpautop(make_clickable(esc_html($desc)))); ?></td></tr>
					<?php endif; ?>
					<?php if ($desc = $app_info->getRecentChanges()): ?>
					<tr><th>Recent Changes</th><td><?php echo wp_kses_post(nl2br($app_info->getRecentChanges())); ?></td></tr>
					<?php endif; ?>
					<?php if ($video = $app_info->getVideo()): ?>
					<tr><th>Video</th><td><?php echo esc_html($video); ?></td></tr>
					<?php endif; ?>
				</table>
			<?php endif; ?>
		</div>

		<script>
			// Animasi loading saat submit form fetch
			document.getElementById('gplay-form').addEventListener('submit', function() {
				const progress = document.getElementById('gplay-progress');
				const fill = document.getElementById('gplay-fill');
				const percent = document.getElementById('gplay-percent');
				const text = document.getElementById('gplay-text');

				progress.style.display = 'block';
				progress.style.opacity = '1';
				fill.style.width = '0%';
				percent.textContent = '0%';

				let p = 0;
				const messages = ["Connecting...", "Fetching details...", "Loading screenshots...", "Almost done..."];
				let i = 0;

				const timer = setInterval(() => {
					if (p < 92) {
						p += Math.random() * 5 + 2;
						if (p > 92) p = 92;
					}
					fill.style.width = p + '%';
					percent.textContent = Math.round(p) + '%';
					if (p > 30 && i < messages.length) {
						text.textContent = messages[i++];
					}
				}, 300);

				setTimeout(() => {
					clearInterval(timer);
					progress.style.opacity = '0';
					setTimeout(() => progress.style.display = 'none', 600);
				}, 45000);
			});
		</script>
		
		 <script>
		// Pure Vanilla JS - Auto extract package name dari URL Google Play
		document.addEventListener('DOMContentLoaded', function () {
			const packageInput = document.getElementById('package');

			if (!packageInput) return;

			// Fungsi untuk extract package name dari berbagai format URL
			function extractPackageName(value) {
				if (!value || typeof value !== 'string') return value;

				value = value.trim();

				// 1. Format standar: ?id=com.example.app
				const idMatch = value.match(/[?&]id=([a-zA-Z0-9._]+)/i);
				if (idMatch) {
					return idMatch[1];
				}

				// 2. Format short link: .../details/com.example.app
				const shortMatch = value.match(/play\.google\.com\/store\/apps\/details\/([a-zA-Z0-9._]+)/i);
				if (shortMatch) {
					return shortMatch[1];
				}

				// 3. Format lain yang kadang muncul: /store/apps/details?id=com.example.app&...
				const fallbackMatch = value.match(/details\/id\/([a-zA-Z0-9._]+)/i);
				if (fallbackMatch) {
					return fallbackMatch[1];
				}

				// Jika bukan URL Google Play, kembalikan nilai asli (bisa jadi user ketik manual)
				return value;
			}

			// Jalankan saat user mengetik atau mengedit
			packageInput.addEventListener('input', function (e) {
				const cleaned = extractPackageName(e.target.value);
				if (cleaned !== e.target.value) {
					e.target.value = cleaned;
				}
			});

			// Jalankan saat paste (karena paste tidak selalu trigger 'input' langsung)
			packageInput.addEventListener('paste', function () {
				setTimeout(() => {
					const cleaned = extractPackageName(packageInput.value);
					if (cleaned !== packageInput.value) {
						packageInput.value = cleaned;
					}
				}, 100);
			});

			// Optional: Validasi format package name (hanya huruf kecil, angka, titik, underscore)
			packageInput.addEventListener('blur', function () {
				const val = packageInput.value;
				if (val && !/^[a-z0-9._]+$/.test(val)) {
					packageInput.style.borderColor = '#d63638';
					// Bisa tambah pesan error jika mau
				} else {
					packageInput.style.borderColor = '';
				}
			});
		});
		</script>

<?php
	}
}

// Main Page
if ( ! function_exists( 'gplay_nelexa_page2' ) ) 
{
	function gplay_nelexa_page2() 
	{
		if (!current_user_can('manage_options')) wp_die('No permission');

		$app_info = $error = null;

		if (isset($_POST['nonce']) && wp_verify_nonce($_POST['nonce'], 'gplay_fetch')) {
			$package = sanitize_text_field($_POST['package'] ?? '');
			$locale  = sanitize_text_field($_POST['lang'] ?? 'en_US');
			$country = sanitize_text_field($_POST['country'] ?? 'us');

			if ($package) {
				$result = gplay_nelexa_get_app($package, $locale, $country);
				$app_info = is_object($result) ? $result : null;
				$error    = is_string($result) ? $result : null;
			} else {
				$error = 'Package name required.';
			}
		}
		?>
		<div class="wrap">
			<h1>Google Play App Info <span style="font-size:16px;color:#666;">Pro v2.0</span></h1>

			<!-- CINEMATIC PROGRESS UI -->
			<div id="gplay-progress" style="display:none;position:fixed;inset:0;background:linear-gradient(135deg,#0f0c29,#302b63,#24243e);z-index:99999;color:#fff;overflow:hidden;">
				<div style="position:absolute;inset:0;opacity:0.15;background:radial-gradient(circle at 20% 80%,#00ff88,transparent 50%),radial-gradient(circle at 80% 20%,#00ffff,transparent 50%);"></div>
				<div style="position:relative;z-index:2;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;">
					<div id="gplay-icon-box" style="width:120px;height:120px;background:#ffffff18;border-radius:28px;backdrop-filter:blur(10px);margin-bottom:40px;display:flex;align-items:center;justify-content:center;overflow:hidden;">
						<div class="spinner"></div>
					</div>
					<div id="gplay-text" style="font-size:24px;font-weight:600;margin-bottom:20px;text-shadow:0 2px 10px #000;">Connecting to Google Play...</div>
					<div style="width:520px;max-width:90vw;height:18px;background:#ffffff18;border-radius:50px;overflow:hidden;box-shadow:inset 0 4px 15px #0004;">
						<div id="gplay-fill" style="width:0%;height:100%;background:linear-gradient(90deg,#00c9ff,#92fe9d,#00c9ff);background-size:200%;border-radius:50px;animation:shimmer 4s infinite;box-shadow:0 0 30px rgba(0,201,255,0.6);transition:width .6s ease;"></div>
					</div>
					<div style="margin-top:18px;font-size:14px;opacity:0.8;" id="gplay-percent">0%</div>
				</div>
			</div>

			<style>
				@keyframes spin {to{transform:rotate(360deg)}}
				@keyframes shimmer {0%{background-position:-200%}100%{background-position:200%}}
				.spinner{width:80px;height:80px;border:6px solid #fff3;border-top-color:#00c9ff;border-radius:50%;animation:spin 1.2s cubic-bezier(0.4,0,0.2,1) infinite;}
				.gplay-card{background:#fff;padding:30px;border-radius:16px;box-shadow:0 10px 40px rgba(0,0,0,.12);margin:25px 0;max-width:720px;}
				.gplay-card input{font-size:15px;padding:12px;}
				img.screenshot{width:220px;margin:8px;border-radius:12px;box-shadow:0 8px 25px rgba(0,0,0,.15);transition:transform .2s;}
				img.screenshot:hover{transform:scale(1.05);}
			</style>

			<form method="post" id="gplay-form" class="gplay-card">
				<?php wp_nonce_field('gplay_fetch', 'nonce'); ?>
				<table class="form-table">
					<tr>
						<th><label>Package Name</label></th>
						<td>
							<input type="text" name="package" class="regular-text" required placeholder="com.whatsapp" value="<?php echo esc_attr($_POST['package'] ?? ''); ?>">
							<p class="description">Example: com.instagram.android • com.mojang.minecraftpe</p>
						</td>
					</tr>
					<tr><th>Language</th><td><input type="text" name="lang" value="<?php echo esc_attr($_POST['lang'] ?? 'en_US'); ?>" placeholder="en_US"></td></tr>
					<tr><th>Country</th><td><input type="text" name="country" value="<?php echo esc_attr($_POST['country'] ?? 'us'); ?>" placeholder="us"></td></tr>
				</table>
				<?php submit_button('Fetch App Info', 'primary large'); ?>
			</form>

			<?php if ($error): ?>
				<div class="notice notice-error" style="padding:20px;font-size:16px;margin-top:20px;">
					<strong>Error:</strong> <?php echo esc_html($error); ?>
				</div>
			<?php endif; ?>

			<?php if ($app_info): ?>
				<script>
					// SUCCESS: Reveal real icon + finish animation
					document.addEventListener('DOMContentLoaded', () => {
						const box = document.getElementById('gplay-icon-box');
						const fill = document.getElementById('gplay-fill');
						const text = document.getElementById('gplay-text');
						const percent = document.getElementById('gplay-percent');
						const progress = document.getElementById('gplay-progress');

						fill.style.width = '100%';
						percent.textContent = '100%';
						text.textContent = 'Success! Loaded <?php echo addslashes($app_info->getName()); ?>';

						const img = new Image();
						img.onload = () => {
							box.innerHTML = `<img src="${img.src}" style="width:100%;height:100%;object-fit:cover;border-radius:24px;">`;
						};
						img.src = <?php echo wp_json_encode($app_info->getIcon()?->getUrl() ?: ''); ?> || '<?php echo GPLAY_NELEXA_URL; ?>placeholder.png';

						setTimeout(() => {
							progress.style.opacity = '0';
							setTimeout(() => progress.style.display = 'none', 600);
						}, 1000);
					});
				</script>

				<!-- IMPORT BUTTON -->
				<div style="text-align:center;margin:40px 0;">
					<button type="button" id="import-btn" onclick="gplayImportPost()">
						Import as WordPress Post
					</button>
				</div>
				
				<h2 style="color:#1da1f2;font-size:28px;">
					<?php echo esc_html($app_info->getName()); ?>
					<small style="color:#666;font-size:16px;">by <?php echo esc_html($app_info->getDeveloperName()); ?></small>
				</h2>

				<table class="widefat fixed striped" style="font-size:15px;">
					<tr><th width="180">Package</th><td><code><?php echo esc_html($app_info->getId()); ?></code></td></tr>
					<tr><th>Version</th><td><?php echo esc_html($app_info->getAppVersion() ?: 'Varies'); ?></td></tr>
					<tr><th>Updated</th><td><?php echo $app_info->getUpdated()?->format('d M Y'); ?></td></tr>
					<tr><th>Installs</th><td><?php echo esc_html($app_info->getInstalls()); ?></td></tr>
					<tr><th>Rating</th><td><?php echo number_format($app_info->getScore(), 1); ?> / 5 (<?php echo number_format_i18n($app_info->getNumberVoters()); ?>)</td></tr>
					<tr><th>Price</th><td><?php echo $app_info->isFree() ? 'Free' : esc_html($app_info->getPrice() . ' ' . $app_info->getCurrency()); ?></td></tr>
					<tr><th>Contains Ads</th><td><?php echo $app_info->isContainsAds() ? 'Yes' : 'No'; ?></td></tr>
					<?php if ($icon = $app_info->getIcon()): ?>
					<tr><th>Icon</th><td><img src="<?php echo esc_url($icon->getUrl()); ?>" style="max-width:144px;border-radius:24px;"></td></tr>
					<?php endif; ?>
					<?php if ($screenshots = $app_info->getScreenshots()): ?>
					<tr>
						<th>Screenshots</th>
						<td style="padding:20px 0;">
							<?php foreach ($screenshots as $ss): ?>
								<img src="<?php echo esc_url($ss->getUrl()); ?>" class="screenshot" loading="lazy">
							<?php endforeach; ?>
						</td>
					</tr>
					<?php endif; ?>
					<?php if ($desc = $app_info->getDescription()): ?>
					<tr><th>Description</th><td><?php echo wp_kses_post(wpautop(make_clickable(esc_html($desc)))); ?></td></tr>
					<?php endif; ?>
					<?php if ($desc = $app_info->getRecentChanges()): ?>
					<tr><th>Recent Changes</th><td><?php echo wp_kses_post(nl2br($app_info->getRecentChanges())); ?></td></tr>
					<?php endif; ?>

					<?php if ($desc = $app_info->getVideo()): ?>
					<tr><th>Video</th><td><?php echo esc_html($app_info->getVideo()); ?></td></tr>
					<?php endif; ?>
						
				</table>
			<?php endif; ?>
		</div>

		<script>
		document.getElementById('gplay-form').onsubmit = function() {
			const progress = document.getElementById('gplay-progress');
			const fill = document.getElementById('gplay-fill');
			const percent = document.getElementById('gplay-percent');
			const text = document.getElementById('gplay-text');

			progress.style.display = 'block';
			progress.style.opacity = '1';
			fill.style.width = '0%';
			percent.textContent = '0%';

			let p = 0;
			const messages = ["Connecting...", "Fetching details...", "Loading screenshots...", "Almost done..."];
			let i = 0;

			const timer = setInterval(() => {
				if (p < 92) p += Math.random() * 5 + 2;
				fill.style.width = p + '%';
				percent.textContent = Math.round(p) + '%';
				if (p > 30 && i < messages.length) {
					text.textContent = messages[i++];
				}
			}, 300);

			setTimeout(() => clearInterval(timer), 40000);
		}; 
		
		</script>
		<?php
	}
}

// Core function with caching
if ( ! function_exists( 'gplay_nelexa_get_app' ) ) 
{
	function gplay_nelexa_get_app($package, $locale = 'en_US', $country = 'us') 
	{
		$key = 'gplay_' . md5("{$package}_{$locale}_{$country}");
		$cached = get_transient($key);
		if ($cached !== false) return $cached;

		if (!gplay_nelexa_autoload()) {
			return 'Nelexa library not installed.';
		}

		try {
			$gplay = (new \Nelexa\GPlay\GPlayApps())
				->setDefaultLocale($locale)
				->setDefaultCountry($country);

			$info = $gplay->getAppInfo($package);
			set_transient($key, $info, 6 * HOUR_IN_SECONDS);
			return $info;
		} catch (\Nelexa\GPlay\Exception\GooglePlayException $e) {
			$msg = $e->getCode() === 404 ? 'App not found.' : 'Google Play error: ' . $e->getMessage();
		} catch (Throwable $e) {
			$msg = 'Error: ' . $e->getMessage();
		}
		set_transient($key, $msg, 10 * MINUTE_IN_SECONDS);
		return $msg;
	}
}