<?php

 
if (!function_exists('manual_post_page')) 
{
    function manual_post_page() 
	{ 
        $sc        = new StructurCode();
		
        if (defined('DOING_AJAX') && DOING_AJAX) return;
		
        /* ================= SETTINGS ================= */  
        $default_sources  = auto_importer_default_sources();
        $default_settings = auto_importer_default_settings();
        $settings = wp_parse_args(get_option('auto_importer_settingss', []), $default_settings);
		/* 
		$apps = $sc->getAllAppIDSearch('LUDUS');

		echo '<pre>';
		print_r($apps);
		echo '</pre>'; 
		*/
		 
		/* 
		$hasil = $sc->getAllAppIDSearch('whatsapp');
		echo '<pre>';
		print_r($hasil);
		echo '</pre>';  
		*/

		?>
 
 
        <div class="wrap">
            <h1 class="wp-heading-inline"><?php _e('Manual Importer', TEXT_DOMAIN); ?></h1>

            <hr class="wp-header-end">

            <div class="two-col">
                <div class="settings-col col-1">
					<?php 
					//echo $sc->renderImporterSettingsPostbox($settings, $default_sources);
					echo $sc->render_search_all_form_submit_box(); 
					echo $sc->render_manual_submit_box($settings); 
					?>
                </div>
				
                <div class="settings-col col-2">
					<?php echo $sc->renderHelpTabsSection(); ?>
                </div>
				
            </div>

			<?php
            //echo $sc->renderImportControlsAndProgress($count);
            //echo $sc->renderImportPostList($count, $items, $sc, $settings);
            ?>
        </div>
	<?php 
	}
}

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

        if (!class_exists('Go_Curl')) {
            echo '<div class="notice notice-error">
                <p><strong>Go_Curl class not found.</strong> Importer disabled.</p>
            </div>';
            return;
        }

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

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

        // Validasi source
        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;
        }

        $base_url = trailingslashit($settings['base_url']);

        if ($failsafe) return;

        /* ================= SCRAPING DATA ================= */
        $source = trim($settings['source'] ?? '');

        // Mapping source ke method Auto
        $source_to_method = [
            '5play'      => '5play',
            'getmodsapk' => 'Getmodsapk',
            'apkmody'    => 'Apkmody',
            'liteapks'   => 'Liteapks',
        ];

        $items = [];
        $count = 0;
		//Code_Apkmody_Auto
        if (isset($source_to_method[$source]) && $source !== 'custom') {
            $method_name = 'Code_' . $source_to_method[$source] . '_Auto';

            if (method_exists($sc, $method_name)) {
                $result = $sc->$method_name($base_url, $Go_Curl);

                if (isset($result['status']) && $result['status'] !== 'error') {
                    $items = $result['items'] ?? [];
                    $count = $result['count'] ?? count($items);
                } else {
                    // Error sudah ditangani di dalam method Auto → cukup return
                    return;
                }
            } else {
                error_log("Method '$method_name' not found for source '$source'");
                echo '<div class="notice notice-error">
                    <p>Parser for source <strong>' . esc_html($source) . '</strong>  not available.</p>
                </div>';
                return;
            }
        } elseif ($source === 'custom') {
            // Custom source → bisa ditambahkan logika khusus di sini nanti
            echo '<div class="notice notice-info">
                <p>Custom source selected. Please use custom parser.</p>
            </div>';
        } else {
            echo '<div class="notice notice-error">
                <p>Source is invalid or unsupported.</p>
            </div>';
            return;
        }

        /* ================= NONCE & RENDER ================= */
        wp_nonce_field('auto_submit_post', 'nonce');
 
        ?>
		  
        <div class="wrap">
            <h1 class="wp-heading-inline"><?php _e('Auto Importer', TEXT_DOMAIN); ?></h1>
            <hr class="wp-header-end">

            <div class="two-col">
                <div class="settings-col col-1">
					<?php 
					echo $sc->renderImporterSettingsPostbox($settings, $default_sources);
					echo $sc->render_search_all_form_submit_box(); 
					echo $sc->render_manual_submit_box($settings); 
					?>
                </div>
				
                <div class="settings-col col-2">
					<?php echo $sc->renderHelpTabsSection(); ?>
                </div>
            </div>

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

<script>
document.addEventListener('DOMContentLoaded', function () {

    function updateStatus(index, text, cls) {
        const row = document.querySelector('tr[data-index="' + index + '"]');
        if (!row) return;

        const badge = row.querySelector('.status-badge');
        const statusText = row.querySelector('.status-text');

        if (badge) {
            badge.textContent = text;
            badge.className = 'status-badge ' + cls;
        }
        if (statusText) {
            statusText.textContent = text;
        }
    }

    document.querySelectorAll('.ai-manual-submit-btn').forEach(btn => {
        btn.addEventListener('click', function () {

            const button = this;
            const form   = button.closest('.ai-auto-submit-form');
            const url    = form.dataset.url;
            const index  = form.dataset.index;
            const nonce  = form.querySelector('input[name="nonce"]').value;
            const td     = form.closest('td');

            // 🔒 Disable button
            button.disabled = true;
            const originalText = button.textContent;
            button.textContent = '⏳ Processing...';

            updateStatus(index, 'Processing...', 'badge-processing');

            fetch(ajaxurl, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: new URLSearchParams({
                    action: 'manual_submit_post',
                    url: url,
                    nonce: nonce
                })
            })
            .then(r => r.json())
            .then(res => {
                if (res.success) {

                    updateStatus(index, 'Done', 'badge-success');

                    const postId = res.data?.post_id || 0;

                    if (postId && td) {
                        td.innerHTML = `
                            <a href="post.php?post=${postId}&action=edit"
                               class="button button-secondary"
                               target="_blank">
                                ✏️ Edit Post
                            </a>
                        `;
                    } else {
                        td.innerHTML = '<span class="text-muted">Imported</span>';
                    }

                } else {
                    // ❌ Failed → enable kembali
                    updateStatus(index, 'Failed', 'badge-error');
                    button.disabled = false;
                    button.textContent = originalText;
                    console.error(res);
                }
            })
            .catch(err => {
                updateStatus(index, 'Error', 'badge-error');
                button.disabled = false;
                button.textContent = originalText;
                console.error(err);
            });

        });
    });

});
</script>

<style>
.status-badge {
    padding: 4px 8px;
    border-radius: 4px;
    font-weight: 600;
}
.badge-waiting { background:#ccd0d4; }
.badge-processing { background:#ffb900; }
.badge-success { background:#46b450; color:#fff; }
.badge-error { background:#dc3232; color:#fff; }
</style>

	<?php
    }
}

