<?php
// =========================
// Tambah menu admin
// =========================
add_action('admin_menu', function() {
    add_menu_page(
        'Search Google Play',            // Page title
        'Search Google Play',            // Menu title
        'manage_options',                // Capability
        'search-google-play',            // Menu slug
        'search_google_play_page',       // Callback
        'dashicons-search',              // Icon
        999                              // Position
    );
});

// =========================
// Callback halaman admin
// =========================
function search_google_play_page() { ?>
    <div class="wrap">
        <h1 style="text-align:center;color:#00d4ff;font-size:2.2rem;">Search Google Play</h1>

        <div class="form-area" style="max-width:800px;margin:0 auto;background:#1a1a1f;padding:20px;border-radius:10px;border:1px solid #333;">
            <label for="app_title" style="display:block;text-align:center;color:#e0e0e0;font-size:1.5rem;margin-bottom:10px;">Enter App Title:</label>
            <input type="text" id="app_title" placeholder="Example: WhatsApp" 
                   style="width:100%;padding:15px;font-size:1.3rem;background:#222;color:white;border:1px solid #444;border-radius:6px;margin-bottom:15px;">
        </div>

        <div id="overlay" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.75);z-index:9999;text-align:center;">
            <div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);color:white;font-size:1.5rem;">
                Loading...
            </div>
        </div>

        <div id="result" style="display:none;background:#111;padding:20px;border-radius:8px;border:1px solid #333;white-space:pre-wrap;font-family:'Courier New', monospace;min-height:200px;margin-top:20px;"></div>
    </div>

    <script>
    const input = document.getElementById('app_title');
    const resultEl = document.getElementById('result');
    const overlay = document.getElementById('overlay');
    let timeout = null;

    input.addEventListener('input', function() {
        clearTimeout(timeout);

        const query = this.value.trim();
        if (!query) {
            resultEl.style.display = 'none';
            return;
        }

        // Delay sebelum trigger AJAX
        timeout = setTimeout(async () => {
            overlay.style.display = 'block';
            resultEl.style.display = 'block';
            resultEl.innerHTML = '';

            try {
                const formData = new FormData();
                formData.append('action', 'search_appid_ajax');
                formData.append('app_title', query);

                const response = await fetch('<?php echo admin_url("admin-ajax.php"); ?>', {
                    method: 'POST',
                    body: formData
                });

                const text = await response.text();
                resultEl.innerHTML = text;
                resultEl.scrollIntoView({ behavior: 'smooth', block: 'end' });

            } catch (err) {
                resultEl.innerHTML = `<span style="color:#ff4d4d;">ERROR: ${err.message}</span>`;
            } finally {
                overlay.style.display = 'none';
            }

        }, 700); // Delay 700ms
    });
    </script>

    <style>
        body { font-family: system-ui, sans-serif; background: #0f0f11; color: #e0e0e0; padding: 20px; line-height: 1.6; }
    </style>
	
	<?php
}

// =========================
// AJAX handler
// =========================
add_action('wp_ajax_search_appid_ajax', 'search_appid_ajax_callback1');

function search_appid_ajax_callback1() {
    if (!isset($_POST['app_title'])) {
        echo "ERROR: App title not found";
        wp_die();
    }

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

    echo "<pre style='white-space:pre-wrap;font-family:Courier New;'>"; 
    echo "===============================\n";
    echo "Search Query: $title\n";
    echo "===============================\n";

    if ($appid) {
        // Ambil data dari Google Play API Nelexa\GPlay
        $link   = $sc->getAppsLink($appid);
        $versi  = $sc->getAppsVersi($appid);
        $poster = $sc->GetAppsPoster($appid);
        echo "✅ AppID Found: $appid\n";
        echo "• Title  : $title\n";
        echo "• Version: " . ($versi ?: 'Not found') . "\n";
        echo "• Poster : " . ($poster ?: 'Not found') . "\n";
        echo "• Link   : " . ($link ?: 'Not found') . "\n";

    } else {
        echo "❌ AppID not found or blocked by Google Play\n";
    }

    echo "===============================\n";
    echo "</pre>";
	//$debugGoogleSnippet = $sc->debugGoogleSnippetMulti($appid, 'apkgk.com', 'apkcombo.com', 'apkpure.com', 'apkfab.com');

    //echo "• debugGoogleSnippet   : " . $debugGoogleSnippet . "\n";
    wp_die();
}
