<?php
if (! defined('ABSPATH')) exit; 

function wp_happymod() {
global $opt_themes;
@ini_set('display_errors', ERRORS);
@ini_set('user_agent', 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)');
@ini_set('user_agent', 'My-Application/2.5');
@ini_set('user_agent', 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)');
@ini_set('user_agent', 'My-Application/2.5');
echo do_shortcode('[css]');
$Go_Curl 	= new Go_Curl();
$types			= 'post';
$sources		= 'happymod.cloud';
$demos			= 'https://www.happymod.cloud/roblox-apks-mod/com.roblox.client/';
$demosx			= 'https://www.happymod.cloud/';
$checkx			= $Go_Curl->http_responsex($demosx);


$keyz			= $opt_themes['api_key_scrape'];
//if($keyz){
//$rand_apikey 	= array_rand($keyz);
//$apikey 		= $keyz[$rand_apikey]; 
//}

$protocol 		= 'https://'.$sources;
$status 		= $Go_Curl->http_responsex($protocol); 
?>

<?php

// Panggil fungsi
/* $result = $Go_Curl->shortlink(
    'https://www.google.com/search?q=contoh+url+panjang',
    'rahasia123'  // Ganti dengan API key asli kamu
);
echo $result['short_url']; */
 
?>

	<div class="wrap">
	<div class="play_menu" style="text-transform:uppercase">
        <b>Add sources from <?php echo parse_url($protocol)['host']; ?></b>
	</div> 
	</div> 	
	
	<?php 
	$demo    = $demos;
	$source  = $sources;
	$api_keys = !empty($opt_themes['api_key_scrape']) ? (array)$opt_themes['api_key_scrape'] : [];
	$checker = new Check_Status_Cloudflare($Go_Curl, $demo, $source, $api_keys);
	$checker->check_and_display();
	?>
	
	
	<?php
	if (isset($_POST['wp_sb'])) {
		@ini_set('display_errors', ERRORS);
		if (isset($_POST['wp_url'])) {
			$url			= trim(strip_tags($_POST['wp_url']));
			if (stristr($url, $sources)) {
			require_once get_template_directory().'/libs/addons/includes/class/happymod.class.php';
			global $opt_themes;
			$getslinks		= new scrapes;
			$gets_data		= $getslinks->scrape_web_info($url, false); 
				
			require_once get_template_directory().'/libs/addons/includes/inc/top_2.php';


			if (count($gets_data) and !isset($gets_data['error'])) {
			require_once get_template_directory().'/libs/addons/includes/inc/post_content.php';	
			require_once get_template_directory().'/libs/addons/includes/inc/img_gallery.php';	
 
			/*
			start from playstore
			*/
			require_once get_template_directory().'/libs/addons/includes/inc/playstore.php';	
			
			/*
			start from sources
			*/ 
			require_once get_template_directory().'/libs/addons/includes/inc/hmd.php';	
			
			/*
			for apkmody metabox	
			*/
			require_once get_template_directory().'/libs/addons/includes/inc/dlpro.php';	
			
/* 
			$download_info_link = array();
			//$count		= count($gets_data['link_download_aptoide']); 

			if (!empty($gets_data['sizes_GP'])) {
				$size_dw = $gets_data['sizes_GP'];
			} else {
				$size_dw = $gets_data['size_sc'];
			}
			
			$link_urlz = $gets_data['downloadlink'];
			
			if (!empty($opt_themes['ouo'])) {
				$shortened_url = ouo_io_user($link_urlz);
			} elseif (!empty($opt_themes['shrinkearn'])) {
				$shortened_url = shrinkearn_user($link_urlz);
			} elseif (!empty($opt_themes['adurl'])) {
				$shortened_url = adurl_user($link_urlz);
			} else {
				$shortened_url = $final_url; // Gunakan yang sudah diproses (APK atau direct)
			}
			$download_info_link_data = [
				'name' 		=> $gets_data['namedownloadlink'],
				'title' 	=> $gets_data['namedownloadlink'],
				'url' 		=> $link_urlz,
				'links' 	=> $link_urlz,
				'sizes1' 	=> $size_dw,
				'sizes' 	=> $size_dw,
				'size' 		=> $size_dw,
				'tipes' 	=> '',
				'notes' 	=> '',
			];

			array_push($download_info_link, $download_info_link_data);
			update_post_meta($post_id, "repeatable_fields", $download_info_link);
			update_post_meta($post_id, "group_downloads_links", $download_info_link);
 */

			 
			$download_info_link = array();

			// === 1. Ambil dan sanitasi link download utama ===
			$original_url = trim($gets_data['downloadlink'] ?? '');

			if (empty($original_url)) {
				// Jika tidak ada link, hapus meta lama agar tidak ada data kosong
				/* delete_post_meta($post_id, 'repeatable_fields');
				delete_post_meta($post_id, 'group_downloads_links');
				return; */
			}

			// Sanitasi URL
			$original_url = esc_url_raw($original_url);

			// Validasi URL dasar
			if (!filter_var($original_url, FILTER_VALIDATE_URL)) {
				// URL tidak valid → tetap simpan direct (atau bisa skip sesuai kebutuhan)
				$final_url = $original_url;
			} else {
				$final_url = $original_url;
			}

			// === 2. Upload otomatis ke Media Library (jika fitur import_apk aktif) ===
			if (!empty($opt_themes['import_apk'])) {
				$attach_id = upload_remote_file_apk($original_url);

				if (!is_wp_error($attach_id) && $attach_id) {
					$final_url = esc_url(wp_get_attachment_url($attach_id));
				}
				// Jika gagal, tetap pakai $original_url (sudah ada di $final_url)
			}

			// === 3. Proses URL Shortener (OUO → Shrinkearn → Adurl) ===
			
				// Ambil setting dari Redux
				$enable_auto = isset( $opt_themes['enable_shortlinks'] ) ? $opt_themes['enable_shortlinks'] : false;
				$service     = isset( $opt_themes['auto_shortlink'] ) ? $opt_themes['auto_shortlink'] : 'ouo_sl';

				// Jika fitur Automatic Short Links MATI → langsung pakai URL asli
				if ( ! $enable_auto ) {
					$shortened_url = $final_url;
				} else {
					// Fitur AKTIF → proses sesuai service yang dipilih
					switch ( $service ) {
						case 'ouo_sl':
							$shortened_url = ouo_io_user( $original_url );
							break;

						case 'shrinkearn_sl':
							$shortened_url = shrinkearn_user( $original_url );
							break;

						case 'paid4link_sl':
							$shortened_url = paid4link_user( $original_url );
							break;

						case 'adurl_sl':
							$shortened_url = adurl_user( $original_url );
							break;

						default:
							$shortened_url = $final_url; // fallback jika service tidak dikenali
							break;
					}
				}
				 
				// Pastikan URL akhir valid
				$link_url = esc_url($shortened_url) ?: $final_url;

			// === 4. Ambil Size (prioritas sizes_GP → size_sc) ===
			$size_display = '';
			if (!empty($gets_data['sizes_GP'])) {
				$size_display = wp_strip_all_tags($gets_data['sizes_GP']);
			} elseif (!empty($gets_data['size_sc'])) {
				$size_display = wp_strip_all_tags($gets_data['size_sc']);
			}

			// === 5. Ambil Nama Link (fallback jika kosong) ===
			$link_name = trim($gets_data['namedownloadlink'] ?? '');
			if (empty($link_name)) {
				$link_name = 'Download APK'; // atau 'Direct Download', 'Official Link', dll
			}
			$link_name = sanitize_text_field($link_name);

			// === 6. Bangun data download (single entry) ===
			$download_info_link[] = array(
				'name'   => $link_name,
				'title'  => $link_name,
				'url'    => $link_url,
				'links'  => $link_url,
				'size'   => $size_display,        // Cukup satu field (hapus duplikat sizes/sizes1)
				'tipes'  => 'APK',                // Bisa diganti otomatis jika ada data tipe
				'notes'  => '',                   // Bisa diisi dari field lain jika ada
			);

			// === 7. Simpan ke Post Meta ===
			update_post_meta($post_id, 'repeatable_fields', $download_info_link);
			update_post_meta($post_id, 'group_downloads_links', $download_info_link);


			if (!empty($gets_data['sizes_GP'])) {
				$size_dwz = $gets_data['sizes_GP'];
			} else {
				$size_dwz = $gets_data['size_sc'];
			}

			if (!empty($gets_data['title_GP'])) {
				$title_dwz = $gets_data['title_GP'] . ' Apk';
			} else {
				$title_dwz = $gets_data['app_name'] . ' Apk';
			}
 

			$linkapkz	= ouo_io_exhemes('https://exthem.es/apk.php?pkg='.$gets_data['GP_ID']);
			$linkapkz2	= ouo_io_exhemes('https://play.google.com/store/apps/details?id='.$gets_data['GP_ID']);
			 			 
			$download_info_link_data_gps = [
				'name' 		=> $title_dwz,
				'url' 		=> $linkapkz,
				'sizes1' 	=> $size_dwz,
				'sizes' 	=> $size_dwz,
				'title' 	=> $title_dwz,
				'links' 	=> $linkapkz,
				'size' 		=> $size_dwz,
				'tipes' 	=> '',
				'notes' 	=> '',
			];

			array_push($download_info_link, $download_info_link_data_gps);
			update_post_meta($post_id, "repeatable_fields", $download_info_link);
			update_post_meta($post_id, "group_downloads_links", $download_info_link);
		
			require_once get_template_directory().'/libs/addons/includes/inc/dw_apt.php';	
			require_once get_template_directory().'/libs/addons/includes/inc/dw_apkgk.php';		


			wp_set_object_terms($post_id, $gets_data['title_GP'], 'post_tag', true);

			if ($post_id)
			$urlX			= get_permalink($post_id);
			require_once get_template_directory().'/libs/addons/includes/result.php'; 
			}
			} else {
			echo '<div class="play_menu" style="text-transform:uppercase!important;color:#00a0d2"><h3 style="color:#00a0d2">Please check your link.. your link is <b style="color:red">' . $url . '</b></h3></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 <?php if (isset($_POST['submit'])) { ?> class="active" <?php } ?> data-tab="tab2"><a><i class="fa fa-search"></i> Search</a></li>-->
				<li <?php if (!isset($_POST["submit"]) && !isset($_POST["wp_sb"])) { ?>class="active" <?php } ?>data-tab="tab3"><a><i class="fa fa-rss"></i> Latest Update</a></li>
				<li data-tab="tab4"><a><i class="fa fa-pencil-square-o"></i> add manual</a></li>
				<?php if (isset($_POST['wp_sb'])) { ?>
				<li <?php if (isset($_POST['wp_sb'])) { ?>class="active" <?php } ?>data-tab="tab5"><a><i class="fa fa-bullhorn"></i> Debugs</a></li>
				<?php } ?>
			</ul>
			<div style="clear:both"></div>
		</div>
	</div>



	<div class="containerX">
		<div class="tab-content">

			<div id="tab1" class="tab-pane fade"> 
				<ul class="play_menu">
				<li>Your Status Post is <?php if ($opt_themes['apk_status'] != 'draft') { ?> <blink><strong class="blink blink-one" style="color:green"><?php echo $opt_themes['apk_status']; ?></strong></blink> You ready to Make auto posting now <?php } else { ?><blink><strong class="blink blink-one" style="color:red"><?php echo $opt_themes['apk_status']; ?></strong></blink>. Please Change to <blink><strong class="blink" style="color:green">publish</strong></blink> to make Auto Posting, you can go to Setting Page <?php } ?> </li>
				</ul>
			</div>

			
		<div id="tab2" class="tab-pane fade <?php if(isset($_POST['submit'])) { ?>in active <?php } ?>">
				<div class="play_menu" style="text-transform:uppercase"><b>Search</b></div>     
 
		</div> 

		
		<div id="tab3" class="tab-pane fade <?php if (!isset($_POST["submit"]) && !isset($_POST["wp_sb"])) { ?>in active <?php } ?>">
			
			<div class="play_menu" style="text-transform:uppercase"><b>Latest Update</b></div> 
				<?php 

				// Pagination
				$paged = isset($_GET['apps']) ? max(1, (int)$_GET['apps']) : 1;
				$sc_url = ($paged > 1) 
					? "https://www.happymod.cloud/new-mod,{$paged}.html" 
					: "https://www.happymod.pro/new-mod.html";

				// Fetch page
				$html = file_get_html($sc_url);

				if (!$html) {
					echo '<div class="alert alert-danger text-center my-5">Unable to load data from happymod.cloud. Please try again later.</div>';
					return;
				}
				//new-mod,60.html
				
				preg_match_all('#new-mod,(\d+).html"#si', $html, $page_matches);
				$page_numbers = array_unique($page_matches[1] ?? []);
				$total_pages = !empty($page_numbers) ? max($page_numbers) : $total_pages;
				$total_pages = max($total_pages, $paged); 
				?>

				<section>
					<div class="row" id="apps-list">
						<?php
						$counter = 1; // Start from 1 for proper ranking on each page

						foreach ($html->find("li.list-item") as $item) {
							$link = $item->find('a', 0);
							if (!$link || empty($link->href)) continue;

							// Data extraction
							$title_elem = $item->find('.list-info-title', 0);
							$title = $title_elem ? trim($title_elem->innertext) : 'Unknown App';

							$img = $item->find('img', 0);
							$icon = $img ? ($img->{'data-src'} ?? $img->src ?? '') : '';

							$spans = $item->find('.list-info-text span');
							$version = !empty($spans[0]) ? trim($spans[0]->innertext) : 'N/A';

							// Smart mod description (prioritizes actual features)
							$mod_desc = $item->find('.list-info-text span', 3)->innertext;
							foreach ($spans as $span) {
								$text = trim($span->innertext);
								if (preg_match('/(money|unlocked|pro|premium|mod menu|subscribed|god mode|ads removed|high damage)/i', $text)) {
									$mod_desc = $text;
									break;
								}
							}
 		
							$detail_url = 'https://www.happymod.cloud' . $link->href; 
							$appId 	= $Go_Curl->get_playstore_id_by_title_google($title);
							?>

							<div class="col-12 col-md-6 mb-4">
								<span class="position-relative archive-post--remove app-container d-flex align-items-center">
									<!-- Icon with Number Overlay -->
									<div class="flex-shrink-0" style="position:relative;">
									
									
										 
									<img src="<?= $appId ? $Go_Curl->getAppsPoster($appId) : $icon; ?>" class="app-logo rounded" width="64" height="64" alt="<?php echo htmlspecialchars($title); ?>">
										 

										 
										<span style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);background:rgba(0,0,0,0.85);color:white;padding:5px 9px;border-radius:6px;font-weight:bold;font-size:13px;border:2px solid white;">
											<?= $counter ?>
										</span> 
									</div>

									<!-- App Info -->
									<div class="app-info flex-grow-1">
										<h3 class="h5 font-weight-semibold w-100 app-title mb-1">
											<?php echo htmlspecialchars($title); ?> 
										</h3>
										<div class="text-truncate text-muted app-desc small">
											<span class="clamp-1 w-100"><?php echo htmlspecialchars($mod_desc); ?></span>
										</div>
									</div>

									<!-- Get Button + Version -->
									<div class="app-get text-end ms-3">
										<form method="POST" target="_blank" class="d-inline">
											<input style="display:none" type="text" name="wp_url" value="<?php echo htmlspecialchars($detail_url); ?>">
											<button type="submit" name="wp_sb" class="get-button btn btn-success btn-sm"><?php echo postnow; ?></button>
										</form>
										<div class="text-muted small mt-1">v.<?php echo htmlspecialchars($version); ?></div>
									</div>
								</span>
							</div>

							<?php
							$counter++;
						}

						// Cleanup
						$html->clear();
						unset($html);
						?>
					</div>
				</section>

				<?php 
				$sc_page = 'sc-happymod'; 
				$paged = max(1, intval($_GET['apps'] ?? 1));
				$total_pages = max(1, intval($total_pages ?? 1)); // pastikan variabel ini sudah ada
				$paged = min($paged, $total_pages);
				?>

				<div class="nav_wrapper">
					<!-- Pagination -->
					<nav aria-label="Page navigation">
						<ul class="pagination">
							<!-- First (sembunyi di HP kecil) -->
							<li class="page-item hide-mobile <?php echo $paged <= 1 ? 'disabled' : ''; ?>">
								<a class="page-link" href="?page=<?php echo $sc_page; ?>&apps=1">
									<span class="desktop-only">First</span>
									<span class="mobile-only">««</span>
								</a>
							</li>

							<!-- Previous -->
							<li class="page-item <?php echo $paged <= 1 ? 'disabled' : ''; ?>">
								<a class="page-link" href="?page=<?php echo $sc_page; ?>&apps=<?php echo $paged - 1; ?>">
									<span class="desktop-only">Prev</span>
									<span class="mobile-only">«</span>
								</a>
							</li>

							<?php
							// Jumlah halaman yang ditampilkan (dinamis berdasarkan layar)
							$visible_base = 5;
							$visible = $visible_base;

							// Kurangi di layar kecil (bisa diatur lebih lanjut via JS jika mau)
							$start = max(1, $paged - floor($visible / 2));
							$end = min($total_pages, $start + $visible - 1);
							if ($end - $start + 1 < $visible) {
								$start = max(1, $end - $visible + 1);
							}

							// Ellipsis kiri
							if ($start > 1): ?>
								<li class="page-item">
									<a class="page-link" href="?page=<?php echo $sc_page; ?>&apps=1">1</a>
								</li>
								<?php if ($start > 2): ?>
									<li class="page-item"><span class="page-link ellipsis">...</span></li>
								<?php endif; ?>
							<?php endif; ?>

							<!-- Nomor halaman -->
							<?php for ($i = $start; $i <= $end; $i++): 
								$is_active = ($i == $paged);
							?>
								<li class="page-item <?php echo $is_active ? 'active' : ''; ?>">
									<a class="page-link" href="?page=<?php echo $sc_page; ?>&apps=<?php echo $i; ?>">
										<?php echo $i; ?>
									</a>
								</li>
							<?php endfor; ?>

							<!-- Ellipsis kanan -->
							<?php if ($end < $total_pages): ?>
								<?php if ($end < $total_pages - 1): ?>
									<li class="page-item"><span class="page-link ellipsis">...</span></li>
								<?php endif; ?>
								<li class="page-item">
									<a class="page-link" href="?page=<?php echo $sc_page; ?>&apps=<?php echo $total_pages; ?>">
										<?php echo $total_pages; ?>
									</a>
								</li>
							<?php endif; ?>

							<!-- Next -->
							<li class="page-item <?php echo $paged >= $total_pages ? 'disabled' : ''; ?>">
								<a class="page-link" href="?page=<?php echo $sc_page; ?>&apps=<?php echo $paged + 1; ?>">
									<span class="desktop-only">Next</span>
									<span class="mobile-only">»</span>
								</a>
							</li>

							<!-- Last (sembunyi di HP kecil) -->
							<li class="page-item hide-mobile <?php echo $paged >= $total_pages ? 'disabled' : ''; ?>">
								<a class="page-link" href="?page=<?php echo $sc_page; ?>&apps=<?php echo $total_pages; ?>">
									<span class="desktop-only">Last</span>
									<span class="mobile-only">»»</span>
								</a>
							</li>
						</ul>
					</nav>

					<!-- Go to Page -->
					<div class="go-to">
						<span>Go to page:</span>
						<input type="number" id="goto-page-input" min="1" max="<?php echo $total_pages; ?>" value="<?php echo $paged; ?>">
						<button id="goto-page-btn">Go</button>
					</div>
				</div>

				<script>
				document.addEventListener('DOMContentLoaded', function() {
					const btn = document.getElementById('goto-page-btn');
					const input = document.getElementById('goto-page-input');
					const maxPage = <?php echo $total_pages; ?>;

					function goToPage() {
						let page = parseInt(input.value, 10);
						if (isNaN(page) || page < 1) page = 1;
						if (page > maxPage) page = maxPage;

						input.value = page;
						window.location.href = '?page=<?php echo $sc_page; ?>&apps=' + page;
					}

					btn.addEventListener('click', goToPage);

					input.addEventListener('keypress', function(e) {
						if (e.key === 'Enter') {
							e.preventDefault();
							goToPage();
						}
					});
				});
				</script>
				 
			 

			</div>

			<div id="tab4" class="tab-pane fade">
				<div class="play_menu" style="text-transform:uppercase"><i class="fa fa-pencil-square-o" aria-hidden="true"></i>&nbsp;<b>Paste your link post here</b></div>

				<div class="play_menu">
				<form name="myForm" id="myForm" method="POST" class='f'>
				<input type="text" name="wp_url" placeholder="example : <?php echo $demos; ?>">
				<input type="submit" id="Submit" name="wp_sb" value="<?php echo postnow; ?>" />
				</form>
				</div>

				<div class="play_menu" style="text-transform:uppercase"><b>Add manual</b></div>

				<div class="play_menu" style="text-transform:uppercase">
				<ol style="padding-right: 20px !important;">
				<li>Open website <a style="color:var(--color_link_h)!important;font-weight: 700;" href="https://<?php echo parse_url($demos)['host']; ?>" target="_blank"><?php echo parse_url($demos)['host']; ?></a></li>
				<li>Copy link post and paste to form</li>
				<li>use the url into this format: <strong style="color:var(--color_link_h)!important;font-weight: 700;text-transform:lowercase!important"><?php echo $demos; ?></strong> </li>
				</ol>
				</div>

			</div>

			<div id="tab5" class="tab-pane fade <?php if (isset($_POST['wp_sb'])) { ?> in active<?php } ?>">
				
			<?php require_once get_template_directory().'/libs/addons/includes/debug.php'; ?>
			</div>

		</div>
	</div>




	<div style="clear:both"></div>

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