<?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,
		];
	}
} 
 