<?php

if (!function_exists('auto_submit_post')) 
{
	add_action('wp_ajax_auto_submit_post', 'auto_submit_post');

	function auto_submit_post() 
	{
		global $opt_themes;

		check_ajax_referer('auto_submit_post', 'nonce');

		$settings = get_option('auto_importer_settingss', [
			'source'   => '5play',
			'base_url' => 'https://5play.org/en/android/games/',
		]);
		
		if (!current_user_can('manage_options')) {
			wp_send_json_error(['message' => 'Hanya untuk Administrator']);
		}

		$url = isset($_POST['wp_url']) ? esc_url_raw(trim($_POST['wp_url'])) : '';
		if (empty($url) || !filter_var($url, FILTER_VALIDATE_URL)) {
			wp_send_json_error(['message' => 'URL tidak valid']);
		}

		
		if (($settings['source'] ?? '') === '5play') {
			
			if (strpos(parse_url($url, PHP_URL_HOST), '5play.org') === false) {
				wp_send_json_error(['message' => 'Only supports links from 5play.org']);
			}
			
		} elseif (($settings['source'] ?? '') === 'getmodsapk') {
			
			if (strpos(parse_url($url, PHP_URL_HOST), 'getmodsapk.com') === false) {
				wp_send_json_error(['message' => 'Only supports links from getmodsapk.com']);
			}
			
		} elseif (($settings['source'] ?? '') === 'apkmody') {
			
			if (strpos(parse_url($url, PHP_URL_HOST), 'apkmody.com') === false) {
				wp_send_json_error(['message' => 'Only supports links from getmodsapk.com']);
			}
			
		} elseif (($settings['source'] ?? '') === 'liteapks') {
			
			if (strpos(parse_url($url, PHP_URL_HOST), 'liteapks.com') === false) {
				wp_send_json_error(['message' => 'Only supports links from getmodsapk.com']);
			}
			
		} elseif (($settings['source'] ?? '') === 'custom') {
			
		}  

		try {
			// 1. Scraping detail game
			if (($settings['source'] ?? '') === '5play') { 
			
				require_once get_template_directory() . '/libs/addons/includes/class/5play.class.php';
				
			} elseif (($settings['source'] ?? '') === 'getmodsapk') {
				
				require_once get_template_directory().'/libs/addons/includes/class/getmodsapk.class.php'; 
				
			} elseif (($settings['source'] ?? '') === 'apkmody') {
				
				require_once get_template_directory().'/libs/addons/includes/class/apkmody.class.php'; 
				
			} elseif (($settings['source'] ?? '') === 'liteapks') {
				
				require_once get_template_directory().'/libs/addons/includes/class/liteapks.class.php'; 
				
			} elseif (($settings['source'] ?? '') === 'custom') {
				
			}
			
			$scraper = new scrapes();
			$data = $scraper->scrape_web_info($url, false);

			if (!$data || !empty($data['error'])) {
				wp_send_json_error([
					'message' => 'Scraping failed: ' . ($data['error'] ?? 'Unknown error')
				]);
			} 

			$importer = new APK_Importer($data); 

			$result = $importer->import();

			if (is_wp_error($result)) {
				if ($result->get_error_code() === 'duplicate_found') {
					$existing_id = $result->get_error_data()['post_id'] ?? 0;
					wp_send_json_error([
						'message'      => $result->get_error_message(),
						'is_duplicate' => true,
						'existing_id'  => $existing_id,
						'edit_link'    => $existing_id ? get_edit_post_link($existing_id, '') : '',
						'title'        => $existing_id ? get_the_title($existing_id) : ''
					]);
				}
				wp_send_json_error(['message' => $result->get_error_message()]);
			}

			$post_id = (int) $result;
			if ($post_id < 1) {
				wp_send_json_error(['message' => 'Failed to get valid post ID']);
			}
			
			if (($settings['source'] ?? '') === '5play') { 
				
				$importer->List_Download_5play();

			} elseif (($settings['source'] ?? '') === 'getmodsapk') {
				
				$importer->List_Download_Getmodsapk();

			} elseif (($settings['source'] ?? '') === 'apkmody') {
				
				$importer->List_Download_Apkmody();

			} elseif (($settings['source'] ?? '') === 'liteapks') {

				$importer->List_Download_Liteapks();

			} elseif (($settings['source'] ?? '') === 'custom') {
				
			}  

			$importer->add_direct_apk_download();

			wp_send_json_success([
				'post_id'   => $post_id,
				'title'     => get_the_title($post_id),
				'edit_link' => get_edit_post_link($post_id, ''),
				'message'   => 'Post successfully imported!'
			]);
			
		} catch (Exception $e) {
			wp_send_json_error(['message' => 'Unexpected error: ' . $e->getMessage()]);
		}
	}
}

if (!function_exists('auto_importer_default_sources')) 
{
	function auto_importer_default_sources() 
	{
		return [
			'5play'      => 'https://5play.org/en/android/games/',
			'getmodsapk' => 'https://getmodsapk.com/games/',
			'apkmody'    => 'https://apkmody.com/games',
			'liteapks'   => 'https://liteapks.com/games',
			'custom'     => '',
		];
	}
}

if (!function_exists('auto_importer_default_settings')) 
{
	function auto_importer_default_settings($source = '5play') 
	{
		$sources = auto_importer_default_sources();

		if (!isset($sources[$source])) {
			$source = '5play';
		}

		return [
			'source'   => $source,
			'base_url' => $sources[$source],
		];
	}
}

if (!function_exists('auto_importer_register_settings')) 
{
	function auto_importer_register_settings() 
	{
		register_setting(
			'auto_importer_groups',
			'auto_importer_settingss',
			[
				'sanitize_callback' => 'auto_importer_sanitize_settings'
			]
		);
	}
	add_action('admin_init', 'auto_importer_register_settings');
}

if (!function_exists('auto_importer_sanitize_settings')) 
{
	function auto_importer_sanitize_settings($input) 
	{

		$sources = auto_importer_default_sources();

		$source = isset($input['source'], $sources[$input['source']])
			? $input['source']
			: '5play';

		$base_url = !empty($input['base_url'])
			? esc_url_raw($input['base_url'])
			: $sources[$source];

		return [
			'source'   => $source,
			'base_url' => $base_url,
		];
	}
}

if (!function_exists('auto_importer_handle_reset_button')) 
{
	function auto_importer_handle_reset_button() 
	{
		if (
			isset($_POST['auto_importer_reset_settings']) &&
			check_admin_referer('auto_importer_reset_action', 'auto_importer_reset_nonce') &&
			current_user_can('manage_options')
		) {

			update_option(
				'auto_importer_settingss',
				auto_importer_default_settings()
			);

			wp_redirect(
				add_query_arg('ai_reset', 'success', wp_get_referer())
			);
			exit;
		}
	}
	add_action('admin_init', 'auto_importer_handle_reset_button');
}
 
if (!function_exists('auto_importer_emergency_reset_handler')) 
{
	function auto_importer_emergency_reset_handler() 
	{
		if (
			is_admin() &&
			current_user_can('manage_options') &&
			isset($_GET['ai_force_reset']) &&
			$_GET['ai_force_reset'] === '1'
		) {

			// Hapus settings
			delete_option('auto_importer_settingss');

			// Redirect balik ke halaman Auto Post + notice
			wp_safe_redirect(
				admin_url('admin.php?page=sc-auto-post&ai_reset=success')
			);
			exit;
		}
	}
	add_action('init', 'auto_importer_emergency_reset_handler');
}

if (!function_exists('auto_importer_admin_bar_reset')) 
{
	function auto_importer_admin_bar_reset($wp_admin_bar) 
	{
		if (!current_user_can('manage_options')) {
			return;
		}

		$wp_admin_bar->add_node([
			'id'    => 'ai_emergency_reset',
			'title' => '🚨 Reset Importer',
			'href'  => admin_url('admin.php?page=sc-auto-post&ai_force_reset=1'),
			'meta'  => [
				'title'   => 'Emergency reset importer settings',
				'onclick' => "return confirm('Reset importer settings to default?');",
			],
		]);
	}
	add_action('admin_bar_menu', 'auto_importer_admin_bar_reset', 999);
}

add_action('admin_post_ai_manual_submit', function () 
{
	if (
		! current_user_can('manage_options') ||
		! isset($_POST['ai_manual_nonce']) ||
		! wp_verify_nonce($_POST['ai_manual_nonce'], 'ai_manual_submit_action')
	) {
		wp_die('Unauthorized');
	}

	$url = esc_url_raw($_POST['wp_url'] ?? '');

	if (!$url) {
		wp_redirect(admin_url('admin.php?page=sc-auto-post&ai_manual=fail'));
		exit;
	}

	// 🔥 PANGGIL FUNCTION IMPORT UTAMA
	auto_submit_post($url);

	wp_redirect(admin_url('admin.php?page=sc-auto-post&ai_manual=success'));
	exit;
});

/**
 * Register Auto Importer Settings
 */
if (!function_exists('auto_importer_register_settings')) 
{
	function auto_importer_register_settings() 
	{

		register_setting(
			'auto_importer_groups',
			'auto_importer_settingss',
			[
				'sanitize_callback' => 'auto_importer_sanitize_settings',
			]
		);
	}
	add_action('admin_init', 'auto_importer_register_settings');
}

/**
 * Sanitize Auto Importer Settings
 */ 
if (!function_exists('auto_importer_sanitize_settings')) 
{
	function auto_importer_sanitize_settings($input) 
	{
		$allowed_sources = [
			'5play',
			'getmodsapk',
			'apkmody',
			'liteapks',
			'custom',
		];

		$source = isset($input['source'])
			? sanitize_text_field($input['source'])
			: '5play';

		$base_url = isset($input['base_url'])
			? esc_url_raw($input['base_url'])
			: '';

		return [
			'source'   => in_array($source, $allowed_sources, true) ? $source : '5play',
			'base_url' => $base_url,
		];
	}
} 
 
// =============================================
// HALAMAN ADMIN AUTO POST
// =============================================
if (!function_exists('auto_post_page')) 
{
	function auto_post_page() 
	{			
			
		$curl_file = get_template_directory() . '/libs/addons/inc/curls.php';
		$Go_Curl = new Go_Curl();
		$sc = new StructurCode();
		
		if (defined('DOING_AJAX') && DOING_AJAX) return;

		/* ================= FAILSAFE ================= */
		$failsafe = false;

		if (!file_exists($curl_file)) {
			$failsafe = true;
		} else {
			require_once $curl_file;
			if (!class_exists('Go_Curl')) {
				$failsafe = true;
			}
		}

		// FAIL SAFE — jika class tidak ada
		if (!class_exists('Go_Curl')) {
			echo '<div class="notice notice-error">
				<p><strong>Go_Curl class not found.</strong> Importer disabled.</p>
			</div>';
			return;
		}
		
		/* $Go_Curl 	= new Go_Curl();
		$sc 		= new StructurCode(); */
		
		if (!empty($_GET['ai_reset']) && $_GET['ai_reset'] === 'success') {
			echo '<div class="notice notice-success is-dismissible">
				<p><strong>Importer settings reset successfully.</strong></p>
			</div>';
		}

		if ($failsafe) {
			echo '<div class="notice notice-error">
				<p><strong>SAFE MODE ACTIVE</strong><br>
				Scraper error detected. Please reset settings.</p>
			</div>';
		}

		/* ================= SETTINGS ================= */
		$default_sources  = auto_importer_default_sources();
		$default_settings = auto_importer_default_settings();

		$settings = wp_parse_args(
			get_option('auto_importer_settingss', []),
			$default_settings
		);

		if (!isset($default_sources[$settings['source']])) {
			$settings['source'] = 'liteapks';
		}

		$expected_base = $default_sources[$settings['source']];

		if (
			empty($settings['base_url']) ||
			strpos($settings['base_url'], parse_url($expected_base, PHP_URL_HOST)) === false
		) {
			$settings['base_url'] = $expected_base;
		}
	 
		// FINAL URL
		$base_url = trailingslashit($settings['base_url']);

		if ($failsafe) return;
		/* ======= HTML FORM LANJUT DI SINI ======= */ 
		
		
		$Go_Curl 	= new Go_Curl();
		$sc 		= new StructurCode();
		 
		
		if (($settings['source'] ?? '') === '5play') {			
			
			//$result = $sc->Code_5play_Auto($base_url, $Go_Curl); 
			 
			$result = $sc->Code_5play_Auto($base_url, $Go_Curl);

			if ($result['status'] === 'error') {
				// sudah ditampilkan notice di dalam method
				return;
			}

			$items = $result['items'];
			$count = $result['count'];

		} elseif (($settings['source'] ?? '') === 'getmodsapk') {			
			
			$result = $sc->Code_Getmodsapk_Auto($base_url, $Go_Curl);
			
			if ($result['status'] === 'error') {
				// sudah ditampilkan notice di dalam method
				return;
			}

			$items = $result['items'];
			$count = $result['count'];

		} elseif (($settings['source'] ?? '') === 'apkmody') {
			
			$result = $sc->Code_Apkmody_Auto($base_url, $Go_Curl);
			
			if ($result['status'] === 'error') {
				// sudah ditampilkan notice di dalam method
				return;
			}

			$items = $result['items'];
			$count = $result['count'];

		} elseif (($settings['source'] ?? '') === 'liteapks') {
			 
			$result = $sc->Code_Liteapks_Auto($base_url, $Go_Curl);
			
			if ($result['status'] === 'error') {
				// sudah ditampilkan notice di dalam method
				return;
			}

			$items = $result['items'];
			$count = $result['count'];

		} elseif (($settings['source'] ?? '') === 'custom') {
			
		} else {
			
		}
	 
		wp_nonce_field('auto_submit_post', 'nonce');
		
		?> 
		
<div class="wrap">
	<h1 class="wp-heading-inline">Auto Importer</h1>
	<hr class="wp-header-end">

	<div class="two-col">

		<div class="settings-col col-1">
		
			<div class="postbox ai-settings-box">
				<h2 class="hndle ai-center-title"><span> 🚀 Importer Settings</span></h2>

				<div class="inside">
				
								 
				<!-- Pesan info yang akan di-toggle -->
				<p id="info_key" style="display: none; margin-top: 12px; padding: 12px 16px; background-color: #fff3cd; border: 1px solid #ffeeba; border-radius: 5px; color: #664d03; font-size: 0.95em;">
					<strong>Attention:</strong> For <strong>APKMODY</strong>, <strong>GETMODSAPK</strong>, and <strong>LITEAPKS</strong> sources, make sure you have entered a valid <strong>API Key</strong> or token in the settings so the import process runs smoothly without being blocked by cloudfkare.
				</p>

				
				<form method="post" action="options.php">
				<?php settings_fields('auto_importer_groups'); ?>

				<table class="form-table">
				<!-- SOURCE -->
				<tr>
				<th scope="row">Source</th>
				<td>
				<select name="auto_importer_settingss[source]" id="source-select">
				<?php foreach ($default_sources as $k => $v): ?>
				<option value="<?php echo esc_attr($k); ?>" <?php selected($settings['source'], $k); ?>>
				<?php echo strtoupper($k); ?>
				</option>
				<?php endforeach; ?>
				</select>
				</td>
				</tr>

				<!-- BASE URL -->
				<tr id="base_url">
				<th scope="row">URL Pages</th>
				<td>
				<input id="base_domain_url" type="url" name="auto_importer_settingss[base_url]" value="<?php echo esc_attr($settings['base_url']); ?>" class="regular-text code"  placeholder="https://example.com/path/" />
				</td>
				</tr>
				</table>
				

				<div class="ai-help-box fancy">
					<div class="ai-help-title">
						<strong>Examples for URL Pages</strong>
					</div>
					<p>Add Url <strong>Apps Page</strong> or <strong>Games Page</strong>, not <strong>Single Page</strong></p> 
					
					<ol id="info_5play">
						<li><code>https://5play.org/en/android/games/</code></li>
						<li><code>https://5play.org/en/android/games/page/2/</code></li>
						<li><code>https://5play.org/en/android/apps/</code></li>
						<li><code>https://5play.org/en/android/games/apps/2/</code></li>
					</ol>
	 
					<ol id="info_getmodsapk"> 
						<li><code>https://getmodsapk.com/games/</code></li>
						<li><code>https://getmodsapk.com/games/?page=2</code></li>
						<li><code>https://getmodsapk.com/apps/</code></li>
						<li><code>https://getmodsapk.com/apps/?page=2</code></li>
					</ol>
				
					<ol id="info_apkmody"> 
						<li><code>https://apkmody.com/games</code></li>
						<li><code>https://apkmody.com/games/page/2</code></li>
						<li><code>https://apkmody.com/apps</code></li>
						<li><code>https://apkmody.com/apps/page/2</code></li>
					</ol>
			
					<ol id="info_liteapks"> 
						<li><code>https://liteapks.com/games</code></li>
						<li><code>https://liteapks.com/games/page/2</code></li>
						<li><code>https://liteapks.com/apps</code></li>
						<li><code>https://liteapks.com/apps/page/2</code></li>
					</ol> 
				</div>
				<br />
			

				<div style="display:flex; gap:10px; align-items:center;">
				
				<button type="submit"
					name="submit"
					id="submit"
					class="button button-primary">
				Save Settings
				</button>

				</form>

				<form method="post" style="margin:0;">
				<?php wp_nonce_field('auto_importer_reset_action', 'auto_importer_reset_nonce'); ?>
				<input type="hidden" name="auto_importer_reset_settings" value="1">
				<button type="submit" class="button" onclick="return confirm('Reset importer settings to default?');"> Reset Settings </button>
				</form>
				
				</div>
				
				</div>
			</div>
			
		</div>

		<div class="settings-col col-2">	 
				
				<div class="ai-tabs-wrapper">

					<div class="ai-tabs-nav">
					
						<button class="ai-tab-btn active" data-tab="ai-tab-usage">
							📘 How to Use
						</button>
						<button class="ai-tab-btn" data-tab="ai-tab-reset">
							🔄 How to Reset
						</button>
						<button class="ai-tab-btn" data-tab="ai-tab-donasi">
							❤️ Donation
						</button>
						
					</div>

					<div class="ai-tabs-content">

						<!-- ================= TAB: HOW TO USE ================= -->
						<div id="ai-tab-usage" class="ai-tab-panel active">

							<div class="postbox ai-how-to-use"> 
				 
								<div class="ai-accordion">

									<div class="ai-acc-item">
										<button class="ai-acc-title">
											⚙️ Configure Importer Settings
											<span class="ai-acc-icon">+</span>
										</button>
										<div class="ai-acc-content">
											<p>
												Select the <strong>Source</strong> and enter the correct
												<strong>URL Pages</strong> Apps or Games, based on the examples provided.
												Click <strong>Save Settings</strong> before starting the import.
											</p>
										</div>
									</div>

									<div class="ai-acc-item">
										<button class="ai-acc-title">
											▶️ Start Import
											<span class="ai-acc-icon">+</span>
										</button>
										<div class="ai-acc-content">
											<p>
												Click <strong>Start Import</strong> to begin the automatic import process.
												Settings will be locked while the importer is running.
											</p>
										</div>
									</div>

									<div class="ai-acc-item">
										<button class="ai-acc-title">
											⏸️ Pause & ⛔ Stop Import
											<span class="ai-acc-icon">+</span>
										</button>
										<div class="ai-acc-content">
											<ul>
												<li><strong>Pause</strong> — temporarily pause the import</li>
												<li><strong>Stop</strong> — cancel the import completely</li>
											</ul>
										</div>
									</div>

									<div class="ai-acc-item">
										<button class="ai-acc-title">
											📊 Import Status
											<span class="ai-acc-icon">+</span>
										</button>
										<div class="ai-acc-content">
											<ul>
												<li><strong>Processing</strong> — item is being imported</li>
												<li><strong>Success</strong> — imported successfully</li>
												<li><strong>Already Imported</strong> — skipped automatically</li>
												<li><strong>Failed / Connection Error</strong> — import failed</li>
											</ul>
										</div>
									</div>

									<div class="ai-acc-item">
										<button class="ai-acc-title">
											⚠️ Manual Submit
											<span class="ai-acc-icon">+</span>
										</button>
										<div class="ai-acc-content">
											<p>
												If an item fails or encounters a connection error,
												a <strong>Submit Manual</strong> button will appear automatically.
												Use it to import the item manually.
											</p>
										</div>
									</div>

									<div class="ai-acc-item">
										<button class="ai-acc-title">
											🎉 Import Completed
											<span class="ai-acc-icon">+</span>
										</button>
										<div class="ai-acc-content">
											<p>
												Once all items are processed, the table will be hidden
												and the importer will reset automatically.
											</p>
										</div>
									</div>

								</div>

							
								<p class="ai-note" style="font-size: 13px;line-height: 1.5;margin: 10px 1em;">
									<em>Do not close or refresh the page while the import is running.</em>
								</p> 
							
							</div>
					
						</div>

						<!-- ================= TAB: RESET DOC ================= -->
						<div id="ai-tab-reset" class="ai-tab-panel">

							<div class="ai-accordion ai-reset-accordion">

								<div class="ai-acc-item">
									<button class="ai-acc-title">
										📘 Reset System Overview
										<span class="ai-acc-icon">+</span>
									</button>
									<div class="ai-acc-content">
										<p>
											This documentation explains how the <strong>Auto Importer Reset System</strong>
											works, including normal reset, emergency reset, and admin bar reset.
										</p>
									</div>
								</div>

								<div class="ai-acc-item">
									<button class="ai-acc-title">
										1️⃣ Normal Reset (Reset Settings Button)
										<span class="ai-acc-icon">+</span>
									</button>
									<div class="ai-acc-content">
										<p>
											Allows administrators to restore all Auto Importer settings to their default
											values using the <strong>Reset Settings</strong> button.
										</p>

										<ul>
											<li>Nonce validation for security</li>
											<li>Admin-only permission check</li>
											<li>Resets settings to default values</li>
											<li>Redirects back with success status</li>
										</ul>

										<p><strong>Trigger:</strong></p>
										<pre><code>POST: auto_importer_reset_settings
							Nonce: auto_importer_reset_nonce</code></pre>

										<p><strong>Handler:</strong></p>
										<pre><code>auto_importer_handle_reset_button()</code></pre>

										<div class="ai-doc-notice info">
											<strong>Security:</strong> Uses nonce verification and capability checks.
										</div>
									</div>
								</div>

								<div class="ai-acc-item">
									<button class="ai-acc-title">
										2️⃣ Emergency Reset (Force Reset)
										<span class="ai-acc-icon">+</span>
									</button>
									<div class="ai-acc-content">
										<p>
											Designed for critical situations such as corrupted settings,
											importer crashes, or broken admin UI.
										</p>

										<ul>
											<li>Deletes <code>auto_importer_settingss</code> option completely</li>
											<li>No form submission required</li>
											<li>Admin-only access</li>
										</ul>

										<p><strong>Trigger URL:</strong></p>
										<pre><code>/wp-admin/admin.php?page=sc-auto-post&amp;ai_force_reset=1</code></pre>

										<p><strong>Handler:</strong></p>
										<pre><code>auto_importer_emergency_reset_handler()</code></pre>

										<div class="ai-doc-notice warning">
											<strong>Warning:</strong> Use only when normal reset is not possible.
										</div>
									</div>
								</div>

								<div class="ai-acc-item">
									<button class="ai-acc-title">
										3️⃣ Admin Bar – Emergency Reset
										<span class="ai-acc-icon">+</span>
									</button>
									<div class="ai-acc-content">
										<p>
											Adds a quick <strong>🚨 Reset Importer</strong> shortcut to the WordPress Admin Bar.
										</p>

										<ul>
											<li>Visible only to administrators</li>
											<li>Confirmation dialog before reset</li>
											<li>Direct access to emergency reset</li>
										</ul>

										<p><strong>Handler:</strong></p>
										<pre><code>auto_importer_admin_bar_reset()</code></pre>
									</div>
								</div>

								<div class="ai-acc-item">
									<button class="ai-acc-title">
										4️⃣ Redirect & Best Practices
										<span class="ai-acc-icon">+</span>
									</button>
									<div class="ai-acc-content">
										<pre><code>admin.php?page=sc-auto-post&amp;ai_reset=success</code></pre>

										<ul>
											<li>Use <strong>Normal Reset</strong> for routine troubleshooting</li>
											<li>Use <strong>Emergency Reset</strong> only if the UI is broken</li>
											<li>Restrict reset access to administrators</li>
											<li>Do not expose emergency reset URLs publicly</li>
										</ul>
									</div>
								</div>

							</div>
							
						</div>				 

						<!-- ================= TAB: donasi ================= -->
						<div id="ai-tab-donasi" class="ai-tab-panel">

							<div class="ai-donation-box">
								<h3>❤️ Support This Theme</h3>

								<p>
									If this theme helps you save time and grow your website,
									please consider supporting development through a donation.
								</p>

								<ul>
									<li>☕ Help maintain updates</li>
									<li>🚀 Fund new features</li>
									<li>🛠 Faster bug fixes</li>
								</ul>

								<!-- PayPal -->
								<a href="https://paypal.me/exthemesdevs" target="_blank" class="ai-donate-btn">
									<img alt="PayPal" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz48c3ZnIGhlaWdodD0iNTEycHgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDUxMiA1MTI7IiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCA1MTIgNTEyIiB3aWR0aD0iNTEycHgiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxnIGlkPSJfeDMyXzUwLXBheXBhbCI+PGc+PHBhdGggZD0iTTI1MC41ODUsMjcxLjg3NGM2OC41NjYtMC44MTEsMTIwLjI5OS0yOC4wOTcsMTQyLjEwNi05MS41OTMgICAgYzIxLjkxMS02MS42NzEsMTYuMzMyLTExOC42NzYtNDQuNjMtMTQyLjMxMWMtMzkuNDU3LTE1LjMxNi01Mi40NDEtMTEuNTYzLTIwNi45MjMtMTEuNTYzYy0xMC4wNDIsMC0xOC43NjUsNy40MDUtMjAuMjg4LDE3LjE0MiAgICBMNjEuNDEyLDQyMC43NzhjLTEuMDE0LDcuNDA0LDQuNTY0LDE0LjA5OSwxMi4yNzIsMTQuMDk5aDc1LjY2OWMyLjAyOSwwLDIuNzM4LTAuNzA4LDMuMDQzLTIuNTM0ICAgIGM0LjE1OC0yNS42NjQsMTguMjU5LTExNi40NDcsMjEuODA4LTEzNS45MjJDMTgwLjA4OSwyNjQuNzc0LDIwNi41NjMsMjcyLjU4NiwyNTAuNTg1LDI3MS44NzR6IiBzdHlsZT0iZmlsbDojMDAyRDhBOyIvPjxwYXRoIGQ9Ik00MjMuNDI3LDE1MC40NmMtMS44MjYtMS4zMTktMi41MzYtMS44MjctMy4wNDMsMS4zMTdjLTIuMDI5LDExLjU2NS01LjE3MywyMi44MjMtOC45MjcsMzQuMDgzICAgIEMzNzAuOTg1LDMwMS4yOSwyNTguOCwyOTEuMjQ5LDIwNC4wMjYsMjkxLjI0OWMtNi4xODgsMC0xMC4yNDUsMy4zNDgtMTEuMDU3LDkuNTM0ICAgIGMtMjIuOTIzLDE0Mi40MTEtMjcuNDg4LDE3Mi4xMzEtMjcuNDg4LDE3Mi4xMzFjLTEuMDE1LDcuMjAyLDMuNTUsMTMuMDg1LDEwLjc1MiwxMy4wODVoNjQuNDFjOC43MjMsMCwxNS45MjUtNi4zOTEsMTcuNjUtMTUuMTEyICAgIGMwLjcwOS01LjQ3OS0xLjExNSw2LjE4NywxNC42MDYtOTIuNjA5YzQuNjY1LTIyLjMxNCwxNC41MDQtMTkuOTgsMjkuNzE5LTE5Ljk4YzcyLjAxOSwwLDEyOC4yMTEtMjkuMjE0LDE0NC45NDgtMTEzLjkxICAgIEM0NTQuMTYxLDIwOS4wODgsNDUyLjIzNCwxNzEuOTYzLDQyMy40MjcsMTUwLjQ2eiIgc3R5bGU9ImZpbGw6IzAxOUJFMTsiLz48L2c+PC9nPjxnIGlkPSJMYXllcl8xIi8+PC9zdmc+">
									Donate via PayPal
								</a>

								<hr>

								<!-- Bitcoin -->
								<div class="ai-crypto-box">
									<strong>₿ Donate via Bitcoin</strong>
									<textarea
										class="aps-textarea ai-autoheight"
										readonly
										onclick="this.select()"
										spellcheck="false">AK4yetqZNDYyQdLKZVHqRh9HpdxdAEhyy</textarea>
								</div>

								<!-- USDT -->
								<div class="ai-crypto-box">
									<strong>🪙 Donate via Tether (USDT – TRC20)</strong>
									<textarea
										class="aps-textarea ai-autoheight"
										readonly
										onclick="this.select()"
										spellcheck="false">TSP7i8XuRvbQQ5VfhDC2EwL8XMucvU4Qr1</textarea>
								</div>
								
								<!-- EthereumCoin -->
								<div class="ai-crypto-box">
									<strong>🪙 Donate via Ethereum (ERC-20 / ETH)</strong>
									<textarea
										class="aps-textarea ai-autoheight"
										readonly
										onclick="this.select()"
										spellcheck="false">0x94fcbd06a3f700898ba750fc942d726b86da1f5f</textarea>
								</div>

								<p class="ai-donate-note">
									<em>Thank you for your support ❤️</em>
								</p>
							</div>

						</div>
						
					</div>

			</div>


		</div>

	</div>

	<!-- Controls -->
	<div class="import-controls-wrapper">
	<div class="import-controls">
	<button id="btn-start" class="import-btn primary">
	<span class="dashicons dashicons-controls-play"></span>
	<span class="label">Start Import</span>
	</button>

	<button id="btn-pause" class="import-btn secondary" disabled>
	<span class="dashicons dashicons-controls-pause"></span>
	<span class="label">Pause</span>
	</button>

	<button id="btn-stop" class="import-btn danger" disabled>
	<span class="dashicons dashicons-no-alt"></span>
	<span class="label">Stop</span>
	</button>
	</div>
	</div>	


	<!-- Progress Bar (default disembunyikan) -->
	<div class="progress-container" id="progress-container">
	<div class="progress-header">
	<strong>Progress Import</strong>
	<span id="progress-text">0 / <?php echo $count; ?></span>
	</div>
	<div class="progress-bar-wrapper">
	<div id="progress-bar"></div>
	</div>
	<div id="current-game" style="margin-top:10px; min-height:22px;"></div>
	</div>
	
	<h2 style="/* display:flex; justify-content:center; */font-size: 1.1rem;">
	List <?php echo $count; ?> Post from &nbsp;<a href="<?php echo $settings['base_url']; ?>" target="_blank"><?php echo esc_html(parse_url($settings['base_url'])['host']); ?></a>
	</h2>
	 
	<table id="ai-import-table"  class="wp-list-table widefat fixed striped posts ai-import-table">
		<thead>
			<tr>
				<td class="manage-column column-cb check-column"></td>
				<th class="manage-column column-thumb">Image</th>
				<th class="manage-column column-title column-primary">Title</th>
				<th class="manage-column column-appid">App ID</th>
				<th class="manage-column column-source">Source</th>
				<th class="manage-column column-status">Status</th>
				<th class="manage-column column-action">Action</th>
			</tr>
		</thead>

		<tbody id="the-list">
		<?php 
		for ($i = 0; $i < $count; $i++): 
		//print_r($items);
		$item 		= $items[$i];
		$appId 		= $Go_Curl->get_playstore_id_by_title_google($item['title']);
		?>
			<tr class="ai-item" 
				data-url="<?= esc_url($item['url']) ?>" 
				data-index="<?php echo $i; ?>">

				<th class="check-column"></th>

				<!-- IMAGE -->
				<td class="thumb column-thumb">
					<div class="ai-thumb-wrap">
						<img src="<?= $appId ? $Go_Curl->getAppsPoster($appId) : $item['image'] ?>" 
							 alt="" />
					</div>
				</td>

				<!-- TITLE -->
				<td class="title column-title column-primary">
					<strong class="ai-item-title">
						<?= esc_html($item['title']) ?> <?= $item['versi'] ?>
					</strong>

					<div class="row-actions ai-row-meta">
						<span class="ai-index">#<?php echo $i + 1; ?></span>
						<span class="sep">•</span> 
						<span class="status-text">Wait</span>
					</div>
				</td>

				<!-- appId -->
				<td class="appId column-appid">
					<span class="ai-appid">
						<?= esc_html($appId) ?>
					</span>
				</td>

				<!-- SOURCE -->
				<td class="source column-source">
					<span class="ai-source">
						<a href="<?= esc_url($item['url']) ?>" target="_blank"><?php echo esc_html(parse_url($settings['base_url'])['host']); ?></a>
					</span>
				</td>

				<!-- STATUS -->
				<td class="status column-status">
					<span class="status-badge badge-waiting">Wait</span>
				</td>
				
				<!-- post_manual -->				
				<td class="appId column-appid">
					<form id="post_manual" action="<?php echo admin_url('admin.php?page=sc-'); ?><?php if ($settings['source'] === '5play'): ?>5play<?php elseif ($settings['source'] === 'getmodsapk'): ?>getmodsapk<?php elseif ($settings['source'] === 'apkmody'): ?>apkmody<?php elseif ($settings['source'] === 'liteapks'): ?>liteapks<?php endif; ?>" method="post" target="_blank" > 
					<input type="hidden" name="wp_url" value="<?= esc_url($item['url']) ?>" />
					<input type="submit" id="Submit" name="wp_sb" class="button-primary" value="⚠️ Submit Manual" />					
					</form> 
				</td>	
			</tr>
		<?php endfor; ?>
		</tbody>
	</table>
	 
	<div id="ai-import-complete" style="display:none; margin:40px 0; padding:40px; text-align:center; background:#f6fff8; border:2px dashed #46b450; border-radius:8px;">
		<h2 style="margin:0 0 10px;font-size:26px;">🎉 All items imported</h2>
		<p style="font-size:15px;color:#555;">
			All items were successfully processed.
		</p>
	</div>


</div>
		
 

	<?php
	}
}

if (!function_exists('add_style_to_sc_auto_post_page')) 
{
	add_action('admin_head', 'add_style_to_sc_auto_post_page');
	function add_style_to_sc_auto_post_page() 
	{
		if (isset($_GET['page']) && $_GET['page'] === 'sc-auto-post') {
		?>       
		<!-- CSS -->
	 
		<style>		
		.import-controls-wrapper.is-sticky {position: fixed;left: 50%;bottom: 24px;transform: translateX(-50%);z-index: 9999;background: none;padding: 12px 14px;border-radius: 10px;animation: slideUp .25s ease-out;}@keyframes slideUp {from {transform: translateX(-50%) translateY(20px);opacity: 0;}to {transform: translateX(-50%) translateY(0);opacity: 1;}}.import-controls #btn-pause, .import-controls #btn-stop {display: none;}.ai-help-box.fancy > ol {display: none;}.ai-import-running select[name="auto_importer_settingss[source]"], .ai-import-running input[name="auto_importer_settingss[base_url]"] {pointer-events: none;opacity: 0.6;}button.disabled {opacity: 0.55;cursor: not-allowed;}.progress-container {position: sticky;top: 32px;z-index: 1000;margin: 20px auto 30px;padding: 16px 18px;background: rgba(255, 255, 255, 0.92);border-radius: 12px;border: 1px solid #dcdcde;box-shadow: 0 6px 25px rgba(0,0,0,0.12), inset 0 1px 0 rgba(255,255,255,0.7);backdrop-filter: blur(10px);max-width: 1200px;display: none;opacity: 0;transform: translateY(-8px);transition: opacity .35s ease, transform .35s ease;}.progress-container.visible {display: block;opacity: 1;transform: translateY(0);}.progress-header {display: flex;justify-content: space-between;align-items: center;margin-bottom: 10px;font-size: 14px;font-weight: 600;color: #1d2327;}#progress-text {font-size: 13px;font-weight: 500;color: #50575e;}.progress-bar-wrapper {height: 30px;width: 100%;background: #e2e4e7;border-radius: 6px;overflow: hidden;box-shadow: inset 0 1px 2px rgba(0,0,0,0.08);}#progress-bar {height: 100%;width: 0%;border-radius: 6px;background: linear-gradient(90deg, #16a34a, #15803d);transition: width .45s ease;}#current-game {margin-top: 10px;min-height: 22px;font-size: 13px;color: #50575e;font-style: italic;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;}@media (max-width: 960px) {.progress-container {top: 0;border-radius: 0;margin: 0;padding: 12px 16px;}}.ai-import-table {border-radius: 12px;overflow: hidden;box-shadow: 0 10px 35px rgba(0,0,0,.08);}.ai-import-table thead th {background: #f6f7f7;font-weight: 600;padding: 14px 10px;}.ai-import-table td {vertical-align: middle;padding: 14px 10px;}.ai-thumb-wrap {width: 56px;height: 56px;border-radius: 8px;overflow: hidden;background: #f0f0f1;display: flex;align-items: center;justify-content: center;}.ai-thumb-wrap img {width: 100%;height: 100%;object-fit: cover;}.ai-item-title {font-size: 14px;line-height: 1.4;font-weight: 600;display: block;margin-bottom: 4px;}.ai-row-meta {font-size: 12px;color: #646970;}.ai-row-meta .sep {margin: 0 6px;}.ai-source {background: #eef2ff;color: #3730a3;padding: 4px 8px;border-radius: 999px;font-size: 12px;font-weight: 500;}.status-badge {display: inline-flex;align-items: center;gap: 6px;padding: 6px 12px;border-radius: 999px;font-size: 12px;font-weight: 600;}.badge-waiting {background: #f1f5f9;color: #475569;}.badge-processing {background: #fff7ed;color: #9a3412;}.badge-success {background: #ecfdf5;color: #065f46;}.badge-error {background: #fef2f2;color: #991b1b;}.badge-duplicate {background: #eff6ff;color: #1e40af;}tr.ai-item.processing {background: #fff8e1 !important;}tr.ai-item.success {background: #f0fdf4 !important;}tr.ai-item.error {background: #fef2f2 !important;}@media (max-width: 782px) {.ai-import-table thead {display: none;}.ai-import-table tr.ai-item {display: block;padding: 12px;border-bottom: 1px solid #e5e7eb;}.ai-import-table td.column-thumb, .ai-import-table td.column-title {display: inline-flex;vertical-align: top;border: none;}.ai-import-table td.column-thumb {width: 70px;margin-right: 12px;}.ai-import-table td.column-title {width: calc(100% - 82px);flex-direction: column;}.ai-thumb-wrap {width: 60px;height: 60px;flex-shrink: 0;}.ai-item-title {font-size: 14px;font-weight: 600;line-height: 1.4;margin-bottom: 4px;display: -webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;overflow: hidden;word-break: break-word;}.ai-row-meta {display: block !important;font-size: 12px;color: #6b7280;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;}.ai-import-table td.column-source, .ai-import-table td.column-status, .ai-import-table th {display: none !important;}}.import-controls-wrapper {display: flex;justify-content: center;margin: 20px 0 25px;}.import-controls {display: flex;gap: 10px;background: #fff;padding: 8px 14px;border-radius: 10px;border: 1px solid #dcdcde;box-shadow: 0 2px 10px rgba(0,0,0,0.08);}.import-btn {display: inline-flex;align-items: center;gap: 6px;padding: 8px 16px;font-size: 13px;font-weight: 500;border-radius: 6px;border: none;cursor: pointer;transition: all 0.18s ease;}.import-btn:hover:not(:disabled) {filter: brightness(1.08);transform: translateY(-1px);}.import-btn:disabled {opacity: 0.45;cursor: not-allowed;}.import-btn.primary {background: #2271b1;color: #fff;}.import-btn.secondary {background: #f0f0f1;color: #1d2327;border: 1px solid #c3c4c7;}.import-btn.danger {background: #d63638;color: #fff;}@media (max-width: 782px) {.import-controls {flex-wrap: wrap;justify-content: center;}.import-btn {flex: 1 1 auto;min-width: 120px;justify-content: center;}}.ai-donation-box {background: #fff;border: 1px solid #ddd;border-radius: 8px;padding: 16px;}.ai-donate-btn {display: inline-flex;align-items: center;gap: 8px;margin: 10px 0;padding: 10px 14px;background: #ffc439;color: #111;font-weight: 600;border-radius: 6px;text-decoration: none;}.ai-donate-btn img {height: 20px;}.ai-crypto-box {margin-top: 14px;padding: 12px;background: #f6f7f7;border: 1px dashed #ccd0d4;border-radius: 6px;}.aps-textarea {width: 100%;resize: none;font-family: monospace;font-size: 13px;padding: 8px;border-radius: 4px;cursor: pointer;}.ai-tabs-nav {display: flex;border-bottom: 1px solid #ddd;margin-bottom: 16px;}.ai-tab-btn {background: #f1f1f1;border: 1px solid #ddd;border-bottom: none;padding: 10px 16px;cursor: pointer;font-weight: 600;margin-right: 6px;border-radius: 6px 6px 0 0;}.ai-tab-btn.active {background: #fff;border-bottom: 1px solid #fff;}.ai-tab-panel {display: none;}.ai-tab-panel.active {display: block;}.two-col {display: flex;gap: 12px;}.col-1 {order: 1;}.col-2 {order: 2;}@media (max-width: 768px) {.two-col {flex-direction: column;}.col-2 {order: 1;}.col-1 {order: 2;}}.settings-col {flex: 1;background: #f6f7f7;padding: 12px;border: 1px solid #ddd;border-radius: 6px;}.ai-help-box.fancy {margin-top: 12px;padding: 14px 16px;background: linear-gradient(135deg, #f6f7f7, #ffffff);border: 1px solid #dcdcde;border-left: 4px solid #2271b1;border-radius: 6px;box-shadow: 0 4px 14px rgba(0,0,0,.05);}.ai-help-title {display: flex;align-items: center;gap: 6px;font-size: 13px;margin-bottom: 8px;color: #1d2327;}.ai-help-box ol {margin: 0;padding-left: 20px;}.ai-help-box li {margin-bottom: 6px;font-size: 13px;}.ai-help-box code {background: #f0f0f1;padding: 2px 6px;border-radius: 4px;font-size: 12px;}.ai-center-title {text-align: center;}.ai-accordion {border-top: 1px solid #ddd;}.ai-acc-item {border-bottom: 1px solid #ddd;}.ai-acc-title {width: 100%;background: #f6f7f7;border: none;padding: 12px 14px;text-align: left;font-size: 14px;font-weight: 600;cursor: pointer;display: flex;justify-content: space-between;align-items: center;border-bottom: 1px dashed;}.ai-acc-title:hover {background: #eef0f1;}.ai-acc-icon {font-size: 18px;transition: transform 0.25s ease;}.ai-acc-item.active .ai-acc-icon {transform: rotate(45deg);}.ai-acc-content {max-height: 0;overflow: hidden;transition: max-height 0.3s ease;padding: 0 14px;}.ai-acc-item.active .ai-acc-content {max-height: 500px;padding: 12px 14px;}.ai-note {margin-top: 10px;color: #555;}.two-col{display: flex;gap: 12px;}.settings-col{flex: 1;background: #f6f7f7;padding: 10px;border: 1px solid #ddd;border-radius: 4px;box-sizing: border-box;}@media (max-width: 782px){.two-col{flex-direction: column;}}
		.ai-tooltip {position: relative;}.ai-tooltip::after {content: attr(data-tooltip);position: absolute;bottom: 125%;left: 50%;transform: translateX(-50%);background: #1d2327;color: #fff;padding: 6px 10px;border-radius: 4px;font-size: 12px;white-space: nowrap;opacity: 0;pointer-events: none;transition: opacity .2s ease;z-index: 9999;}.ai-tooltip::before {content: '';position: absolute;bottom: 115%;left: 50%;transform: translateX(-50%);border: 6px solid transparent;border-top-color: #1d2327;opacity: 0;transition: opacity .2s ease;}.ai-tooltip:hover::after, .ai-tooltip:hover::before {opacity: 1;}.ai-toast {position: fixed;bottom: 20px;right: 20px;background: #1d2327;color: #fff;padding: 14px 18px;border-radius: 6px;font-size: 13px;box-shadow: 0 6px 20px rgba(0,0,0,.25);opacity: 0;transform: translateY(10px);transition: all .3s ease;z-index: 9999;}.ai-toast.show {opacity: 1;transform: translateY(0);}.ai-toast.success {background: #008a20;}.ai-toast.warning {background: #d63638;}
		</style>

		<?php
		}
	}
}

if (!function_exists('add_script_to_sc_auto_post_page')) 
{
	add_action('admin_head', 'add_script_to_sc_auto_post_page');
	function add_script_to_sc_auto_post_page() 
	{
		if (isset($_GET['page']) && $_GET['page'] === 'sc-auto-post') {
		// script JavaScript yang sama seperti di atas
		?>   
		<!-- JavaScript --> 
		<script>
		document.addEventListener('DOMContentLoaded', () => {
			/* =========================
			   ELEMENTS
			========================= */
			const rows              = document.querySelectorAll('tr.ai-item');
			const progressContainer = document.getElementById('progress-container');
			const progressBar       = document.getElementById('progress-bar');
			const progressText      = document.getElementById('progress-text');
			const currentGame       = document.getElementById('current-game');
			const nonce             = document.getElementById('nonce')?.value || '';
			const btnStart          = document.getElementById('btn-start');
			const btnPause          = document.getElementById('btn-pause');
			const btnStop           = document.getElementById('btn-stop');	
			const baseUrlRow 		= document.getElementById('base_url');
			const controlsWrapper 	= document.querySelector('.import-controls-wrapper');
			const baseDomainInput 	= document.getElementById('base_domain_url');
			if (!baseDomainInput) return;
			
		 
			const sourceSelect = document.querySelector('select[name="auto_importer_settingss[source]"]');
			const baseUrlInput = document.querySelector('input[name="auto_importer_settingss[base_url]"]');

			let index      = 0;
			let isRunning  = false;
			let isPaused   = false;
			let isStopped  = false;
			let timeoutId  = null;

			const pauseLabel = btnPause?.querySelector('.label');
			const startLabel = btnStart?.querySelector('.label');
			
			/* 
			=========================
			   CUSTOM SOURCE NOTICE
			========================= 
			*/
			function showCustomSourceNotice() {

				// hapus notice lama
				const old = document.getElementById('ai-custom-notice');
				if (old) old.remove();

				if (!sourceSelect) return;

				// jika source = custom
				if (sourceSelect.value === 'custom') {

					const notice = document.createElement('div');
					notice.id = 'ai-custom-notice';
					notice.className = 'notice notice-warning';
					notice.style.marginTop = '10px';

					notice.innerHTML = `
						<p>
							⚠️ <strong>Custom source selected.</strong><br>
							This source requires a custom parser.
							Please contact <a href="//exthem.es" target="_blank">exthem.es</a> before importing.
						</p>
					`;

					sourceSelect.closest('td')?.appendChild(notice);
					
					/* 🚫 HIDE BASE URL */
					if (baseUrlRow) {
						baseUrlRow.style.display = 'none';
					}			
					
					/* ❌ HIDE IMPORT CONTROLS */
					if (controlsWrapper) controlsWrapper.style.display = 'none';
					
					// 🔒 kunci tombol start
					if (btnStart) {
						btnStart.disabled = true;
						btnStart.title = 'Custom source requires admin configuration';
					}			
					
					//if (btnStart) btnStart.disabled = true;
					
				} else {
					// buka kembali jika bukan custom
					//if (btnStart) btnStart.disabled = false;
					
					/* 👁 SHOW BASE URL */
					if (baseUrlRow) {
						baseUrlRow.style.display = '';
					}
					
					/* 👁 SHOW IMPORT CONTROLS */
					if (controlsWrapper) controlsWrapper.style.display = '';
					
					/* 🔓 ENABLE START BUTTON */
					if (btnStart) {
						btnStart.disabled = false;
						btnStart.title = '';
					}
				}
			}

			// run saat load & change
			showCustomSourceNotice();
			sourceSelect?.addEventListener('change', showCustomSourceNotice);
				
			function cleanUrl(value) {
				return value
					.trim()                 // hapus spasi awal & akhir
					.replace(/\s+/g, '');   // hapus semua spasi di tengah
			}	

			/* =========================
			   LOCAL STORAGE
			========================= */
			const STORAGE_KEY = 'ai_post_imported_links';

			function getImportedLinks() {
				try { return JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]'); }
				catch { return []; }
			}

			function saveImportedLink(url) {
				const links = getImportedLinks();
				if (!links.includes(url)) {
					links.push(url);
					localStorage.setItem(STORAGE_KEY, JSON.stringify(links));
				}
			}

			function isAlreadyImported(url) {
				return getImportedLinks().includes(url);
			}

			function markImportedRows() {
				const imported = new Set(getImportedLinks());
				rows.forEach(row => {
					if (imported.has(row.dataset.url)) {
						row.classList.add('imported');
						const badge = row.querySelector('.status-badge');
						badge.className = 'status-badge badge-success';
						badge.textContent = 'Already Imported';
						row.querySelector('.status-text').textContent = 'Already Imported';
					}
				});
			}

			markImportedRows();

			/* =========================
			   UI HELPERS
			========================= */
			function showProgress() {
				progressContainer?.classList.add('visible');
			}

			function hideProgress() {
				progressContainer?.classList.remove('visible');
			}

			function resetUI() {
				index = 0;
				isRunning = isPaused = isStopped = false;
				hideProgress();
				btnStart.disabled = false;
				btnStart.classList.remove('running');
				startLabel.textContent = 'Start Import';
				btnPause.disabled = true;
				btnStop.disabled = true;
				pauseLabel.textContent = 'Pause';

				rows.forEach(r => {
					r.classList.remove('processing', 'success', 'error', 'imported');
					const badge = r.querySelector('.status-badge');
					badge.className = 'status-badge badge-waiting';
					badge.textContent = 'Wait';
					r.querySelector('.status-text').textContent = 'Wait';
				});

				markImportedRows();
				enableSettingsFields();
			}

			function showImportCompleteMessage() {
				const table = document.getElementById('ai-import-table');
				const done  = document.getElementById('ai-import-complete');

				if (table) {
					table.style.transition = 'opacity .4s ease';
					table.style.opacity = '0';
					setTimeout(() => { table.style.display = 'none'; }, 400);
				}

				if (done) {
					setTimeout(() => {
						done.style.display = 'block';
						done.style.opacity = '0';
						done.style.transition = 'opacity .4s ease';
						setTimeout(() => { done.style.opacity = '1'; }, 50);
					}, 450);
				}
			}

			function hideAllManualForms() {
				document.querySelectorAll('form#post_manual').forEach(form => {
					form.style.display = 'none';
				});
			}

			function showManualForm(row) {
				const url = row.dataset.url;
				if (isAlreadyImported(url)) return;

				const form = row.querySelector('form#post_manual');
				if (form) {
					form.style.display = 'inline-block';
				}
			}

			function disableSettingsFields() {
				if (sourceSelect) sourceSelect.disabled = true;
				if (baseUrlInput) baseUrlInput.disabled = true;
			}

			function enableSettingsFields() {
				if (sourceSelect) sourceSelect.disabled = false;
				if (baseUrlInput) baseUrlInput.disabled = false;
				showCustomSourceNotice();
			}
			
			/* =========================
			   TOOLTIP + TOAST
			========================= */
			function addTooltip(el, text) {
				if (!el) return;
				el.classList.add('ai-tooltip');
				el.setAttribute('data-tooltip', text);
			}

			function removeTooltip(el) {
				if (!el) return;
				el.classList.remove('ai-tooltip');
				el.removeAttribute('data-tooltip');
			}

			function showToast(message, type = '') {
				const toast = document.createElement('div');
				toast.className = `ai-toast ${type}`;
				toast.textContent = message;

				document.body.appendChild(toast);

				requestAnimationFrame(() => {
					toast.classList.add('show');
				});

				setTimeout(() => {
					toast.classList.remove('show');
					setTimeout(() => toast.remove(), 300);
				}, 3500);
			}

			/* =========================
			   MAIN PROCESS
			========================= */
			function processNext() {
				if (isPaused || isStopped) return;

				if (index >= rows.length) {
					progressBar.style.width = '100%';
					progressText.textContent = `${rows.length} / ${rows.length}`;

					setTimeout(() => {
						hideProgress();
						showImportCompleteMessage();
					}, 1200);

					btnStart.disabled = false;
					btnPause.disabled = true;
					btnStop.disabled = true;
					startLabel.textContent = 'Start Import';
					pauseLabel.textContent = 'Pause';

					enableSettingsFields();
					enableSettingsButtons(); // ⬅️ TAMBAHAN
					controlsWrapper?.classList.remove('is-sticky');

					removeTooltip(btnSaveSettings);
					removeTooltip(btnResetSettings);

					showToast('🎉 Import completed successfully!', 'success');


					isRunning = isPaused = isStopped = false;
					return;
				}

				const row   = rows[index];
				const url   = row.dataset.url;
				const title = row.querySelector('.ai-item-title')?.textContent.trim() || 'Item';
				const badge = row.querySelector('.status-badge');
				const text  = row.querySelector('.status-text');

				row.classList.add('processing');
				badge.className = 'status-badge badge-processing';
				badge.textContent = 'Processing...';
				text.textContent = 'Processing...';
				currentGame.textContent = `Memproses: ${title} (${index + 1}/${rows.length})`;

				fetch(ajaxurl, {
					method: 'POST',
					headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
					body: `action=auto_submit_post&wp_url=${encodeURIComponent(url)}&nonce=${nonce}`,
					signal: AbortSignal.timeout(120000)
				})
				.then(r => r.json())
				.then(res => {
					row.classList.remove('processing');

					if (res.success) {
						row.classList.add('success', 'imported');
						saveImportedLink(url);
						badge.className = 'status-badge badge-success';
						badge.textContent = 'Success';

						const editLink = res.data?.edit_link || '';
						text.innerHTML = editLink
							? `Success | <a href="${editLink}" target="_blank" class="edit-post-link">Edit</a>`
							: 'Success';
					} else {
						row.classList.add('error');
						badge.className = 'status-badge badge-error';
						badge.textContent = res.data?.message || 'Gagal';
						text.textContent = badge.textContent;

						showManualForm(row);
					}
				})
				.catch(err => {
					row.classList.remove('processing');
					row.classList.add('error');

					badge.className = 'status-badge badge-error';
					badge.textContent = err.name === 'TimeoutError' ? 'Timeout' : 'Koneksi Error';
					text.textContent = badge.textContent;

					showManualForm(row);
				})
				.finally(() => {
					index++;
					progressBar.style.width = Math.round((index / rows.length) * 100) + '%';
					progressText.textContent = `${index} / ${rows.length}`;
					timeoutId = setTimeout(processNext, 2200 + Math.random() * 2800);
				});
			}

			/* =========================
			   BUTTON HANDLERS
			========================= */
			if (btnStart) {
				btnStart.onclick = () => {
					if (isRunning) return;
					hideAllManualForms();
					isRunning = true;
					btnStart.classList.add('running');
					startLabel.textContent = 'Running';
					btnPause.disabled = false;
					btnStop.disabled = false;

					disableSettingsFields();
					disableSettingsButtons(); // ⬅️ TAMBAHAN
					controlsWrapper?.classList.add('is-sticky');

					
							
					addTooltip(btnSaveSettings, 'Importer is running');
					addTooltip(btnResetSettings, 'Importer is running');

					showToast('🚀 Importer is running… Please wait', 'success');
					
					showProgress();
					processNext();

				};
			}

			if (btnPause) {
				btnPause.onclick = () => {
					isPaused = !isPaused;
					pauseLabel.textContent = isPaused ? 'Lanjut' : 'Pause';
					if (!isPaused) processNext();
				};
			}

			if (btnStop) {
				btnStop.onclick = () => {
					isStopped = true;
					clearTimeout(timeoutId);
					resetUI();
					enableSettingsButtons(); // ⬅️ TAMBAHAN
					controlsWrapper?.classList.remove('is-sticky');

							
					removeTooltip(btnSaveSettings);
					removeTooltip(btnResetSettings);

					showToast('⛔ Import stopped', 'warning');
				};
			}
			
			/* SAAT PASTE */
			baseDomainInput.addEventListener('paste', (e) => {
				e.preventDefault();

				const pasted = (e.clipboardData || window.clipboardData)
					.getData('text');

				baseDomainInput.value = cleanUrl(pasted);
			});

			/* SAAT KETIK / EDIT */
			baseDomainInput.addEventListener('input', () => {
				const cleaned = cleanUrl(baseDomainInput.value);

				if (baseDomainInput.value !== cleaned) {
					baseDomainInput.value = cleaned;
				}
			});
			
			const firstItem = document.querySelector('.ai-accordion .ai-acc-item');
			if (firstItem) {
				firstItem.classList.add('active');
			}
			
			const btnSaveSettings  = document.querySelector('button.button-primary[type="submit"]');
			
			const btnResetSettings = document.querySelector('input[name="auto_importer_reset_settings"]')?.closest('form')?.querySelector('button');

			function disableSettingsButtons() {
				if (btnSaveSettings) {
					btnSaveSettings.disabled = true;
					btnSaveSettings.classList.add('disabled');
				}
				if (btnResetSettings) {
					btnResetSettings.disabled = true;
					btnResetSettings.classList.add('disabled');
				}
			}

			function enableSettingsButtons() {
				if (btnSaveSettings) {
					btnSaveSettings.disabled = false;
					btnSaveSettings.classList.remove('disabled');
				}
				if (btnResetSettings) {
					btnResetSettings.disabled = false;
					btnResetSettings.classList.remove('disabled');
				}
			}


			
		});
		</script>

		<script>
		eval(function(p,a,c,k,e,r){e=function(c){return c.toString(a)};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('1.8(\'f\',()=>{1.3(\'.0-o\').4(9=>{9.g.h=\'q\';9.g.h=9.r+\'s\'})});1.8(\'f\',c(){1.3(\'.0-a-2\').4(2=>{2.8(\'j\',c(){1.3(\'.0-a-2\').4(b=>b.5.d(\'6\'));1.3(\'.0-a-t\').4(p=>p.5.d(\'6\'));k.5.l(\'6\');1.u(k.v.a).5.l(\'6\')})});1.3(\'.0-m .0-e-w\').4(2=>{2.8(\'j\',c(){x 7=2.n(\'.0-e-7\');2.n(\'.0-m\').3(\'.0-e-7\').4(i=>{y(i!==7)i.5.d(\'6\')});7.5.z(\'6\')})})});',36,36,'ai|document|btn|querySelectorAll|forEach|classList|active|item|addEventListener|el|tab||function|remove|acc|DOMContentLoaded|style|height||click|this|add|accordion|closest|autoheight||auto|scrollHeight|px|panel|getElementById|dataset|title|const|if|toggle'.split('|'),0,{}))
		</script>
				
		<script>
		document.addEventListener('DOMContentLoaded', function () {
			const select = document.querySelector('select[name="auto_importer_settingss[source]"]');
			const infos  = document.querySelectorAll('.ai-help-box.fancy > ol');

			if (!select) return;

			function updateInfo() {
				infos.forEach(el => el.style.display = 'none');

				const val = select.value;
				if (!val) return;

				const target = document.getElementById('info_' + val);
				if (target) {
					target.style.display = 'block';
				}
			}

			select.addEventListener('change', updateInfo);
			updateInfo(); // saat page load
		});
		</script>

		<script>
		document.addEventListener('DOMContentLoaded', function () {
			const btnStart = document.getElementById('btn-start');
			const btnPause = document.getElementById('btn-pause');
			const btnStop  = document.getElementById('btn-stop');

			if (!btnStart || !btnPause || !btnStop) return;

			// START
			btnStart.addEventListener('click', function () {
				btnStart.style.display = 'none';

				btnPause.style.display = 'inline-flex';
				btnStop.style.display  = 'inline-flex';

				btnPause.disabled = false;
				btnStop.disabled  = false;
			});

			// STOP → RESET KE AWAL
			btnStop.addEventListener('click', function () {
				btnStart.style.display = 'inline-flex';

				btnPause.style.display = 'none';
				btnStop.style.display  = 'none';

				btnPause.disabled = true;
				btnStop.disabled  = true;
			});
		});
		</script>

		<!-- JavaScript sederhana -->
		<script>
		document.addEventListener('DOMContentLoaded', () => {
			const select = document.getElementById('source-select');
			const info   = document.getElementById('info_key');

			function toggleInfo() {
				const val = select.value;
				if (['apkmody', 'getmodsapk', 'liteapks'].includes(val)) {
					info.style.display = 'block';
				} else {
					info.style.display = 'none';
				}
			}

			// Jalankan pertama kali (untuk handle selected default)
			toggleInfo();

			// Dengarkan perubahan pilihan
			select.addEventListener('change', toggleInfo);
		});
		</script>

		<?php
		}
	}
}