<?php  
 
add_action('wp_ajax_manual_search_all_app', 'manual_search_all_app_callback');
add_action('wp_ajax_nopriv_manual_search_all_app', 'manual_search_all_app_callback');

function manual_search_all_app_callback() {
	if ( ! isset($_POST['keyword']) ) {
		wp_send_json_error([]);
	}

	$title = sanitize_text_field($_POST['keyword']);
 
	$sc = new StructurCode();

	$result = $sc->getAllAppIDSearch($title);

	wp_send_json_success($result);
}


// =========================
// AJAX handler untuk Search App via Title
// =========================
add_action('wp_ajax_manual_search_app', 'manual_search_app_callback');
add_action('wp_ajax_nopriv_manual_search_app', 'manual_search_app_callback');

function manual_search_app_callback() {
    check_ajax_referer('search_playstore_ajax', 'manual_search_submit_nonce');

    if (empty($_POST['app_title'])) {
        wp_send_json_error('App title is required.');
    }

    $title = sanitize_text_field($_POST['app_title']);
    $sc = new StructurCode(); // Pastikan class ini sudah include

    $appid = $sc->getAppIDs($title);

    if (!$appid) {
        wp_send_json_error('AppID not found for title: ' . $title);
    }

    // Ambil info app
    $link    	= $sc->getAppsLink($appid);
    $appname   	= $sc->GetAppsTitle($appid);
    $version 	= $sc->getAppsVersi($appid);
    $poster  	= $sc->GetAppsPoster($appid);
    $Summary  	= $sc->GetAppsSummary($appid);

    wp_send_json_success([
        'title'   => $appname ?: $title,
        'appid'   => $appid,
        'version' => 'v'.$version ?: '-',
        'summary' => $Summary ?: '-',
        'poster'  => $poster ?: 'https://via.placeholder.com/80x80?text=No+Image',
        'link'    => $link ?: '#'
    ]);
}

add_action('wp_ajax_manual_submit_post', function () 
{
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Permission denied']);
    }

    check_ajax_referer('manual_submit_ajax', 'nonce');

    $url = esc_url_raw(trim($_POST['url'] ?? ''));
    if (!$url || !filter_var($url, FILTER_VALIDATE_URL)) {
        wp_send_json_error(['message' => 'Invalid URL']);
    }

    $settings = get_option('auto_importer_settingss', [
        'source'   => '5play',
        'base_url' => 'https://5play.org/en/android/games/',
    ]);

    $allowed_sources = [
        '5play'      => '5play.org',
        'getmodsapk' => 'getmodsapk.com',
        'apkmody'    => 'apkmody.com',
        'liteapks'   => 'liteapks.com',
        'playstore'   => 'play.google.com',
        'custom'     => null,
    ]; 
    // --- DETEKSI HOST & SOURCE ---
    $host = parse_url($url, PHP_URL_HOST) ?: '';
    $detected_source = 'custom';
    foreach ($allowed_sources as $source => $domain) {
        if ($domain && stripos($host, $domain) !== false) {
            $detected_source = $source;
            break;
        }
    }

    // --- CEK CUSTOM ---
    if ($detected_source === 'custom') {
        wp_send_json_error([
            'message' => "⚠ The submitted URL does not match any allowed source.",
            'detected_host' => $host,
            'detected_source' => $detected_source
        ]);
    }

    $_POST['wp_url'] = $url; // pastikan parser punya key ini

    try {
        $addon_dir = get_template_directory() . '/libs/addons/includes/class/';
       
		$source_to_class = [
			'5play'      => '5play',
			'getmodsapk' => 'getmodsapk',
			'apkmody'    => 'apkmody',
			'liteapks'   => 'liteapks',
			'playstore'   => 'playstore',
		];			

        if (isset($source_to_class[$detected_source]) && $detected_source !== 'custom') {
            $class_file = $addon_dir . $source_to_class[$detected_source] . '.class.php';
            if (!file_exists($class_file)) {
                wp_send_json_error(['message'=>"Parser for source '{$detected_source}' not found."]);
            }
            require_once $class_file;
        }

        // --- Scrape data ---
        $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'),
                'scraper_data' => $data
            ]);
        }

        // --- Import ---
        $importer = new APK_Importer($data);
        $result = $importer->import();
		
		$source_to_method = [
			'5play'      => '5play',
			'getmodsapk' => 'Getmodsapk',
			'apkmody'    => 'Apkmody',
			'liteapks'   => 'Liteapks', 
		];
		if (isset($source_to_method[$source]) && $source !== 'custom' && $source !== 'playstore') {
			$method_name = 'List_Download_' . $source_to_method[$source];
			if (method_exists($importer, $method_name)) {
				$importer->$method_name();
			} else {
				error_log("Method '$method_name' not found in APK_Importer for source '$source'");
			}
		}
 
		// Tambahkan direct apk download
		$importer->add_direct_apk_download();			
 
        $post_id = $importer->post_id ?? 0;
		
		/* ===============================
		 * SIMPAN SOURCE URL (WAJIB)
		 * =============================== */
		if (!empty($post_id)) {
			update_post_meta(
				$post_id,
				'_sc_source_url',
				esc_url_raw($url)
			);
		}

        // --- Ambil meta final ---
        $meta_keys = [
            'wp_GP_ID', 'wp_title_GP', 'wp_poster_GP', 'wp_backgrounds_GP', 'wp_playstore_link',
            'wp_images_GP', 'wp_version_GP', 'wp_sizes', 'wp_installs_GP', 'wp_updates_GP',
            'wp_requires_GP', 'wp_rated_GP', 'wp_ratings_GP', 'wp_desck_GP', 'wp_articlebody_GP',
            'wp_article_content', 'article_gp', 'wp_mods', 'wp_title_wp_mods', 'wp_mods_post',
            'wp_mods2', 'wp_youtube_GP', 'wp_whatnews_GP'
        ];
        $meta_data = [];
        foreach ($meta_keys as $key) {
            $meta_data[$key] = $post_id ? get_post_meta($post_id, $key, true) : '';
        }

        // --- Tambahkan info tambahan ---
        $result['detected_host'] = $host;
        $result['detected_source'] = $detected_source;
        $result['meta'] = $meta_data;
        $result['scraper_data'] = $data; // debug

        wp_send_json_success($result);

    } catch (Exception $e) {
        wp_send_json_error([
            'message' => 'Unexpected error: ' . $e->getMessage(),
            'success' => false,
            'post_id' => 0,
            'meta' => [],
            'detected_host' => $host,
            'detected_source' => $detected_source,
            'scraper_data' => $data ?? null
        ]);
    } 

});
 

if (!function_exists('auto_submit_post')) 
{
    add_action('wp_ajax_auto_submit_post', 'auto_submit_post');
    function auto_submit_post() 
	{
        global $opt_themes;

        // Validasi nonce
        check_ajax_referer('auto_submit_post', 'nonce');

        // Ambil settings
        $settings = get_option('auto_importer_settingss', [
            'source'   => '5play',
            'base_url' => 'https://5play.org/en/android/games/',
        ]);

        // Cek hak akses
        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' => 'Invalid URL']);
        }

        $source = trim($settings['source'] ?? '');

        $allowed_sources = [
            '5play'      => '5play.org',
            'getmodsapk' => 'getmodsapk.com',
            'apkmody'    => 'apkmody.com',
            'liteapks'   => 'liteapks.com',
            'custom'     => null,
        ];

        if (!array_key_exists($source, $allowed_sources)) {
            wp_send_json_error(['message' => 'Invalid source selected.']);
        }

        if ($source !== 'custom') {
            $expected = $allowed_sources[$source];
            $host     = parse_url($url, PHP_URL_HOST);

            if ($host === false || stripos($host, $expected) === false) {
                wp_send_json_error([
                    'message' => "URL must be from {$expected} for source '{$source}'."
                ]);
            }
        }

        try {
            // Path untuk class scraper
            $addon_dir = get_template_directory() . '/libs/addons/includes/class/';

            $source_to_class = [
                '5play'      => '5play',
                'getmodsapk' => 'getmodsapk',
                'apkmody'    => 'apkmody',
                'liteapks'   => 'liteapks',
            ];

            // Load file class jika bukan custom
            if (isset($source_to_class[$source]) && $source !== 'custom') {
                $class_file = $addon_dir . $source_to_class[$source] . '.class.php';
                if (file_exists($class_file)) {
                    require_once $class_file;
                } else {
                    error_log("Class file not found for source '{$source}': " . $class_file);
                    wp_send_json_error([
                        'message' => "Parser for source '{$source}' not found. Contact the administrator."
                    ]);
                }
            }

            // Scrape data
            $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')
                ]);
            }

            // Import
            $importer = new APK_Importer($data);
            $result = $importer->import(); // <-- hasil lengkap

            // Jika import gagal atau duplikat → kirim semua result
            if (!$result['success'] || $result['is_duplicate']) {
                wp_send_json_error($result);
            }

            // Proses list download (jika ada)
            $source_to_method = [
                '5play'      => '5play',
                'getmodsapk' => 'Getmodsapk',
                'apkmody'    => 'Apkmody',
                'liteapks'   => 'Liteapks',
            ];

            if (isset($source_to_method[$source]) && $source !== 'custom') {
                $method_name = 'List_Download_' . $source_to_method[$source];
                if (method_exists($importer, $method_name)) {
                    $importer->$method_name();
                } else {
                    error_log("Method '$method_name' not found in APK_Importer for source '$source'");
                }
            }

            // Tambahkan direct apk download
            $importer->add_direct_apk_download();

            // Kirim semua result lengkap ke frontend
            wp_send_json_success($result);

        } catch (Exception $e) {
            // Kirim semua info error ke frontend
            wp_send_json_error([
                'message' => 'Unexpected error: ' . $e->getMessage(),
                'success' => false,
                'post_id' => 0,
                'edit_link' => '',
                'notices' => [],
                'is_duplicate' => false,
                'missing_gp_id' => false,
                'missing_featured' => false,
            ]);
        }
    }
}

if (!function_exists('auto_submit_post_ol')) 
{
    //add_action('wp_ajax_auto_submit_post', 'auto_submit_post_ol');
    function auto_submit_post_ol() {
        check_ajax_referer('auto_submit_post', 'nonce');

        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' => 'Invalid URL']);
        }

        $settings = get_option('auto_importer_settingss', [
            'source'   => '5play',
            'base_url' => 'https://5play.org/en/android/games/',
        ]);

        try {
            // --- Load class parser sesuai source ---
            $addon_dir = get_template_directory() . '/libs/addons/includes/class/';
            $source = trim($settings['source'] ?? '');
            $source_to_class = [
                '5play'      => '5play',
                'getmodsapk' => 'getmodsapk',
                'apkmody'    => 'apkmody',
                'liteapks'   => 'liteapks',
            ];

            if (isset($source_to_class[$source])) {
                $class_file = $addon_dir . $source_to_class[$source] . '.class.php';
                if (file_exists($class_file)) {
                    require_once $class_file;
                }
            }

            $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) ?: admin_url("post.php?post={$existing_id}&action=edit") : '',
                        'title'        => $existing_id ? get_the_title($existing_id) : ''
                    ]);
                }
                wp_send_json_error(['message' => $result->get_error_message()]);
            }

            $post_id = (int) $result['post_id'] ?? 0;
            if ($post_id < 1) {
                wp_send_json_error(['message' => 'Failed to get valid post ID']);
            }

            // --- Pastikan edit link selalu ada ---
            $edit_link = get_edit_post_link($post_id);
            if (!$edit_link) {
                $edit_link = admin_url("post.php?post={$post_id}&action=edit");
            }

            wp_send_json_success([
                'post_id'   => $post_id,
                'title'     => get_the_title($post_id),
                'edit_link' => $edit_link,
                'message'   => 'Post successfully imported!'
            ]);

        } catch (Exception $e) {
            wp_send_json_error(['message' => 'Unexpected error: ' . $e->getMessage()]);
        }
    }
}

if (!function_exists('auto_submit_post5555')) {
    //add_action('wp_ajax_auto_submit_post', 'auto_submit_post5555');

    function auto_submit_post5555() 
    {
        global $opt_themes;

        // Validasi nonce
        check_ajax_referer('auto_submit_post', 'nonce');

        // Ambil settings default
        $settings = get_option('auto_importer_settingss', [
            'source'   => '5play',
            'base_url' => 'https://5play.org/en/android/games/',
        ]);

        // Hanya admin bisa mengakses
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Hanya untuk Administrator']);
        }

        // Ambil URL dari POST
        $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' => 'Invalid URL']);
        }

        // Periksa source
        $source = trim($settings['source'] ?? '');
        $allowed_sources = [
            '5play'      => '5play.org',
            'getmodsapk' => 'getmodsapk.com',
            'apkmody'    => 'apkmody.com',
            'liteapks'   => 'liteapks.com',
            'custom'     => null,
        ];

        if (!array_key_exists($source, $allowed_sources)) {
            wp_send_json_error(['message' => 'Invalid source selected.']);
        }

        if ($source !== 'custom') {
            $host = parse_url($url, PHP_URL_HOST);
            $expected = $allowed_sources[$source];
            if ($host === false || stripos($host, $expected) === false) {
                wp_send_json_error([
                    'message' => "URL must be from {$expected} for source '{$source}'."
                ]);
            }
        }

        try {
            // Direktori kelas addon
            $addon_dir = get_template_directory() . '/libs/addons/includes/class/';

            // Mapping source ke file class
            $source_to_class = [
                '5play'      => '5play',
                'getmodsapk' => 'getmodsapk',
                'apkmody'    => 'apkmody',
                'liteapks'   => 'liteapks',
            ];

            // Load file class jika ada
            if (isset($source_to_class[$source]) && $source !== 'custom') {
                $class_file = $addon_dir . $source_to_class[$source] . '.class.php';
                if (file_exists($class_file)) {
                    require_once $class_file;
                } else {
                    error_log("Class file not found for source '{$source}': " . $class_file);
                    if (defined('DOING_AJAX') && DOING_AJAX) {
                        wp_send_json_error([
                            'message' => "Parser for source '{$source}' not found. Contact the administrator."
                        ]);
                    }
                }
            }

            // Scraping data
            $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
            $importer = new APK_Importer($data);
            $result = $importer->import();

            // Cek error duplicate
            if (is_wp_error($result)) {
                if ($result->get_error_code() === 'duplicate_found') {
                    $existing_id = $result->get_error_data()['post_id'] ?? 0;
                    $edit_link   = $existing_id ? get_edit_post_link($existing_id, '') : '';
                    if (!$edit_link && $existing_id && current_user_can('edit_post', $existing_id)) {
                        $edit_link = admin_url("post.php?post={$existing_id}&action=edit");
                    }
                    wp_send_json_error([
                        'message'      => $result->get_error_message(),
                        'is_duplicate' => true,
                        'existing_id'  => $existing_id,
                        'edit_link'    => $edit_link,
                        'title'        => $existing_id ? get_the_title($existing_id) : ''
                    ]);
                }
                wp_send_json_error(['message' => $result->get_error_message()]);
            }

            // Pastikan post_id valid
            $post_id = (int) $result;
            if ($post_id < 1) {
                wp_send_json_error(['message' => 'Failed to get valid post ID']);
            }

            // Ambil edit link
            $edit_link = get_edit_post_link($post_id, '');
            if (!$edit_link && current_user_can('edit_post', $post_id)) {
                $edit_link = admin_url("post.php?post={$post_id}&action=edit");
            }

            // Jalankan method download sesuai source jika ada
            $source_to_method = [
                '5play'      => '5play',
                'getmodsapk' => 'Getmodsapk',
                'apkmody'    => 'Apkmody',
                'liteapks'   => 'Liteapks',
            ];

            if (isset($source_to_method[$source]) && $source !== 'custom') {
                $method_name = 'List_Download_' . $source_to_method[$source];
                if (method_exists($importer, $method_name)) {
                    $importer->$method_name();
                } else {
                    error_log("Method '$method_name' not found in APK_Importer for source '$source'");
                    if (defined('DOING_AJAX') && DOING_AJAX) {
                        wp_send_json_error([
                            'message' => "Download feature for source '$source' not available. Contact the administrator."
                        ]);
                    }
                }
            }

            // Tambahkan direct APK download
            $importer->add_direct_apk_download();

            // Kirim response sukses
            wp_send_json_success([
                'post_id'   => $post_id,
                'title'     => get_the_title($post_id),
                'edit_link' => $edit_link,
                'message'   => 'Post successfully imported!'
            ]);

        } catch (Exception $e) {
            wp_send_json_error(['message' => 'Unexpected error: ' . $e->getMessage()]);
        }
    }
}


if (!function_exists('auto_submit_post2')) 
{
	//add_action('wp_ajax_auto_submit_post', 'auto_submit_post2');

	function auto_submit_post2() 
	{
		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'])) : '';

        $host 	= parse_url($url, PHP_URL_HOST);
		
		if (empty($url) || !filter_var($url, FILTER_VALIDATE_URL)) {
			wp_send_json_error(['message' => 'Invalid URL']);
		}
			
		$source = trim($settings['source'] ?? '');

		$allowed_sources = [
			'5play'      => '5play.org',
			'getmodsapk' => 'getmodsapk.com',
			'apkmody'    => 'apkmody.com',
			'liteapks'   => 'liteapks.com',
			'custom'     => null,
		];

		if (!array_key_exists($source, $allowed_sources)) {
			wp_send_json_error(['message' => 'Invalid source selected.']);
		}

		if ($source !== 'custom') {
			$expected = $allowed_sources[$source];
			$host     = parse_url($url, PHP_URL_HOST);

			if ($host === false || stripos($host, $expected) === false) {
				wp_send_json_error([
					'message' => "URL must be from {$expected} for source '{$source}'."
				]);
			}
		}
		
		try {
			// 1. Scraping detail game
						
			// Tentukan path dasar (lebih aman daripada memanggil get_template_directory() berulang)
			$addon_dir = get_template_directory() . '/libs/addons/includes/class/';

			// Mapping source ke nama file class (tanpa ekstensi .php)
			$source_to_class = [
				'5play'      => '5play',
				'getmodsapk' => 'getmodsapk',
				'apkmody'    => 'apkmody',
				'liteapks'   => 'liteapks',
				// 'custom'  => tidak perlu require file khusus
			];

			// Ambil source dari settings
			$source = trim($settings['source'] ?? '');

			// Jika source ada di mapping dan bukan 'custom', load file class-nya
			if (isset($source_to_class[$source]) && $source !== 'custom') {
				$class_file = $addon_dir . $source_to_class[$source] . '.class.php';
				
				if (file_exists($class_file)) {
					require_once $class_file;
				} else {
					// Optional: log error atau kirim respons ke JS
					error_log("Class file not found for source '{$source}': " . $class_file);
					
					// Jika ingin langsung beri tahu user via AJAX
					if (defined('DOING_AJAX') && DOING_AJAX) {
						wp_send_json_error([
							'message' => "Parser for source '{$source}' not found. Contact the administrator."
						]);
					}
				}
			}
			
			$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();
			
			$post_id = (int) $result;
			
			$edit_link = get_edit_post_link($post_id, '');
			if(!$edit_link && current_user_can('edit_post', $post_id)){
				$edit_link = admin_url("post.php?post={$post_id}&action=edit");
			}

			if ($post_id < 1) {
				wp_send_json_error(['message' => 'Failed to get valid post ID']);
			}
			
			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()]);
			}

			// Ambil source dari settings
			$source = trim($settings['source'] ?? '');

			// Mapping source ke nama method (tanpa prefix "List_Download_")
			$source_to_method = [
				'5play'      => '5play',
				'getmodsapk' => 'Getmodsapk',
				'apkmody'    => 'Apkmody',
				'liteapks'   => 'Liteapks',
				// 'custom'  => tidak perlu diproses di sini
			];

			// Jika source ada di mapping dan bukan 'custom'
			if (isset($source_to_method[$source]) && $source !== 'custom') {
				$method_name = 'List_Download_' . $source_to_method[$source];

				// Pastikan method benar-benar ada di class $importer
				if (method_exists($importer, $method_name)) {
					$importer->$method_name();
				} else {
					// Log error jika method tidak ditemukan (penting untuk debugging)
					error_log("Method '$method_name' not found in class APK_Importer for source '$source'");
					
					// Optional: beri tahu user via AJAX jika ini bagian dari handler AJAX
					if (defined('DOING_AJAX') && DOING_AJAX) {
						wp_send_json_error([
							'message' => "Download feature for source '$source' not available. Contact the administrator."
						]);
					}
				}
			}
			// Jika source = 'custom' atau source tidak dikenal → tidak lakukan apa-apa (sesuai kode asli)

			$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_submit_post1')) 
{
	//add_action('wp_ajax_auto_submit_post', 'auto_submit_post1');

	function auto_submit_post1() 
	{
		global $opt_themes;

		check_ajax_referer('auto_submit_post', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Only administrators can perform this action']);
        } 

        // 2. Ambil setting
        $settings = get_option('auto_importer_settings', [
            'source'   => '5play',
            'base_url' => 'https://5play.org/en/android/games/',
        ]);

        $source = $settings['source'] ?? '5play';
		 
        // 3. Validasi URL
        $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' => 'Please provide a valid URL']);
        } 		
		
        // 4. Validasi domain sesuai source
        $host = parse_url($url, PHP_URL_HOST);
        $allowed_domains = [
            '5play'      => '5play.org',
            'getmodsapk' => 'getmodsapk.com',
            'apkmody'    => 'apkmody.com',      // atau apkmody.mobi tergantung versi
            'liteapks'   => 'liteapks.com',
        ];

        /* if (isset($allowed_domains[$source])) {
            if (stripos($host, $allowed_domains[$source]) === false) {
                wp_send_json_error([
                    'message' => "This URL is not from {$allowed_domains[$source]}. Only links from allowed sources are accepted."
                ]);
            }
        } */
		
		/* 
		$url = isset($_POST['wp_url']) ? esc_url_raw($_POST['wp_url']) : '';

		if (empty($url) || !filter_var($url, FILTER_VALIDATE_URL)) {
			wp_send_json_error(['message' => 'Invalid URL']);
		}

		// Opsional: Batasi hanya domain 5play.org
		if (strpos($url, '5play.org') === false) {
			wp_send_json_error(['message' => 'Only supports links from 5play.org']);
		}
		*/
		
        // 5. Tentukan class scraper sesuai source
        $scraper_classes = [
            '5play'      => 'scrapes',
            'getmodsapk' => 'scrapes',
            'apkmody'    => 'scrapes',
            'liteapks'   => 'scrapes',
            // 'custom'  => 'scrapes',
        ];

        $class_name = $scraper_classes[$source] ?? null;

        if (!$class_name) {
            wp_send_json_error(['message' => 'Unsupported source selected']);
        }

        // 6. Load file scraper dengan aman
        $scraper_file = get_template_directory() . "/libs/addons/includes/class/{$source}.class.php";

        if (!file_exists($scraper_file)) {
            error_log("Scraper file not found: $scraper_file");
            wp_send_json_error(['message' => 'Internal configuration error. Please contact administrator.']);
        }

        require_once $scraper_file;


		try {
			 
			
			$scraper = new scrapes();
			$data = $scraper->scrape_web_info($url, false);

			
            if (!$data || !empty($data['error'])) {
                wp_send_json_error([
                    'message' => 'Failed to extract app information. The page structure may have changed.'
                ]);
            }

			$importer = new APK_Importer($data); 


            // Optional: Cek duplikat dulu (jika class sudah support)
            if (method_exists($importer, 'check_for_duplicate')) {
                $duplicate = $importer->check_for_duplicate();
                if ($duplicate) {
                    wp_send_json_error([
                        'message'     => 'This app already exists!',
                        'is_duplicate' => true,
                        'existing_id'  => $duplicate['post_id'],
                        'edit_link'    => get_edit_post_link($duplicate['post_id'], ''),
                        'title'        => get_the_title($duplicate['post_id'])
                    ]);
                }
            }

			$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()]);
			} 
			*/

            if (is_wp_error($result)) {
                wp_send_json_error(['message' => $result->get_error_message()]);
            }
			
			$post_id = (int) $result;
			
            if ($post_id < 1) {
                wp_send_json_error(['message' => 'Failed to create or update post']);
            }
            // Proses link download sesuai source
            $download_methods = [
                '5play'      => 'List_Download_5play',
                'getmodsapk' => 'List_Download_Getmodsapk',
                'apkmody'    => 'List_Download_Apkmody',
                'liteapks'   => 'List_Download_Liteapks',
            ];

            $method = $download_methods[$source] ?? null;

            if ($method && method_exists($importer, $method)) {
                $importer->$method();
            }

			$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'   => 'App successfully imported/updated!'
            ]);
			
		} catch (Exception $e) {
			
            error_log("Auto import error: " . $e->getMessage() . "\n" . $e->getTraceAsString());
            wp_send_json_error(['message' => 'An unexpected error occurred. Please try again later.']);
			 
		}
	}
}

if (!function_exists('auto_importer_default_sources')) 
{
	function auto_importer_default_sources() 
	{
		return [
			'5play'      => 'https://5play.org/en/android/games/',
			'apkmody'    => 'https://apkmody.com/games',
			'getmodsapk' => 'https://getmodsapk.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;
});

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) 
	{
		$allowed_sources = [
			'5play',
			'apkmody',
			'getmodsapk',
			'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,
		];
	}
} 

if (!function_exists('auto_post_page2')) 
{
	function auto_post_page2() 
	{						
		$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'] = '5play';
		}

		$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">		
			<?php
			// Di halaman admin Anda
			echo $sc->renderImporterSettingsPostbox($settings, $default_sources);
			?>			
		</div>

		<div class="settings-col col-2">	 
			<?php
			// Di halaman admin atau template Anda
			echo $sc->renderHelpTabsSection();
			?>
		</div>

	</div>
	
	<?php 
	echo $sc->renderImportControlsAndProgress($count); // $count adalah jumlah total item	
	echo $sc->renderImportPostList($count, $items, $sc, $settings);
	?>

</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']) && in_array($_GET['page'], ['sc-auto-post', 'sc-manual-post'])) {
		?>       
		<!-- CSS -->
	 
		<style>	
		.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-controls-wrapper {position: fixed;left: 50%;bottom: 0px;transform: translateX(-50%);z-index: 99999;background: transparent;padding: 0;border-radius: 10px;overflow: hidden;pointer-events: auto;transition: opacity 0.3s ease, transform 0.3s ease;}.import-controls {display: flex;gap: 10px;background: #ffffff;padding: 10px 16px;border-radius: 10px;border: 1px solid #dcdcde;box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);backdrop-filter: blur(6px);}.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;white-space: nowrap;}.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: nowrap;overflow-x: auto;gap: 8px;padding: 8px 14px;-webkit-overflow-scrolling: touch;}.import-btn {flex: 0 0 auto;min-width: 100px;padding: 8px 12px;font-size: 12.5px;justify-content: center;}@media (max-width: 480px) {.import-controls {gap: 6px;padding: 8px 10px;}.import-btn {min-width: 90px;padding: 7px 10px;font-size: 12px;}}}.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;}}.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;}.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;}.import-notification {position: fixed;top: 50%;left: 50%;transform: translate(-50%,-50%);z-index: 9999;width: 90%;max-width: 520px;background: #fff;border: 1px solid #e0e0e0;border-radius: 16px;overflow: hidden;box-shadow: 0 15px 50px rgba(0,0,0,.15);color: #333;font-family: system-ui,sans-serif;text-align: center;}.notification-content {display: flex;align-items: center;justify-content: center;gap: 16px;padding: 28px 24px 20px;flex-wrap: wrap;}.icon-wrapper {font-size: 48px;color: #6b7280;background: #f3f4f6;width: 64px;height: 64px;border-radius: 16px;display: grid;place-items: center;flex-shrink: 0;}.message strong {color: #1f2937;font-weight: 600;font-size: clamp(1.15rem,4.5vw,1.25rem);}.message {line-height: 1.5;font-size: clamp(0.95rem,3.8vw,1.05rem);color: #4b5563;}.progress-section {padding: 0 24px 20px;}.progress-count {font-size: 1.05rem;font-weight: 500;color: #374151;margin-bottom: 6px;}.progress-count span {font-weight: 700;color: #6366f1;}.current-item {font-size: 0.95rem;color: #4b5563;margin-bottom: 10px;font-style: italic;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;}.loading-bar {height: 6px;background: #f3f4f6;border-radius: 3px;overflow: hidden;}.loading-progress {width: 0%;height: 100%;background: linear-gradient(90deg,#6366f1,#8b5cf6);transition: width .4s ease;}@media (max-width:480px) {.notification-content {flex-direction: column;gap: 14px;padding: 24px 18px 16px;}.icon-wrapper {width: 54px;height: 54px;font-size: 40px;}}.edit-link-section {font-size: 0.95rem;margin-top: 8px;}.edit-link {color: #4f46e5;font-weight: 600;text-decoration: none;transition: color 0.2s;}.edit-link:hover {color: #4338ca;text-decoration: underline;}.current-status {font-size: 1rem;font-weight: 600;margin: 12px 0;padding: 8px 16px;border-radius: 8px;background: #f3f4f6;}.current-status.success {background: #d1fae5;color: #065f46;}.current-status.error {background: #fee2e2;color: #991b1b;}.current-status.processing {background: #fef3c7;color: #92400e;}.summary-section {background: #f9fafb;border: 1px solid #e5e7eb;border-radius: 12px;padding: 16px;margin: 16px 0;}#import-summary-list {list-style: none;padding-left: 0;}#import-summary-list li {padding: 6px 0;font-size: 0.95rem;}#import-summary-list li.success {color: #065f46;}#import-summary-list li.warning {color: #92400e;}#import-summary-list li.error {color: #991b1b;}#import-summary-list li.info {color: #1e40af;}.notification-header {display: flex;justify-content: space-between;align-items: center;padding: 16px 24px;background: #f3f4f6;border-bottom: 1px solid #e5e7eb;}.close-btn {cursor: pointer;font-size: 1.4rem;color: #6b7280;}.close-btn:hover {color: #374151;}.status-success {color: #16a34a;font-weight: 600;}.status-duplicate {color: #d97706;font-weight: 600;}.status-missing {color: #ea580c;}.status-draft {color: #7c3aed;}.status-error {color: #dc2626;font-weight: 600;}.recent-logs li .status-error, .recent-logs li .status-duplicate {font-weight: 600;}#recent-activity-list {list-style: none;padding: 0;margin: 0;max-height: 160px;overflow-y: auto;background: #f1f5f9;border-radius: 6px;-ms-overflow-style: none;scrollbar-width: none;}#recent-activity-list li {padding: 10px 12px;border-bottom: 1px solid #e5e7eb;transition: background-color 0.15s ease;}#recent-activity-list li:last-child {border-bottom: none;}#recent-activity-list li:hover {background-color: #f1f5f9;}#recent-activity-list .time {color: #6b7280;font-family: 'Courier New', Courier, monospace;font-size: 0.75rem;white-space: nowrap;}#recent-activity-list strong {color: #111827;font-weight: 600;margin-right: 8px;}#recent-activity-list .status {display: inline-block;padding: 2px 8px;border-radius: 9999px;font-size: 0.6875rem;font-weight: 500;text-transform: capitalize;}.status-success {background-color: #d1fae5;color: #065f46;}.status-error {background-color: #fee2e2;color: #991b1b;}.status-warning {background-color: #fef3c7;color: #92400e;}.status-info {background-color: #dbeafe;color: #1e40af;}#recent-activity-list small {color: #9ca3af;font-size: 0.75rem;margin-left: 6px;}#recent-activity-list .empty-message {color: #9ca3af;font-style: italic;text-align: center;padding: 16px;}#recent-activity-list::-webkit-scrollbar {display: none;}#recent-activity-list::-webkit-scrollbar-track {background: #f1f5f9;border-radius: 3px;}#recent-activity-list::-webkit-scrollbar-thumb {background: #9ca3af;border-radius: 3px;}#recent-activity-list::-webkit-scrollbar-thumb:hover {background: #6b7280;}
		</style>

		<?php
		}
	}
}

if (!function_exists('enqueue_autopost_admin_script')) 
{
	function enqueue_autopost_admin_script() 
	{
		// Hanya load di halaman yang benar
		if ( ! isset( $_GET['page'] ) || $_GET['page'] !== 'sc-auto-post' ) {
			return;
		}

		// 1. Enqueue script utama (autopost.js)
		wp_enqueue_script(
			'auto-post-js',
			get_stylesheet_directory_uri() . '/libs/addons/assets/js/autopost4.js',
			array( 'jquery' ),
			'1.0',
			true  // Load di footer autopost atau autopost2 autopost3
		);

		// 2. Tambahkan loading indicator sederhana di header (via inline script)
		//    → Tampil saat halaman masih loading, hilang setelah DOM ready
		$loading_html = '
		<style>
			#wpadminbar-loading {
				position: fixed;
				top: 0;
				left: 0;
				right: 0;
				height: 3px;
				background: linear-gradient(to right, #2271b1, #72aee6);
				z-index: 999999;
				transform-origin: left;
				transform: scaleX(0);
				transition: transform 0.3s ease;
			}
			#wpadminbar-loading.active {
				transform: scaleX(1);
			}
		</style>
		<div id="wpadminbar-loading"></div>

		<script>
			document.addEventListener("DOMContentLoaded", function() {
				const loader = document.getElementById("wpadminbar-loading");
				if (loader) {
					loader.classList.add("active");
					// Hilangkan setelah 1.5 detik atau sesuaikan kebutuhan
					setTimeout(() => {
						loader.style.opacity = "0";
						setTimeout(() => loader.remove(), 400);
					}, 1500);
				}
			});
		</script>';

		// Cetak HTML loading + style + script langsung di header admin
		add_action( 'admin_head', function() use ( $loading_html ) {
			echo $loading_html;
		});
	}
	//add_action( 'admin_enqueue_scripts', 'enqueue_autopost_admin_script' );
}

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() 
	{
		
		$Go_Curl = new Go_Curl();
		$sc = new StructurCode();
		if (isset($_GET['page']) && in_array($_GET['page'], ['sc-auto-post', 'sc-manual-post'])) {
		// script JavaScript yang sama seperti di atas
		?>   
		<?php echo $sc->renderImportNotification(); ?>
		<!-- js asli -->

<script>
 
document.addEventListener('DOMContentLoaded', () => {
  /* =========================
       CONFIG
  ========================= */
  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');
  const ImportNotifModal  = document.querySelector('#import-notification');
  const sourceSelect      = document.querySelector('select[name="auto_importer_settingss[source]"]');
  const baseUrlInput      = document.querySelector('input[name="auto_importer_settingss[base_url]"]');
  const pauseLabel        = btnPause?.querySelector('.label');
  const startLabel        = btnStart?.querySelector('.label');
  const STORAGE_KEY       = 'ai_post_imported_links';
  const btnSaveSettings   = document.querySelector('button.button-primary[type="submit"]');
  const btnResetSettings  = document.querySelector('input[name="auto_importer_reset_settings"]')?.closest('form')?.querySelector('button');
  const btnCloseNotif     = document.getElementById('import-notification-close');

  if (!baseDomainInput || !rows.length || !btnStart) return;

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

  let importStats = {
    total:        0,
    success:      0,
    duplicate:    0,
    missingImage: 0,
    draft:        0,
    error:        0
  };

  let recentLogs = [];
  let importLogs = [];

  /* =========================
       UTILITIES
  ========================= */
  function cleanUrl(value) {
    return value.trim().replace(/\s+/g, '');
  }

  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();

  baseDomainInput.addEventListener('paste', (e) => {
    e.preventDefault();
    const pasted = (e.clipboardData || window.clipboardData).getData('text');
    baseDomainInput.value = cleanUrl(pasted);
  });

  baseDomainInput.addEventListener('input', () => {
    const cleaned = cleanUrl(baseDomainInput.value);
    if (baseDomainInput.value !== cleaned) {
      baseDomainInput.value = cleaned;
    }
  });

  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');
    }
  }

  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();
  }

  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);
  }

  function showImportNotification() {
    /* if (ImportNotifModal) ImportNotifModal.style.display = 'block';
    if (btnCloseNotif) btnCloseNotif.style.display = 'block'; */
  }

  function hideImportNotification() {
    /* if (ImportNotifModal) ImportNotifModal.style.display = 'none';
    if (btnCloseNotif) btnCloseNotif.style.display = 'none'; */
  }

  function updateImportProgressKeModal(current, total, currentTitle = '—', editLink = '') {
    if (total <= 0) return;
    const percent = Math.min(100, Math.round((current / total) * 100));
    document.getElementById('current-count').textContent = current;
    document.getElementById('total-count').textContent = total;
    document.getElementById('current-item-title').textContent = `Processing: ${currentTitle}`;
    document.getElementById('progress-fill').style.width = percent + '%';

    const linkSection = document.getElementById('edit-link-section');
    const editLinkEl = document.getElementById('edit-post-link');
    if (editLink && editLink !== '#') {
      editLinkEl.href = editLink;
      linkSection.style.display = 'block';
    } else {
      linkSection.style.display = 'none';
    }
  }

  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';

      const metaDiv = r.querySelector('.ai-row-meta');
      if (metaDiv) metaDiv.remove();
    });

    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(f => f.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 showCustomSourceNotice() {
    const old = document.getElementById('ai-custom-notice');
    if (old) old.remove();

    if (!sourceSelect) return;

    const parentTd = sourceSelect.closest('td');
    if (!parentTd) return;

    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>
        Please contact <a href="//exthem.es" target="_blank">exthem.es</a> for new source.</p>`;
      parentTd.appendChild(notice);

      if (baseUrlRow) baseUrlRow.style.display = 'none';
      if (controlsWrapper) controlsWrapper.style.display = 'none';
      if (btnStart) {
        btnStart.disabled = true;
        btnStart.title = 'Custom source requires admin configuration';
      }
    } else {
      if (baseUrlRow) baseUrlRow.style.display = '';
      if (controlsWrapper) controlsWrapper.style.display = '';
      if (btnStart) {
        btnStart.disabled = false;
        btnStart.title = '';
      }
    }
  }

  window.addEventListener('load', showCustomSourceNotice);
  sourceSelect?.addEventListener('change', showCustomSourceNotice);

  /* =========================
       LOGGING
  ========================= */
  function addRecentLog(title, status, extra = '', editLink = '') {
    const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    const logEntry = {
      time,
      title: title.length > 60 ? title.substring(0, 57) + '...' : title,
      status,
      extra,
      editLink: editLink || ''  // simpan editLink di object log
    };
    recentLogs.unshift(logEntry);
    if (recentLogs.length > 10) recentLogs.pop();
    renderRecentLogs();
  }

  function renderRecentLogs() {
    const list = document.getElementById('recent-activity-list');
    if (!list) return;
    list.innerHTML = '';

    recentLogs.forEach(l => {
      const li = document.createElement('li');
      li.style.marginBottom = '6px';

      // Status dengan warna
      const statusSpan = `<span class="status-${l.status.toLowerCase()}">${l.status}</span>`;

      // Tambahkan link Edit Post jika ada
      let editLinkHtml = '';
      if (l.editLink && l.editLink !== '#' && l.editLink.trim() !== '') {
        editLinkHtml = ` <a href="${l.editLink}" target="_blank" class="recent-edit-link" style="font-size:0.85em; margin-left:8px; color:#2271b1; text-decoration:none;">[Edit Post]</a>`;
      }

      li.innerHTML = `
        <span class="text-gray-500 text-xs">(${l.time})</span> 
        ${statusSpan}
        ${l.title}
        ${l.extra ? ` (${l.extra})` : ''}
        ${editLinkHtml}
      `;

      list.appendChild(li);
    });
  }

/* =========================
   FINAL RECENT LOG BY STATUS
   (AFTER IMPORT COMPLETE)
========================= */
function addRecentLogByStatusComplete() {
  const list = document.getElementById('recent-activity-list');
  if (!list) return;

  // Group log berdasarkan status
  const grouped = {
    Success: [],
    Error: [],
    Duplicate: [],
    Draft: []
  };

  recentLogs.forEach(log => {
    if (grouped[log.status]) {
      grouped[log.status].push(log);
    }
  });

  // Separator utama
  const separator = document.createElement('li');
  separator.style.margin = '10px 0';
  separator.style.borderTop = '2px solid #e5e7eb';
  separator.innerHTML = `<strong>Final Import Results</strong>`;
  list.appendChild(separator);

  Object.entries(grouped).forEach(([status, logs]) => {
    if (!logs.length) return;

    const header = document.createElement('li');
    header.style.marginTop = '8px';
    header.innerHTML = `<strong class="status-${status.toLowerCase()}">${status} (${logs.length})</strong>`;
    list.appendChild(header);

    logs.forEach(l => {
      const li = document.createElement('li');
      li.style.marginLeft = '12px';
      li.style.marginBottom = '4px';

      let editLinkHtml = '';
      if (l.editLink && l.editLink.trim() !== '') {
        editLinkHtml = `
          <a href="${l.editLink}" 
             target="_blank"
             style="margin-left:6px; font-size:0.85em; color:#2271b1; text-decoration:none;">
            [Edit]
          </a>`;
      }

      li.innerHTML = `
        <span class="text-gray-500 text-xs">(${l.time})</span>
        ${l.title}
        ${editLinkHtml}
      `;

      list.appendChild(li);
    });
  });

  // Auto scroll ke bawah
  list.scrollTop = list.scrollHeight;
}


  function addImportLog(message, type = 'info', edit_link = '') {
  const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
  importLogs.unshift({ time, message, type, edit_link });
  if (importLogs.length > 20) importLogs.pop();
  renderImportLogs();
}


  function renderImportLogs() {
  const containers = {
    success: document.getElementById('import-log-success'),
    error: document.getElementById('import-log-error'),
    warning: document.getElementById('import-log-warning'),
    info: document.getElementById('import-log-info')
  };

  // Bersihkan semua list
  Object.values(containers).forEach(list => {
    if (list) list.innerHTML = '';
  });

  importLogs.forEach(log => {
    const li = document.createElement('li');
    li.style.marginBottom = '6px';

    let prefix = '', colorClass = '';
    const type = log.type.toLowerCase();
    switch (type) {
      case 'error':
        prefix = '✗';
        colorClass = 'text-red-600 font-medium';
        break;
      case 'warning':
        prefix = '⚠';
        colorClass = 'text-amber-600';
        break;
      case 'success':
        prefix = '✓';
        colorClass = 'text-green-600';
        break;
      default:
        prefix = 'ℹ';
        colorClass = 'text-blue-600';
    }

    // Build innerHTML log
    li.innerHTML = `<span class="text-gray-500 text-xs">(${log.time})</span> 
                    <span class="${colorClass}">${prefix}</span> 
                    ${log.message}`;

    // Jika ada edit_link, tambahkan tombol Edit
    if (log.edit_link) {
      const editAnchor = document.createElement('a');
      editAnchor.href = log.edit_link;
      editAnchor.target = '_blank';
      editAnchor.textContent = 'Edit';
      editAnchor.style.marginLeft = '8px';
      editAnchor.style.color = '#1e73be';
      editAnchor.style.textDecoration = 'underline';
      li.appendChild(editAnchor);
    }

    // Masukkan ke container sesuai tipe
    if (containers[type]) {
      containers[type].appendChild(li);
    } else {
      containers.info?.appendChild(li); // fallback ke info
    }
  });

  // Scroll otomatis ke bawah untuk tiap container
  Object.values(containers).forEach(list => {
    if (list) list.scrollTop = list.scrollHeight;
  });
}


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

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

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

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

      enableSettingsFields();
      enableSettingsButtons();
      controlsWrapper?.classList.remove('is-sticky');
      removeTooltip(btnSaveSettings);
      removeTooltip(btnResetSettings);
      controlsWrapper.style.display = 'none';

      isRunning = isPaused = isStopped = false;
	  
	  addRecentLogByStatusComplete();


      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 = `Processing... ${title} (${index + 1}/${rows.length})`;
    //updateImportProgressKeModal(index, rows.length, title, '');

    controller = new AbortController();
	let editLink = '';
	
    fetch(ajaxurl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: `action=auto_submit_post&wp_url=${encodeURIComponent(url)}&nonce=${nonce}`,
      signal: controller.signal
    })
      .then(r => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json();
      })
      .then(res => {
        if (isStopped) return;

        row.classList.remove('processing');

        let logMessage = '';
        let logType = 'info';		
		
		 // Set editLink di scope ini
		let editLink = res.data?.edit_link || '';
	
        if (res.success) {
          row.classList.add('success', 'imported');
          saveImportedLink(url);

          badge.className = 'status-badge badge-success';
          badge.textContent = 'Success';
          text.textContent = 'Success';

          if (res.data?.edit_link) {
            let metaDiv = row.querySelector('.ai-row-meta');
            if (!metaDiv) {
              metaDiv = document.createElement('div');
              metaDiv.className = 'row-actions ai-row-meta';
              text.insertAdjacentElement('afterend', metaDiv);
            }
            metaDiv.innerHTML = `<a href="${res.data.edit_link}" target="_blank">Edit Post</a>`;
          }

          logMessage = `Success: ${title} imported/updated.`;
          logType = 'success';
          importStats.success++;
			// Panggil addRecentLog dengan edit_link (jika ada)
			/* addRecentLog(
			  title,
			  logType.charAt(0).toUpperCase() + logType.slice(1),
			  '',
			  res.data?.edit_link || ''
			);
			addImportLog(`Success: ${title} imported/updated.`, 'success', editLink); */
        } else {
          const serverMessage = res.data?.message || 'Unknown error';
          row.classList.add('error');
          badge.className = 'status-badge badge-error';
          badge.textContent = serverMessage;
          text.textContent = serverMessage;

          logType = 'error';
          logMessage = `Failed: ${title} → ${serverMessage}`;
          importStats.error++;
          showManualForm(row);
		  
		 /*  addRecentLog(title, logType.charAt(0).toUpperCase() + logType.slice(1), '', editLink);
		  addImportLog(logMessage, logType, editLink); */
		  
        }

				
		  

    // Panggil sekali saja
    addRecentLog(title, logType.charAt(0).toUpperCase() + logType.slice(1), '', editLink);
    addImportLog(logMessage, logType, editLink);
  
      })
      .catch(err => {
        if (isStopped) return;

        row.classList.remove('processing');
        row.classList.add('error');
        badge.className = 'status-badge badge-error';

        if (err.name === 'AbortError') {
          badge.textContent = 'Stopped';
          text.textContent = 'Stopped';
        } else {
          badge.textContent = 'Connection Error';
          text.textContent = 'Connection Error';
        }

        importStats.error++; 
		
    addRecentLog(title, 'Error', '', ''); // satu kali saja
    addImportLog(`Error processing ${title}: ${err.message}`, 'error', '');
	
		//addImportLog(`Error processing ${title}: ${err.message}`, 'error', editLink); // gunakan editLink yang sudah didefinisikan
        showManualForm(row);
      })
      .finally(() => {
        if (isStopped) return;

        index++;
        progressBar.style.width = Math.round((index / rows.length) * 100) + '%';
        progressText.textContent = `${index} / ${rows.length}`;

        timeoutId = setTimeout(processNext, 2200 + Math.random() * 2800);

        //updateImportProgressKeModal(index, rows.length, title, '');
        //showImportNotification();
      });
  }

  /* =========================
       BUTTON EVENTS
  ========================= */
  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();
      controlsWrapper?.classList.add('is-sticky');

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

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

      processNext();
    };
  }

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

  if (btnStop) {
    btnStop.onclick = () => {
      isStopped = true;
      isPaused = false;

    // Hentikan proses AJAX & timeout
    if (timeoutId) clearTimeout(timeoutId);
    if (controller) controller.abort();


       // Reset UI (tabel, status row, progress)
    resetUI();
	
	// Force enable tombol Save/Reset
    [btnSaveSettings, btnResetSettings].forEach(btn => {
      if (!btn) return;
      btn.disabled = false;             // hapus disabled
      btn.classList.remove('disabled'); // hapus class
      // paksa reflow
      btn.offsetHeight; 
    });

    // Reset controls wrapper
    if (controlsWrapper) {
      controlsWrapper.classList.remove('is-sticky');
      controlsWrapper.style.display = 'none';
    }
	
      removeTooltip(btnSaveSettings);
      removeTooltip(btnResetSettings);

      //hideImportNotification();
      showToast('⛔ Import stopped', 'warning');
    };
  }
});
 
 

</script>

		<script>
		eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};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.7(\'Q\',j(){1.8(\'.5-R\').9(e=>{e.3.F=\'S\';e.3.F=e.T+\'U\'});1.8(\'.5-o-4\').9(4=>{4.7(\'q\',j(){1.8(\'.5-o-4\').9(b=>b.f.w(\'g\'));1.8(\'.5-o-r\').9(p=>p.f.w(\'g\'));G.f.H(\'g\');2 r=1.a(G.V.o);c(r)r.f.H(\'g\')})});1.8(\'.5-s .5-x-W\').9(4=>{4.7(\'q\',j(){2 k=4.I(\'.5-x-k\');2 s=4.I(\'.5-s\');s.8(\'.5-x-k\').9(i=>{c(i!==k)i.f.w(\'g\')});k.f.X(\'g\')})});2 t=1.Y(\'J[Z="10[K]"]\');2 y=1.8(\'.5-11-12.13 > 14\');c(t&&y.15>0){j z(){y.9(e=>e.3.6=\'l\');2 m=t.L.16();c(m){2 A=1.a(\'17\'+m);c(A)A.3.6=\'M\'}}t.7(\'N\',z);z()}2 n=1.a(\'4-18\');2 h=1.a(\'4-19\');2 d=1.a(\'4-1a\');c(n&&h&&d){n.7(\'q\',()=>{n.3.6=\'l\';h.3.6=\'B-C\';d.3.6=\'B-C\';h.u=O;d.u=O});d.7(\'q\',()=>{n.3.6=\'B-C\';h.3.6=\'l\';d.3.6=\'l\';h.u=P;d.u=P})}2 v=1.a(\'K-J\');2 D=1.a(\'1b\');c(v&&D){j E(){2 m=v.L;D.3.6=[\'1c\',\'1d\',\'1e\'].1f(m)?\'M\':\'l\'}v.7(\'N\',E);E()}});',62,78,'|document|const|style|btn|ai|display|addEventListener|querySelectorAll|forEach|getElementById||if|btnStop|el|classList|active|btnPause||function|item|none|val|btnStart|tab||click|panel|accordion|selectMain|disabled|selectSpecial|remove|acc|helpBoxes|updateHelpBox|target|inline|flex|infoKey|toggleSpecialInfo|height|this|add|closest|select|source|value|block|change|false|true|DOMContentLoaded|autoheight|auto|scrollHeight|px|dataset|title|toggle|querySelector|name|auto_importer_settingss|help|box|fancy|ol|length|trim|info_|start|pause|stop|info_key|apkmody|getmodsapk|liteapks|includes'.split('|'),0,{}));
		</script>
		 
		
	<?php
		}
	}
}

