<?php
 
add_action('wp_ajax_submit_game', 'submit_game_insert_post');

function submit_game_insert_post() {
    global $opt_themes;

    check_ajax_referer('submit_game_nonce', 'nonce');

    // Security: Hanya admin
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Access for Administrator only']);
    }

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

    try {
        // 1. Lakukan scraping
        require_once get_template_directory() . '/libs/addons/includes/class/5play.class.php';
        $scraper = new scrapes;
        $gets_data = $scraper->scrape_web_info($url, false);

        if (!$gets_data || !empty($gets_data['error'])) {
            wp_send_json_error([
                'message' => 'Scrape failed:' . ($gets_data['error'] ?? 'Unknown error')
            ]);
        }

        // 2. Load class importer (pastikan file class sudah di-include)
        // Jika class ada di file terpisah, include dulu:
        // require_once get_template_directory() . '/libs/addons/includes/class-apk-post-importer.php';

        // 3. Buat instance dan jalankan import
        //$importer = new APK_Post_Importer($gets_data, $opt_themes);
		$importer = new APK_Importer($gets_data); 

        //$result = $importer->run();		
		$result = $importer->import();
		
		$post_id = (int) $result;	
        //$post_id = $importer->get_post_id();
	
		// === Start Source download ===
		$download_info_link = array();

		$count = count($gets_data['downloadlinks_gma']);

		for ($i = 0; $i < $count; $i++) {
			// Lewati jika link utama kosong
			$original_url = trim($gets_data['downloadlinks_gma'][$i] ?? '');
			if (empty($original_url)) {
				continue;
			}

			$original_url = esc_url_raw($original_url);

			if (!empty($gets_data['size_downloadlinks_gma'])) {
				$size_display = wp_strip_all_tags($gets_data['size_downloadlinks_gma'][$i]);
			} elseif (!empty($gets_data['size_sc'])) {
				$size_display = wp_strip_all_tags($gets_data['size_sc']);
			} elseif (!empty($gets_data['sizes_GP'])) {
				$size_display = wp_strip_all_tags($gets_data['sizes_GP']);
			} else {
				$size_display = wp_strip_all_tags($gets_data['sizes_GP'] ?? '');
			}
			
			$full_url_or_path 	= $gets_data['types_downloadlinks_gma'][$i] ?? $gets_data['downloadlinks_gma'][$i] ?? '';

			$filename 		= basename(parse_url($full_url_or_path, PHP_URL_PATH));
			$extension 		= pathinfo($filename, PATHINFO_EXTENSION);
			$types_dw 		= !empty($extension) ? strtoupper($extension) : '';

			if($opt_themes['import_apk']){	 
			
			$attach_id		= upload_remote_file_apk( $original_url, $post_id ); 
				
			if ( is_wp_error( $attach_id ) ) {
				echo 'Error: ' . $attach_id->get_error_message();
				error_log( 'APK Upload Failed [' . $post_id . ']: ' . $attach_id->get_error_message() );
				$final_url 	= esc_url_raw( $original_url );
			} else {
				error_log( 'File uploaded! Attachment ID [' . $post_id . ']: ' . wp_get_attachment_url( $attach_id ) );
				echo 'File uploaded! Attachment ID: ' . $attach_id . '<br>';
				echo 'URL: ' . wp_get_attachment_url( $attach_id );
				$final_url 	= wp_get_attachment_url( $attach_id );
			}
				
			} else {
				$final_url = esc_url_raw( $original_url );
			}
 
			// Pastikan URL akhir valid		
			$link_url 	= $importer->shorten_links($final_url);	
			//$link_url 	= $final_url;
			
			//print_r($importer->get_image_url());
			//print_r($attach_id);
			 
			// === Bangun data link ===
			$download_info_link[] = array(
				'name'   => sanitize_text_field($gets_data['name_downloadlinks_gma'][$i] ?? ''),
				'title'  => sanitize_text_field($gets_data['name_downloadlinks_gma'][$i] ?? ''),
				'url'    => $link_url,
				'links'  => $link_url,
				'size'   => $size_display,
				'tipes'  => $types_dw,
				'notes'  => sanitize_text_field($gets_data['notes_downloadlinks_gma'][$i] ?? ''),
			);
		}

		// === Simpan ke post meta (HANYA SEKALI di luar loop!) ===
		if (!empty($download_info_link)) {
			update_post_meta($post_id, 'repeatable_fields', $download_info_link);
			update_post_meta($post_id, 'group_downloads_links', $download_info_link);
		}
		
		$importer->add_direct_apk_download();	
		
		// === Stop Source download ===
		
		//$impot_link->add_direct_apk_download();	
		  
		if (is_wp_error($result) && $result->get_error_code() === 'duplicate_found') {
			$post_id = $result->get_error_data()['post_id'] ?? 0;
			wp_send_json_error([
				'message'      => $result->get_error_message(),
				'is_duplicate' => true,
				'existing_id'  => $post_id,
				'edit_link'    => $post_id ? get_edit_post_link($post_id, '') : '',
				'title'        => $post_id ? get_the_title($post_id) : ''
			]);
		}


        /* if (is_wp_error($result)) {
            wp_send_json_error([
                'message' => $result->get_error_message()
            ]);
        } */
	
        // Sukses!

        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 created/updated'
        ]);

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

// =============================================
// Auto Importer Page
// =============================================
function play5_auto() {
    if (defined('DOING_AJAX') && DOING_AJAX) return;

    $Go_Curl = new Go_Curl();
    $paged = max(1, (int)($_GET['games'] ?? 1));

    $url = $paged > 1
        ? "https://5play.org/en/android/games/page/{$paged}/"
        : "https://5play.org/en/android/games/";

    $html = $Go_Curl->file_get_contents_curlx($url);

    if (!$html) {
        echo '<div class="alert alert-danger">Failed to load page from 5play.org</div>';
        return;
    }
	
	/* 
    // Ambil block list game
	preg_match('#<div class="glist app-list">(.*?)<div class="navigation"#s', $html, $m);
	$block = $m[1] ?? $html; // fallback ambil seluruh HTML jika pattern gagal

	// Ambil semua judul
	preg_match_all('#<span class="title">(.*?)</span>#is', $block, $judul);
	// Ambil link game (href) dengan benar
	preg_match_all('#<a[^>]+href="(https://5play.org/[^"]+)"#is', $block, $link);

	$judul = $judul[1] ?? [];
	$link  = $link[1] ?? []; 
	*/
	
    // Ambil block list game
	$block 		= preg_match('#<div class="glist app-list">(.*?)<div class="navigation fc">#s', $html, $m) ? $m[1] : '';
	if (empty($block)) {
	$msg 		= '<div class="alert alert-warning">No games found – layout may have changed.</div>';
	if ($is_ajax) { echo $msg; exit; } else { die($msg); }
	}
	// Extract data (same as before)
	preg_match_all('#<span class="title">(.*?)</span>#is', $block, $judul);
	$judul 		= $judul[1];
	preg_match_all('#<a.*?href="(.*?)\".*?>#is', $block, $link);
	$link 		= $link[1];
	preg_match_all('#<img.*?src="(.*?)".*?>#is', $block, $img);
	$img 		= $img[1];
	preg_match_all('#<span class="meta meta-vers">.*?<i class="meta-item">(.*?)<\/i>#is', $block, $versi);
	$versi 		= $versi[1];
	// Sync arrays

    $count = min(count($judul), count($link));

    if ($count === 0) {
        echo '<div class="alert alert-warning">No games found on this page</div>';
        return;
    }
    ?>
	 <?php wp_nonce_field('submit_game_nonce', 'submit_game_nonce'); ?>
 <?php
// ... (kode scraping & extract data tetap sama seperti sebelumnya)

// Output HTML
?>

<div class="wrap">
    <h1 class="wp-heading-inline">Auto Importer 5play.org – Page <?php echo $paged; ?></h1>
    <span class="subtitle">Total: <?php echo $count; ?> games</span>

    <!-- Controls -->
    <div class="import-controls-wrapper">
        <div class="import-controls">
            <button id="btn-start" class="import-btn primary">
                <span class="dashicons dashicons-controls-play"></span>
                <span class="label">Mulai Import</span>
            </button>

            <button id="btn-pause" class="import-btn secondary" disabled>
                <span class="dashicons dashicons-controls-pause"></span>
                <span class="label">Pause</span>
            </button>

            <button id="btn-stop" class="import-btn danger" disabled>
                <span class="dashicons dashicons-no-alt"></span>
                <span class="label">Stop</span>
            </button>
        </div>
    </div>

    <!-- Progress Bar (default disembunyikan) -->
    <div class="progress-container" id="progress-container">
        <div class="progress-header">
            <strong>Progress Import</strong>
            <span id="progress-text">0 / <?php echo $count; ?></span>
        </div>
        <div class="progress-bar-wrapper">
            <div id="progress-bar"></div>
        </div>
        <div id="current-game" style="margin-top:10px; min-height:22px;"></div>
    </div>

    <!-- Tabel daftar game -->
    <table class="wp-list-table widefat fixed striped posts">
        <thead>
            <tr>
                <td class="manage-column column-cb check-column"></td>
                <th class="manage-column column-thumb">Image</th>
                <th class="manage-column column-title column-primary">Judul</th>
                <th class="manage-column column-source">Sumber</th>
                <th class="manage-column column-status">Status</th>
            </tr>
        </thead>
        <tbody id="the-list">
        <?php for ($i = 0; $i < $count; $i++): ?>
            <tr class="ai-item" data-url="<?php echo esc_url($link[$i]); ?>" data-index="<?php echo $i; ?>">
                <th class="check-column"></th>
                <td class="thumb column-thumb">
                    <img src="<?php echo esc_url($img[$i] ?? 'https://via.placeholder.com/60x60?text=No+Image'); ?>" 
                         width="60" height="60" style="border-radius:4px;" alt="">
                </td>
                <td class="title column-title">
                    <strong class="ai-item-title"><?php echo esc_html($judul[$i]); ?></strong>
                    <div class="row-actions">
                        <span>#<?php echo $i + 1; ?></span> | 
                        <span class="status-text">Menunggu</span>
                    </div>
                </td>
                <td class="source column-source">5play.org</td>
                <td class="status column-status">
                    <span class="status-badge badge-waiting">Menunggu</span>
                </td>
            </tr>
        <?php endfor; ?>
        </tbody>
    </table>

    <!-- CSS -->
    <style>
        /* Progress Container - Default disembunyikan */
        .progress-container {
            margin: 20px 0 30px;
            padding: 16px;
            background: rgba(255,255,255,0.7);
            border-radius: 12px;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.4);
            box-shadow: 0 6px 25px rgba(0,0,0,0.1);
            display: none;
            opacity: 0;
            transform: translateY(10px);
            transition: opacity 0.4s ease, transform 0.4s ease;
        }

        .progress-container.visible {
            display: block;
            opacity: 1;
            transform: translateY(0);
        }

        .progress-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            font-weight: 600;
            color: #1d2327;
        }

        .progress-bar-wrapper {
            background: #e2e4e7;
            height: 10px;
            border-radius: 5px;
            overflow: hidden;
            box-shadow: inset 0 1px 2px rgba(0,0,0,0.06);
        }

        #progress-bar {
            height: 100%;
            width: 0%;
            background: linear-gradient(90deg, #2271b1, #135e96);
            transition: width 0.6s ease;
        }

        #current-game {
            margin-top: 10px;
            color: #50575e;
            font-style: italic;
        }

        /* Controls */
        .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-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;
        }

        .import-btn .dashicons {
            font-size: 17px;
        }

        .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: white;
        }

        .import-btn.secondary {
            background: #f0f0f1;
            color: #1d2327;
            border: 1px solid #c3c4c7;
        }

        .import-btn.danger {
            background: #d63638;
            color: white;
        }

        .import-btn.running::after {
            content: '';
            position: absolute;
            inset: -3px;
            border-radius: 8px;
            border: 2px solid rgba(34,113,177,0.4);
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0% { opacity: 0.3; }
            50% { opacity: 0.7; }
            100% { opacity: 0.3; }
        }

        /* Badge & Status */
        .status-badge {
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }

        .badge-waiting    { background:#f0f0f1; color:#50575e; }
        .badge-processing { background:#fef2c8; color:#856404; }
        .badge-success    { background:#d1e7dd; color:#0f5132; }
        .badge-error      { background:#f8d7da; color:#842029; }
        .badge-duplicate  { background:#cfe2ff; color:#084298; }

        tr.ai-item.processing { background:#fff8e1 !important; }
        tr.ai-item.success    { background:#f0fdf4 !important; }
        tr.ai-item.error      { background:#fef2f2 !important; }

        /* Link edit */
        .edit-post-link {
            margin-left: 8px;
            font-size: 12px;
            color: #2271b1;
            text-decoration: underline;
        }

        .edit-post-link:hover {
            color: #135e96;
        }

        @media (max-width: 782px) {
            .import-controls { flex-wrap: wrap; justify-content: center; }
            .import-btn { flex: 1 1 auto; min-width: 120px; justify-content: center; }
        }
		/* Progress Container Sticky */
.progress-container {
    margin: 20px 0 30px;
    padding: 16px;
    background: rgba(255,255,255,0.92);
    border-radius: 12px;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255,255,255,0.5);
    box-shadow: 0 6px 25px rgba(0,0,0,0.12);
    
    /* ── Bagian Sticky ─────────────────────────────── */
    position: sticky;
    top: 32px;                    /* Jarak dari atas (sesuaikan dengan tinggi admin bar) */
    z-index: 1000;                /* Pastikan di atas elemen lain */
    margin-top: 0;                /* Hilangkan margin atas saat sticky */
    width: 100%;                  /* Lebar penuh */
    max-width: 1200px;            /* Opsional: batasi lebar agar tidak terlalu lebar di layar besar */
    left: 50%;
    transform: translateX(-50%);  /* Center secara horizontal */
    box-sizing: border-box;
}

/* Saat di dalam container utama (untuk mobile & tampilan lebih rapi) */
@media (max-width: 960px) {
    .progress-container {
        top: 0;                   /* Tempel di paling atas pada mobile */
        border-radius: 0;
        margin: 0;
        padding: 12px 16px;
    }
}
    </style>

    <?php wp_nonce_field('submit_game_nonce', 'submit_game_nonce'); ?>

    <!-- JavaScript -->
    <script>
    document.addEventListener('DOMContentLoaded', () => {
    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('submit_game_nonce')?.value || '';
    const btnStart = document.getElementById('btn-start');
    const btnPause = document.getElementById('btn-pause');
    const btnStop = document.getElementById('btn-stop');

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

    const pauseLabel = btnPause.querySelector('.label');
    const startLabel = btnStart.querySelector('.label');

    // LocalStorage-Schlüssel für bereits importierte Links
    const STORAGE_KEY = 'ai_5play_imported_links';

    // Hilfsfunktionen für localStorage
    function getImportedLinks() {
        try {
            return JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
        } catch (e) {
            return [];
        }
    }

    function saveImportedLink(url) {
        const links = getImportedLinks();
        if (!links.includes(url)) {
            links.push(url);
            localStorage.setItem(STORAGE_KEY, JSON.stringify(links));
        }
    }

    // Zeilen markieren, die bereits importiert wurden
    function markImportedRows() {
        const imported = new Set(getImportedLinks());
        rows.forEach(row => {
            const url = row.dataset.url;
            if (imported.has(url)) {
                row.classList.add('imported');
                // Optional: Status-Text und Badge anpassen
                const badge = row.querySelector('.status-badge');
                const statusText = row.querySelector('.status-text');
                if (badge && statusText &&
                    !row.classList.contains('success') &&
                    !row.classList.contains('error')) {
                    badge.className = 'status-badge badge-success';
                    badge.textContent = 'Sudah Diimport';
                    statusText.textContent = 'Sudah Diimport';
                }
            }
        });
    }

    // Beim Laden der Seite bereits importierte Einträge markieren
    markImportedRows();

    function showProgress() {
        progressContainer.classList.add('visible');
    }

    function hideProgress() {
        progressContainer.classList.remove('visible');
        setTimeout(() => {
            progressBar.style.width = '0%';
            progressText.textContent = `0 / ${rows.length}`;
            currentGame.textContent = '';
        }, 600);
    }

    function resetUI() {
        isRunning = false;
        isPaused = false;
        isStopped = false;
        index = 0;
        hideProgress();

        // Force reset aller Buttons & Anzeige
        btnStart.disabled = false;
        btnStart.classList.remove('running');
        startLabel.textContent = 'Mulai Import';
        btnPause.disabled = true;
        pauseLabel.textContent = 'Pause';
        btnStop.disabled = true;

        // Visuellen Status aller Zeilen zurücksetzen, aber 'imported' bleibt erhalten
        document.querySelectorAll('tr.ai-item').forEach(r => {
            r.classList.remove('processing', 'success', 'error');
            const badge = r.querySelector('.status-badge');
            badge.className = 'status-badge badge-waiting';
            badge.textContent = 'Menunggu';
            r.querySelector('.status-text').textContent = 'Menunggu';
        });

        // Bereits importierte Einträge erneut markieren
        markImportedRows();
    }

    function processNext() {
        if (isStopped || isPaused) return;

        // Endbedingung: alle Spiele verarbeitet
        if (index >= rows.length) {
            progressText.textContent = `${rows.length} / ${rows.length} • Selesai!`;
            currentGame.textContent = 'Import selesai ✓ Semua game telah diproses.';
            setTimeout(() => {
                resetUI();
            }, 2000); // 2 Sekunden, damit der Benutzer die Meldung sieht
            return;
        }

        const row = rows[index];
        const url = row.dataset.url;
        const title = row.querySelector('.ai-item-title').textContent.trim();

        currentGame.textContent = `Memproses: ${title} (#${index + 1}/${rows.length})`;
        row.classList.add('processing');

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

        badge.className = 'status-badge badge-processing';
        badge.textContent = 'Processing...';
        statusText.textContent = 'Processing...';

        fetch(ajaxurl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `action=submit_game&wp_url=${encodeURIComponent(url)}&nonce=${nonce}`,
            signal: AbortSignal.timeout(45000)
        })
        .then(r => r.json())
        .then(res => {
            row.classList.remove('processing');

            if (res.success) {
                row.classList.add('success', 'imported');
                saveImportedLink(url); // Erfolgreichen Import speichern

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

                const editLink = res.data?.edit_link || '';
                if (editLink) {
                    statusText.innerHTML = 'Berhasil | <a href="' + editLink + '" target="_blank" class="edit-post-link">Edit Post</a>';
                } else {
                    statusText.textContent = 'Berhasil';
                }
            } else {
                row.classList.add('error');
                let msg = res.data?.message || 'Gagal';
                if (res.data?.is_duplicate) {
                    badge.className = 'status-badge badge-duplicate';
                    msg = 'Sudah ada - ' + msg;
                } else {
                    badge.className = 'status-badge badge-error';
                }
                badge.textContent = msg;
                statusText.textContent = msg;
            }
        })
        .catch(err => {
            row.classList.add('error');
            badge.className = 'status-badge badge-error';
            badge.textContent = err.name === 'TimeoutError' ? 'Timeout' : 'Koneksi Error';
            statusText.textContent = err.name === 'TimeoutError' ? 'Timeout' : 'Koneksi Error';
        })
        .finally(() => {
            index++;
            const percent = Math.round((index / rows.length) * 100);
            progressBar.style.width = percent + '%';
            progressText.textContent = `${index} / ${rows.length}`;

            if (index >= rows.length) {
                progressText.textContent = `${rows.length} / ${rows.length} • Selesai!`;
                currentGame.textContent = 'Import selesai ✓';
                setTimeout(resetUI, 1800);
            } else if (!isPaused && !isStopped) {
                const delay = 2000 + Math.random() * 4000;
                timeoutId = setTimeout(processNext, delay);
            }
        });
    }

    btnStart.addEventListener('click', () => {
        if (isRunning && !isPaused) return;
        isRunning = true;
        isPaused = false;
        isStopped = false;
        btnStart.classList.add('running');
        startLabel.textContent = 'Sedang Berjalan';
        btnPause.disabled = false;
        btnStop.disabled = false;
        pauseLabel.textContent = 'Pause';
        showProgress();
        processNext();
    });

    btnPause.addEventListener('click', () => {
        if (isPaused) {
            isPaused = false;
            pauseLabel.textContent = 'Pause';
            currentGame.textContent = 'Melanjutkan...';
            processNext();
        } else {
            isPaused = true;
            clearTimeout(timeoutId);
            pauseLabel.textContent = 'Lanjutkan';
            currentGame.textContent = 'Dipause...';
        }
    });

    btnStop.addEventListener('click', () => {
        isStopped = true;
        isPaused = false;
        isRunning = false;
        clearTimeout(timeoutId);
        resetUI();
    });
});
    </script>
	
</div>

    <?php
}