<?php
if ( ! defined( 'ABSPATH' ) ) exit; 
// Silence is golden.
if (!function_exists('file_get_html')) {
require_once get_template_directory().'/libs/addons/inc/dom.php';
}
function debug_extract_from_grid($html)
{
    echo "<pre>";
    echo "=== DEBUG EKSTRAK APKDone GAME CARDS (2026 Stable Version) ===\n\n";

    if (empty($html)) {
        echo "HTML kosong!\n</pre>";
        return;
    }

    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NOBLANKS);
    libxml_clear_errors();

    $xpath = new DOMXPath($dom);

    // Cek grid container (hanya info, tidak wajib)
    $gridQuery = "//div[contains(concat(' ', @class, ' '), ' grid ') and contains(@class, 'gap-x-4') and contains(@class, 'grid-cols-2')]";
    $grids = $xpath->query($gridQuery);
    echo "Jumlah GRID container: " . $grids->length . " (normal jika >0)\n";

    // Target semua app-card (paling reliable)
    $cards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' app-card ')]");
    echo "Jumlah APP-CARD ditemukan: " . $cards->length . "\n\n";

    if ($cards->length === 0) {
        echo "❌ Tidak menemukan .app-card! Kemungkinan:\n";
        echo "1. Halaman tidak punya konten game\n";
        echo "2. Konten di-load via JS (perlu headless browser)\n";
        echo "3. Proxy gagal atau situs blokir\n";
        echo "Saran: Simpan full HTML & inspect manual.\n</pre>";
        return;
    }

    $i = 1;
    foreach ($cards as $card) {
        if ($i > 10) break; // batasi output debug

        // Judul & Link (prioritas dari h3 > a utama > fallback text)
        // Di dalam loop foreach ($cards as $card)

// Prioritas 1: Ambil dari h3.app-card-title a (paling reliable)
$titleNode = $xpath->query(".//h3[contains(@class, 'app-card-title')]//a", $card);

if ($titleNode->length > 0) {
    $judul = trim($titleNode->item(0)->textContent);
    $link  = trim($titleNode->item(0)->getAttribute('href'));
} else {
    // Fallback kalau h3 hilang (jarang terjadi)
    $aFallback = $xpath->query(".//a[@href and (contains(@class, 'ratio-thumb') or contains(text(), ' '))]", $card);
    if ($aFallback->length > 0) {
        $node = $aFallback->item(0);
        $link  = trim($node->getAttribute('href'));
        $judul = trim($node->getAttribute('title') ?: $node->textContent);
        if (empty($judul)) {
            // Ultimate fallback dari img alt
            $img = $xpath->query(".//img", $card)->item(0);
            $judul = $img ? trim($img->getAttribute('alt')) : 'Tidak terdeteksi';
        }
    } else {
        $judul = 'Tidak terdeteksi';
        $link  = '';
    }
}

        // Poster: prioritaskan data-src (lazy load), lalu src
        $img = $xpath->query(".//img[contains(@class, 'ratio-media')]", $card);
        $poster = '(tidak ada poster)';
        if ($img->length > 0) {
            $imgNode = $img->item(0);
            $poster = $imgNode->getAttribute('data-src') ?: $imgNode->getAttribute('src') ?: '(src kosong)';
            // Optional: ambil alt jika link/judul gagal
            if ($judul === 'Tidak terdeteksi') {
                $judul = trim($imgNode->getAttribute('alt') ?: $judul);
            }
        }

        // Versi & Mods: kumpulkan semua chip-text di meta
        $metaSpans = $xpath->query(".//div[contains(@class, 'app-card-meta')]//span[contains(@class, 'chip-text')]", $card);
        $versiParts = [];
        foreach ($metaSpans as $span) {
            $text = trim($span->textContent);
            if ($text !== '') $versiParts[] = $text;
        }
        $versi = !empty($versiParts) ? implode(' | ', $versiParts) : 'tidak terdeteksi';

        echo "Game #$i\n";
        echo "Judul : $judul\n";
        echo "Link  : $link\n";
        echo "Poster: $poster\n";
        echo "Versi : $versi\n";
        echo str_repeat('-', 70) . "\n\n";

        $i++;
    }

    echo "Tips: Jika poster pakai lazy load, selalu prioritaskan data-src.\n";
    echo "Untuk production: return array hasil daripada echo.\n";
    echo "=== DEBUG SELESAI ===\n";
    echo "</pre>";
}


function debug_apkdone_games($html)
{
    echo "<pre>";
    echo "=== DEBUG APKDone Games ===\n\n";

    if (empty($html)) {
        echo "HTML kosong\n</pre>";
        return;
    }

    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    libxml_clear_errors();

    $xpath = new DOMXPath($dom);

    // Cari semua app-card
    $cards = $xpath->query("//div[contains(@class,'app-card')]");

    echo "Jumlah game card ditemukan: " . $cards->length . "\n\n";

    if ($cards->length === 0) {
        echo "❌ Tidak ada game ditemukan\n";
        echo "Kemungkinan:\n";
        echo "- HTML tidak lengkap\n";
        echo "- Body dikosongkan oleh Cloudflare / JS protection\n";
        echo "</pre>";
        return;
    }

    $i = 1;
    foreach ($cards as $card) {
        if ($i > 6) break; // batasi debug

        // LINK
        $linkNode = $xpath->query(".//div[contains(@class,'app-card-thumb')]//a", $card);
        $link = $linkNode->length ? $linkNode->item(0)->getAttribute('href') : '';

        // POSTER & JUDUL
        $imgNode = $xpath->query(".//img", $card);
        $poster = $imgNode->length ? $imgNode->item(0)->getAttribute('src') : '';
        $judul  = $imgNode->length ? $imgNode->item(0)->getAttribute('alt') : '';

        // VERSI
        $versiNode = $xpath->query(".//div[contains(@class,'app-card-meta')]/span[1]", $card);
        $versi = $versiNode->length ? trim($versiNode->item(0)->nodeValue) : 'tidak terdeteksi';

        echo "Game #$i\n";
        echo "Judul : $judul\n";
        echo "Link  : $link\n";
        echo "Poster: $poster\n";
        echo "Versi : $versi\n";
        echo str_repeat('-', 60) . "\n";

        $i++;
    }

    echo "</pre>";
}


/**
 * Fungsi debug sederhana untuk scrape https://apkdone.com/game/
 * Menampilkan hasil ekstraksi judul, link, versi (poster kosong karena tidak ada di listing)
 */
function debug_code_apkdone($url, $paged = 1)
{
 
    // ==============================================
    // 1. Fetch HTML dengan file_get_contents
    // ==============================================
    $context_options = [
        'http' => [
            'method'          => 'GET',
            'timeout'         => 10,
            'follow_location' => true,
            'header'          => implode("\r\n", [
                'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Referer: https://www.google.com/',
            ]),
        ],
        'ssl' => [
            'verify_peer'     => false,
            'verify_peer_name' => false,
        ]
    ];

    $context = stream_context_create($context_options);
    $html = @file_get_contents($url, false, $context);

    // Retry dengan UA berbeda
    if (empty($html) || strlen($html) < 1000) {
        echo "Retry dengan User-Agent alternatif...\n";
        $context_options['http']['header'] = implode("\r\n", [
            'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130 Safari/537.36',
            'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
            'Accept-Language: en-US,en;q=0.5',
            'Referer: https://www.google.com/',
        ]);
        $context = stream_context_create($context_options);
        $html = @file_get_contents($url, false, $context);
    }

    if (empty($html) || strlen($html) < 1000) {
        echo "GAGAL: Tidak bisa mengambil halaman (kemungkinan blokir IP atau Cloudflare).\n";
        echo "Saran: Coba pakai proxy/VPN atau cek koneksi.\n";
        echo "</pre>";
        return;
    }

    echo "Berhasil ambil HTML! Panjang: " . number_format(strlen($html)) . " karakter\n\n";

    // Tampilkan potongan awal HTML untuk verifikasi
    echo "=== 1500 karakter pertama HTML ===\n";
    echo htmlspecialchars(substr($html, 0, 1500)) . "\n";
    echo str_repeat('-', 80) . "\n\n";

    // ==============================================
    // 2. Regex ekstraksi pola Markdown-like
    // ==============================================
    $pattern = '/###\s*\[([^]]+)\]\((https?:\/\/apkdone\.com\/[^)]+\/)\)\s*(?:\[([^]]+)\]\([^)]+\)\s*)?([^<\r\n]+)/i';

    preg_match_all($pattern, $html, $matches, PREG_SET_ORDER);

    $total_items = count($matches);

    echo "Jumlah game ditemukan: $total_items\n\n";
 

    // Tampilkan 10 game pertama sebagai contoh
    echo "=== 10 GAME PERTAMA (contoh) ===\n\n";
    $i = 1;
    foreach ($matches as $match) {
        if ($i > 10) break;

        $title = trim(html_entity_decode($match[1]));
        $link  = trim($match[2]);
        $versi = trim(preg_replace('/\s+/', ' ', $match[4] ?? 'Tidak terdeteksi'));

        echo "Game #$i\n";
        echo "Judul : $title\n";
        echo "Link  : $link\n";
        echo "Versi : $versi\n";
        echo "Image : (tidak tersedia di listing utama)\n";
        echo str_repeat('-', 70) . "\n";

        $i++;
    }

    if ($total_items > 10) {
        echo "... dan " . ($total_items - 10) . " game lainnya.\n";
    }

    echo "\n=== DEBUG SELESAI ===\n";
    echo "</pre>";
}

function debug_apkdone_file_get_html($url = 'https://apkdone.com/game/')
{
    echo "<pre style='background:#000; color:#0f0; padding:15px; font-family:monospace;'>";
    echo "=== DEBUG APKDone Games - Fixed Version (Jan 2026) ===\n";
    echo "URL: $url\n";
    echo "Waktu: " . date('Y-m-d H:i:s') . "\n\n";

    // Fetch HTML
    $context = stream_context_create([
        'http' => [
            'method'  => 'GET',
            'timeout' => 20,
            'header'  => implode("\r\n", [
                'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Referer: https://www.google.com/',
            ]),
        ],
        'ssl' => [
            'verify_peer'      => false,
            'verify_peer_name' => false,
        ]
    ]);

    $html_raw = @file_get_contents($url, false, $context);

    if ($html_raw === false || strlen($html_raw) < 50000) {  // minimal 50KB untuk halaman game penuh
        echo "GAGAL ambil halaman lengkap! Panjang hanya " . strlen($html_raw ?? 0) . " karakter.\n";
        echo "</pre>";
        return;
    }

    echo "Berhasil ambil HTML! Panjang: " . number_format(strlen($html_raw)) . " karakter\n\n";

    // Parse dengan Simple HTML DOM
    $html = str_get_html($html_raw);
    if (!$html) {
        echo "GAGAL parse HTML!\n";
        echo "</pre>";
        return;
    }

    // Ekstrak semua app-card (ini yang penting!)
    $cards = $html->find('div.app-card');

    $total_cards = count($cards);
    echo "Jumlah div.app-card ditemukan: $total_cards\n";
    echo "(312 seperti debug kamu → ini normal dan benar!)\n\n";

    if ($total_cards === 0) {
        echo "Tidak ada app-card → kemungkinan konten JS-loaded.\n";
        echo "</pre>";
        return;
    }

    echo "=== Ekstraksi 10 Game Pertama dari app-card ===\n\n";

    $i = 1;
    foreach ($cards as $card) {
        if ($i > 10) break;

        // Judul & Link (prioritas dari h3.app-card-title a)
        $title_a = $card->find('h3.app-card-title a', 0);
        $judul = $title_a ? trim($title_a->plaintext) : 'Tidak terdeteksi';
        $link  = $title_a ? trim($title_a->href) : '';

        // Poster (data-src atau src dari img.ratio-media)
        $img = $card->find('img.ratio-media', 0);
        $poster = '(tidak ada poster)';
        if ($img) {
            $poster = $img->getAttribute('data-src') ?: $img->getAttribute('src') ?: '(src kosong)';
            // Fallback judul dari alt jika gagal
            if ($judul === 'Tidak terdeteksi') {
                $judul = trim($img->alt ?: $judul);
            }
        }

        // Versi & Mod (semua span.chip-text di .app-card-meta)
        $meta_spans = $card->find('div.app-card-meta span.chip-text');
        $versi_parts = [];
        foreach ($meta_spans as $span) {
            $text = trim($span->plaintext);
            if ($text) $versi_parts[] = $text;
        }
        $versi = !empty($versi_parts) ? implode(' | ', $versi_parts) : 'tidak terdeteksi';

        echo "Game #$i\n";
        echo "Judul : $judul\n";
        echo "Link  : $link\n";
        echo "Poster: $poster\n";
        echo "Versi : $versi\n";
        echo str_repeat('-', 70) . "\n\n";

        $i++;
    }

    echo "... dan " . ($total_cards - 10) . " game lainnya (total $total_cards).\n";
    echo "\n=== DEBUG SELESAI - Gunakan kode ini untuk produksi ===\n";
    echo "</pre>";

    $html->clear();
    unset($html);
}

/**
 * Debug scrape https://apkdone.com/game/ menggunakan file_get_html() + Simple HTML DOM
 * Menampilkan hasil ekstraksi judul, link, versi, dan poster (jika ada)
 */
function debug_apkdone_file_get_html111($url = 'https://apkdone.com/game/')
{
    echo "<pre style='background:#000; color:#0f0; padding:15px; font-family:monospace;'>";
    echo "=== DEBUG file_get_html() - APKDone Games Listing ===\n";
    echo "URL: $url\n";
    echo "Waktu: " . date('Y-m-d H:i:s') . "\n\n";

    // ==============================================
    // 1. Fetch HTML dengan file_get_contents + Simple HTML DOM
    // ==============================================
    $context = stream_context_create([
        'http' => [
            'method' => 'GET',
            'timeout' => 15,
            'header' => implode("\r\n", [
                'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
            ]),
        ],
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false,
        ]
    ]);

    $html_raw = @file_get_contents($url, false, $context);

    if ($html_raw === false || strlen($html_raw) < 1000) {
        echo "GAGAL mengambil halaman!\n";
        echo "Error: " . (error_get_last()['message'] ?? 'Unknown') . "\n";
        echo "Saran: Cek koneksi, proxy, atau blokir IP.\n";
        echo "</pre>";
        return;
    }

    echo "Berhasil ambil HTML! Panjang: " . number_format(strlen($html_raw)) . " karakter\n\n";

    // Load dengan simple_html_dom
    $html = str_get_html($html_raw);

    if (!$html) {
        echo "GAGAL parse HTML dengan Simple HTML DOM!\n";
        echo "</pre>";
        return;
    }

    echo "HTML berhasil diparse dengan Simple HTML DOM\n\n";

    // ==============================================
    // 2. Coba ekstrak berdasarkan struktur app-card (untuk test apakah ada)
    // ==============================================
    $cards = $html->find('div.app-card');

    echo "Jumlah elemen div.app-card ditemukan: " . count($cards) . "\n";
    echo "(Jika 0 → struktur bukan app-card lagi, sesuai kondisi situs 2026)\n\n";

    // ==============================================
    // 3. Ekstraksi alternatif: fallback ke text pattern (Markdown-like)
    //    karena situs sekarang pakai pola teks heading
    // ==============================================
    echo "=== Mencoba ekstrak pola text-based (### [Judul](link) Versi) ===\n\n";

    // Ambil semua teks plain dari body
    $plain_text = $html->plaintext;

    // Pola regex untuk tangkap ### [Judul](link) lalu versi
    $pattern = '/###\s*?\[([^\]]+?)\]\((https?:\/\/apkdone\.com\/[^)]+?\/)\)\s*?(?:\[([^\]]+?)\]\([^)]+?\)\s*?)?([^<>\r\n]{5,100})/i';

    preg_match_all($pattern, $html, $matches, PREG_SET_ORDER);

	$pattern234 = '/###\s*?\[([^\]]+?)\]\((https?:\/\/apkdone\.com\/[^)]+?\/)\)\s*?(?:\[([^\]]+?)\]\([^)]+?\)\s*?)?([^<>\r\n]{5,100})/is';

	preg_match_all($pattern, $html, $matches, PREG_SET_ORDER);

    $total = count($matches);

    echo "Jumlah game ditemukan dengan pola text: $total\n\n";

    if ($total > 0) {
        $i = 1;
        foreach ($matches as $m) {
            if ($i > 10) break;

            $judul = trim(html_entity_decode($m[1]));
            $link  = trim($m[2]);
            $versi = trim(preg_replace('/\s+/', ' ', $m[4] ?? 'Tidak terdeteksi'));

            echo "Game #$i\n";
            echo "Judul : $judul\n";
            echo "Link  : $link\n";
            echo "Versi : $versi\n";
            echo "Poster: (tidak tersedia di listing utama)\n";
            echo str_repeat('-', 70) . "\n\n";

            $i++;
        }

        if ($total > 10) {
            echo "... dan " . ($total - 10) . " game lainnya.\n";
        }
    } else {
        echo "Tidak menemukan pola text-based juga.\n";
        echo "Saran: Cek manual di browser → inspect element → lihat apakah konten ada di HTML mentah atau di-load JS.\n";
    }

    // Bersihkan memory
    $html->clear();
    unset($html);

    echo "\n=== DEBUG SELESAI ===\n";
    echo "</pre>";
}

function apkdone() {
/**
 * ===============================
 * PHP & REQUEST CONFIG
 * Ambil option/theme global WordPress
 * Tampilkan error sesuai konstanta ERRORS
 * ===============================
*/ 
global $opt_themes;
@ini_set('display_errors', ERRORS);

/**
 * ===============================
 * LOAD CSS VIA SHORTCODE
 * ===============================
*/
echo do_shortcode('[css]');

/**
 * ===============================
 * INIT CLASS
 * Class untuk HTTP / CURL
 * Class utama struktur & scraper
 * ===============================
*/
$Go_Curl = new Go_Curl();
$sc = new StructurCode();

/**
 * ===============================
 * BASIC CONFIG
 * Post type yang akan digunakan
 * Source website target
 * Contoh URL demo (single post)
 * Ambil host saja dari URL demo
 * ===============================
*/
$types   = 'post';
$sources = 'apkdone.com';
$demos   = 'https://apkdone.com/minecraft-game-mod/';
$demosx  = 'https://' . parse_url($demos)['host'];

/**
 * ===============================
 * CONNECTION CHECK
 * Cek apakah domain source bisa diakses
 * ===============================
*/
$checkx = $Go_Curl->http_responsex($demosx);

/**
 * ===============================
 * API KEY SCRAPER
 * Ambil API key scraper dari option theme
 * ===============================
*/
$keyz = $opt_themes['api_key_scrape'];
 
/**
 * ===============================
 * URL & STATUS CHECK
 * Base protocol + source
 * Cek status HTTP URL demo (200 / 403 / 404)
 * ===============================
*/
$protocol = 'https://' . $sources;
$status = $Go_Curl->http_responsex($demos);
$sc_page     = 'sc-5play';
$apikey = $sc->scrape_do_tokens(); 
   
/* echo '<pre>';
print_r($sc->debug_file_get_contents($demos));
echo '</pre>'; */

 
 
//debug_apkdone_file_get_html('https://apkdone.com/game/');
?> 
<?php 

$target_url = 'https://an1.com/7537-grand-hotel-mania-mod.html';

echo "<pre>";
echo "===============================\n";
echo "Mencoba scrape: $target_url\n";
echo "===============================\n";

$data = $sc->fetchWithCloudflareBypass($target_url);

if (!$data['success']) {
    echo "FAILED ❌\n";
    echo "Error: {$data['error']}\n";
} else {
    echo "SUCCESS ✅\n";
    echo "HTML Length : " . number_format($data['html_length']) . " character\n";
    echo "===============================\n";
    echo "• Title	: {$data['title']}\n";
    echo "• H1	: {$data['h1']}\n";
    echo "• Mod	: {$data['mod_features']}\n";
    echo "• Size	: {$data['size']}\n";
    echo "• Download : {$data['download_link']}\n";
    echo "===============================\n";
    echo "• Desc	: {$data['description']}\n";

    if (!empty($data['response_hdr'])) {
        echo "===============================\n";
        echo "• Response Headers:\n";
        foreach ($data['response_hdr'] as $hdr) {
            echo "  $hdr\n";
        }
        echo "===============================\n";
    }
}

echo "</pre>"; 

	?>
	 


	<div class="wrap">
	<div class="play_menu" style="text-transform:uppercase">
        <b>Add sources from <?php echo parse_url($protocol)['host']; ?></b>
	</div> 
	</div> 
	 
	 


	<div style="clear:both"></div>	
    
	<div class="wrap" id="play_fixed" >
	<div class="play_menu" style="margin-bottom: 10px;">
		<ul id="menunya" class="play_menus" style="text-transform:capitalize">
		<li data-tab="tab1"><a><i class="fa fa-home"></i> Home </a></li>  
		<li data-tab="tab2"><a><i class="fa fa-rss"></i> Latest </a></li>  
		</ul>
		<div style="clear:both"></div>
	</div>
	</div>
  
    
	<div class="containerX">
		<div class="tab-content">

		<div id="tab1" class="tab-pane fade">    
		1
		</div>     

		<div id="tab1" class="tab-pane fade">
			
		<div class="play_menu" style="text-transform:uppercase"><b>Latest Games </b></div>		
		
		2

		</div> 
		
		</div>
	</div>
	
<?php 
echo do_shortcode( '[ft_menu]' );
echo do_shortcode( '[ft_js]' ); 
}
