<?php
/*-----------------------------------------------------------------------------------*/
/*  EXTHEM.ES
/*  PREMIUM WORDRESS THEMES
/*
/*  STOP DON'T TRY EDIT
/*  IF YOU DON'T KNOW PHP 
/*
/*-----------------------------------------------------------------------------------*/ 

add_filter( 'wp_default_editor', function () { return 'html'; } );

if ( !function_exists( 'add_post_metaboxes' ) ) 
{
	function add_post_metaboxes() 
	{
		global $post;   	 
		add_meta_box( 'wp_apk_details',  __( 'App Details Info', THEMES_NAMES ), 'apk_details_info', 'post', 'normal', 'low' );  
		add_meta_box( 'gp_versions_table', __( 'List All Versions', THEMES_NAMES ), 'gp_versions_meta_box_callback', 'post', 'normal', 'low' );
		
		//add_meta_box("demo-meta-box", "Custom Meta Box", "custom_meta_box_markup", "post", "after_title", "high", null);
	}
	add_action( 'add_meta_boxes', 'add_post_metaboxes', 0 );
}

if ( !function_exists( 'gp_versions_meta_box_callback' ) ) 
{
	function gp_versions_meta_box_callback( $post ) 
	{
		wp_nonce_field( 'gp_versions_meta_box', 'gp_versions_meta_box_nonce' );

		$current_gp_id   = get_post_meta( $post->ID, 'wp_GP_ID', true );
		$current_post_id = $post->ID;
		$per_page        = 10;
		$initial_page    = 1;

		// Add New Version URL
		$add_new_url = admin_url( 'post-new.php?post_type=post' );
		?>
		<style>
			.gp-versions-table-wrapper { position:relative; overflow-x:auto; margin:20px 0; border-radius:12px; box-shadow:0 4px 15px rgba(0,0,0,0.1); background:#fff; }
			.gp-page-nav { background:#1e293b; color:#e2e8f0; padding:12px 16px; font-weight:600; display:flex; justify-content:space-between; align-items:center; border-top-left-radius:12px; border-top-right-radius:12px; }
			.gp-page-nav a.button { background:#3b82f6; color:white; padding:8px 16px; border-radius:8px; text-decoration:none; font-weight:500; }
			.gp-page-nav a.button:hover { background:#2563eb; }
			.gp-page-nav .sort-info { font-weight:normal; opacity:0.9; font-size:13px; }

			.gp-versions-table { width:100%; min-width:700px; border-collapse:collapse; font-size:14px; }
			.gp-versions-table th, .gp-versions-table td { padding:14px 12px; text-align:left; border-bottom:1px solid #e2e8f0; }
			.gp-versions-table thead th { background:#f8fafc; font-weight:600; color:#374151; position:sticky; top:0; z-index:10; }
			.gp-versions-table tbody tr:nth-child(even) { background:#f8fafc; }
			.gp-versions-table tbody tr:hover { background:#e0f2fe; }
			.gp-versions-table tbody tr.gp-current-version { background:#dbeafe !important; font-weight:600; }
			.gp-versions-table td:first-child, .gp-versions-table th:first-child { position:sticky; left:0; z-index:11; background:inherit; box-shadow:4px 0 10px rgba(0,0,0,0.08); }
			.gp-versions-table img { width:50px; height:50px; object-fit:cover; border-radius:8px; box-shadow:0 2px 6px rgba(0,0,0,0.1); }
			.gp-placeholder-img { width:50px; height:50px; background:#e2e8f0; border-radius:8px; display:flex; align-items:center; justify-content:center; color:#94a3b8; font-size:12px; }

			.gp-pagination { padding:16px; background:#f8fafc; border-top:1px solid #e2e8f0; display:flex; justify-content:space-between; align-items:center; font-size:14px; color:#475569; border-bottom-left-radius:12px; border-bottom-right-radius:12px; }
			.gp-pagination a { color:#2563eb; text-decoration:none; padding:6px 12px; border-radius:6px; margin:0 4px; cursor:pointer; }
			.gp-pagination a:hover { background:#dbeafe; }
			.gp-pagination a.current { background:#1e293b; color:white; font-weight:600; }
			.gp-pagination .disabled { color:#94a3b8; pointer-events:none; }

			.gp-loading-overlay { position:absolute; inset:0; background:rgba(255,255,255,0.9); display:none; align-items:center; justify-content:center; z-index:30; font-size:16px; color:#475569; }
			.gp-loading-overlay::after { content:''; width:32px; height:32px; border:4px solid #e2e8f0; border-top:4px solid #3b82f6; border-radius:50%; animation:spin 1s linear infinite; margin-left:12px; }
			@keyframes spin { to { transform:rotate(360deg); } }
		</style>

		<div class="gp-versions-table-wrapper" id="gp-versions-wrapper">
			<div class="gp-loading-overlay">Loading versions...</div>

			<!-- Navy Header -->
			

			<table class="gp-versions-table">
				<thead>
					<tr>
						<th scope="col" width="80">Poster</th>
						<th scope="col">Title</th>
						<th scope="col" width="100">Version</th>
						<th scope="col" width="140">Last Updated</th>
						<th scope="col" width="70">Action</th>
					</tr>
				</thead>
				<tbody id="gp-versions-tbody">
					<?php 
					if ( ! empty( $current_gp_id ) ) {
						$args = [
							'post_type'      => 'post',
							'posts_per_page' => $per_page,
							'paged'          => $initial_page,
							'post_status'    => 'publish',
							'meta_query'     => [
								'relation' => 'AND',
								[ 'key' => 'wp_GP_ID', 'value' => $current_gp_id, 'compare' => '=' ],
								'version_clause' => [ 'key' => 'wp_version_GP', 'compare' => 'EXISTS' ]
							],
							'orderby' => [ 'version_clause' => 'DESC' ],
						];
						$query = new WP_Query( $args );

						if ( $query->have_posts() ) {
							while ( $query->have_posts() ) { $query->the_post();
								$is_current = ( get_the_ID() === $current_post_id );
								$title      = get_post_meta( get_the_ID(), 'wp_title_GP', true ) ?: get_the_title();
								$version    = get_post_meta( get_the_ID(), 'wp_version_GP', true );
								$poster_url = has_post_thumbnail() ? get_the_post_thumbnail_url( get_the_ID(), 'thumbnail' )
											: ( get_post_meta( get_the_ID(), 'wp_poster_GP', true ) ?: false );
								?>
								<tr <?php echo $is_current ? 'class="gp-current-version"' : ''; ?>>
									<td>
										<?php if ( $poster_url ) : ?>
											<img src="<?php echo esc_url( $poster_url ); ?>" alt="<?php echo esc_attr( $title . ' poster' ); ?>">
										<?php else : ?>
											<div class="gp-placeholder-img">No Image</div>
										<?php endif; ?>
									</td>
									<td><?php echo esc_html( $title ); ?></td>
									<td><?php echo $version ? 'v' . esc_html( $version ) : '<em>—</em>'; ?></td>
									<td><?php echo esc_html( get_the_modified_date( 'M j, Y' ) ); ?></td>
									<td><a href="<?php echo esc_url( get_edit_post_link() ); ?>" target="_blank" style="color:#2563eb;">Edit</a></td>
								</tr>
								<?php
							}
							wp_reset_postdata();
						} else {
							echo '<tr><td colspan="5" style="text-align:center;padding:30px;color:#6b7280;">No published versions found with this Package Name.</td></tr>';
						}
					} else {
						echo '<tr><td colspan="5" style="text-align:center;padding:40px;color:#374151;"><strong>No Package Name set</strong><br><br>Add a <strong style="text-transform:uppercase">Package name</strong> meta value to see all versions.</td></tr>';
					}
					?>
				</tbody>
			</table>

			<!-- Pagination Footer -->
			<div class="gp-pagination" id="gp-pagination">
				<?php if ( ! empty( $current_gp_id ) && $query->have_posts() ) : ?>
					<?php
					$total_posts = $query->found_posts;
					$total_pages = max( 1, ceil( $total_posts / $per_page ) );
					$start = ( $initial_page - 1 ) * $per_page + 1;
					$end   = min( $initial_page * $per_page, $total_posts );
					?>
					<div>Showing <?php echo $start; ?>–<?php echo $end; ?> of <?php echo $total_posts; ?> versions</div>
					<div>
						<?php if ( $initial_page > 1 ): ?>
							<a class="gp-page-link" data-page="<?php echo $initial_page - 1; ?>">← Previous</a>
						<?php else: ?>
							<span class="disabled">← Previous</span>
						<?php endif; ?>

						<?php
						$range = 2;
						$start_page = max(1, $initial_page - $range);
						$end_page   = min($total_pages, $initial_page + $range);
						if ( $start_page > 1 ) echo '<a class="gp-page-link" data-page="1">1</a> ... ';
						for ( $i = $start_page; $i <= $end_page; $i++ ) {
							echo $i == $initial_page ? '<a class="current">'.$i.'</a>' : '<a class="gp-page-link" data-page="'.$i.'">'.$i.'</a>';
						}
						if ( $end_page < $total_pages ) echo ' ... <a class="gp-page-link" data-page="'.$total_pages.'">'.$total_pages.'</a>';
						?>

						<?php if ( $initial_page < $total_pages ): ?>
							<a class="gp-page-link" data-page="<?php echo $initial_page + 1; ?>">Next →</a>
						<?php else: ?>
							<span class="disabled">Next →</span>
						<?php endif; ?>
					</div>
				<?php endif; ?>
			</div>
		</div>

		<?php if ( empty( $current_gp_id ) ) : ?>
			<p style="margin-top:16px;padding:12px;background:#fffbeb;border-left:4px solid #fbbf24;color:#92400e;">
				<strong>Pro Tip:</strong> Enter the app's <strong>Package Name</strong> (e.g., com.whatsapp) in the meta field above.<br>
				Once saved, this table will automatically show all versions of this app.
			</p>
		<?php endif; ?>

		<!-- Inline JavaScript for AJAX Pagination -->
		<script type="text/javascript">
		jQuery(function($) {
			var wrapper   = $('#gp-versions-wrapper');
			var tbody     = $('#gp-versions-tbody');
			var pagination = $('#gp-pagination');
			var loading   = wrapper.find('.gp-loading-overlay');

			function loadPage(page) {
				loading.show();

				$.post('<?php echo admin_url( "admin-ajax.php" ); ?>', {
					action:  'gp_load_versions_page',
					nonce:   '<?php echo wp_create_nonce( "gp_versions_ajax_nonce" ); ?>',
					post_id: <?php echo $post->ID; ?>,
					paged:   page
				}, function(res) {
					if (res.success) {
						tbody.html(res.data.tbody);
						pagination.html(res.data.pagination);
					} else {
						tbody.html('<tr><td colspan="5" style="text-align:center;padding:30px;">' + res.data + '</td></tr>');
						pagination.html('');
					}
					loading.hide();
				}, 'json');
			}

			wrapper.on('click', '.gp-page-link', function(e) {
				e.preventDefault();
				var page = $(this).data('page');
				if (page) loadPage(page);
			});
		});
		</script>
		<?php
	}
}

if ( !function_exists( 'gp_ajax_load_versions_page' ) ) 
{
// AJAX Handler (must be outside the callback)
	function gp_ajax_load_versions_page() 
	{
		check_ajax_referer( 'gp_versions_ajax_nonce', 'nonce' );

		$post_id     = intval( $_POST['post_id'] );
		$paged       = intval( $_POST['paged'] );
		$per_page    = 10;

		$current_gp_id = get_post_meta( $post_id, 'wp_GP_ID', true );
		$current_post_id = $post_id;

		if ( empty( $current_gp_id ) ) {
			wp_send_json_error( 'No Package Name set.' );
		}

		$args = [
			'post_type'      => 'post',
			'posts_per_page' => $per_page,
			'paged'          => $paged,
			'post_status'    => 'publish',
			'meta_query'     => [
				'relation' => 'AND',
				[ 'key' => 'wp_GP_ID', 'value' => $current_gp_id, 'compare' => '=' ],
				'version_clause' => [ 'key' => 'wp_version_GP', 'compare' => 'EXISTS' ]
			],
			'orderby' => [ 'version_clause' => 'DESC' ],
		];

		$query = new WP_Query( $args );

		ob_start();
		if ( $query->have_posts() ) {
			while ( $query->have_posts() ) { $query->the_post();
				$is_current = ( get_the_ID() === $current_post_id );
				$title      = get_post_meta( get_the_ID(), 'wp_title_GP', true ) ?: get_the_title();
				$version    = get_post_meta( get_the_ID(), 'wp_version_GP', true );
				$poster_url = has_post_thumbnail() ? get_the_post_thumbnail_url( get_the_ID(), 'thumbnail' )
							: ( get_post_meta( get_the_ID(), 'wp_poster_GP', true ) ?: false );
				?>
				<tr <?php echo $is_current ? 'class="gp-current-version"' : ''; ?>>
					<td><?php echo $poster_url ? '<img src="'.esc_url($poster_url).'" alt="'.esc_attr($title.' poster').'">' : '<div class="gp-placeholder-img">No Image</div>'; ?></td>
					<td><?php echo esc_html( $title ); ?></td>
					<td><?php echo $version ? 'v' . esc_html( $version ) : '<em>—</em>'; ?></td>
					<td><?php echo esc_html( get_the_modified_date( 'M j, Y' ) ); ?></td>
					<td><a href="<?php echo esc_url( get_edit_post_link() ); ?>" target="_blank" style="color:#2563eb;">Edit</a></td>
				</tr>
				<?php
			}
			wp_reset_postdata();
			$tbody = ob_get_clean();

			$total_posts = $query->found_posts;
			$total_pages = max(1, ceil($total_posts / $per_page));
			$start = ($paged - 1) * $per_page + 1;
			$end   = min($paged * $per_page, $total_posts);

			$pagination = '<div>Showing '.$start.'–'.$end.' of '.$total_posts.' versions</div><div>';

			if ($paged > 1) $pagination .= '<a class="gp-page-link" data-page="'.($paged-1).'">← Previous</a>';
			else $pagination .= '<span class="disabled">← Previous</span>';

			$range = 2;
			$start_page = max(1, $paged - $range);
			$end_page   = min($total_pages, $paged + $range);
			if ($start_page > 1) $pagination .= '<a class="gp-page-link" data-page="1">1</a> ... ';
			for ($i = $start_page; $i <= $end_page; $i++) {
				$pagination .= $i == $paged ? '<a class="current">'.$i.'</a>' : '<a class="gp-page-link" data-page="'.$i.'">'.$i.'</a>';
			}
			if ($end_page < $total_pages) $pagination .= ' ... <a class="gp-page-link" data-page="'.$total_pages.'">'.$total_pages.'</a>';

			if ($paged < $total_pages) $pagination .= '<a class="gp-page-link" data-page="'.($paged+1).'">Next →</a>';
			else $pagination .= '<span class="disabled">Next →</span>';

			$pagination .= '</div>';

			wp_send_json_success([ 'tbody' => $tbody, 'pagination' => $pagination ]);
		} else {
			wp_send_json_error( 'No versions found on this page.' );
		}
	}
	add_action( 'wp_ajax_gp_load_versions_page', 'gp_ajax_load_versions_page' );
}

if ( !function_exists( 'apk_details_info' ) ) 
{
	function apk_details_info() 
	{  		
		global $post;

		// Safety check
		if ( ! $post ) {
			return;
		}

		$post_ids 		= $post->ID;
		$post_id 		= $post_ids;
		
		
		// Determine if we are editing an existing post
		$is_edit 		= ( $GLOBALS['pagenow'] === 'post.php' && isset( $_GET['action'] ) && $_GET['action'] === 'edit' && ! empty( $_GET['post'] ) );
		$is_new_post 	= !$is_edit;


		$post_IDs		= $post->ID; 
		$titleID		= get_post_meta( $post_ids, 'wp_GP_ID', true ); 
		$judul			= wp_strip_all_tags(get_post_meta( $post_ids, 'wp_title_GP',  true )); 
		$developer		= get_post_meta( $post_ids, 'wp_developers_GP', true ); 
		$version		= get_post_meta( $post_ids, 'wp_version_GP', true) ?: get_post_meta( $post_ids, 'wp_version', true);
		$version_web	= get_post_meta( $post_ids, 'wp_version', true );
		$sizes			= get_post_meta( $post_ids, 'wp_sizes_GP', true) ?: get_post_meta( $post_ids, 'wp_sizes', true);
		
		$sizes2			= get_post_meta( $post_ids, 'wp_sizes_GP', true) ?:  get_post_meta( $post_ids, 'wp_sizes', true) ?: 'Unknown';
	 
		$installs		= get_post_meta( $post_ids, 'wp_installs_GP', true ); 
		$requires		= get_post_meta( $post_ids, 'wp_requires_GP', true ); 
		$updates		= get_post_meta( $post_ids, 'wp_updates_GP', true );  
		$contentrated	= get_post_meta( $post_ids, 'wp_contentrated_GP', true ); 
		$rated			= get_post_meta( $post_ids, 'wp_rated_GP', true ); 
		$ratings		= get_post_meta( $post_ids, 'wp_ratings_GP', true ); 
		$persenapgk		= get_post_meta( $post_ids, 'wp_persen_GP', true ); 
		$whatnews		= get_post_meta( $post_ids, 'wp_whatnews_GP', true ); 
		$whatnews		= wp_kses_post( $whatnews );
		$youtube		= get_post_meta( $post_ids, 'wp_youtube_GP', true ); 
		$desck			= wp_strip_all_tags(get_post_meta( $post_ids, 'wp_desck_GP', true ));  
		$postergp		= get_post_meta( $post_ids, 'wp_poster_GP', true );
		$background_gp	= get_post_meta( $post_ids, 'wp_backgrounds_GP', true );
		$gambarX21		= get_post_meta( $post_ids, 'wp_images_GP', true ); 
		$newupdates		= get_post_meta( $post_ids, 'wp_newupdates', true ); 
		$modfeatures	= get_post_meta( $post_ids, 'wp_mods', true );
		$modfeatures2	= get_post_meta( $post_ids, 'wp_mods2', true );
		$wp_mods2		= get_post_meta( $post_ids, 'wp_mods2', true );
		$wp_mods2		= wp_kses_post( $wp_mods2 ); 
		if ( $wp_mods2 === FALSE or $wp_mods2 == '' ) $wp_mods2 = $modfeatures2;
		if ( $modfeatures2 === FALSE or $modfeatures2 == '' ) $modfeatures2 = $wp_mods2;
		$wp_mods_post		= get_post_meta( $post_ids, 'wp_mods_post', true );
		$wp_mods_post2		= get_post_meta( $post_ids, 'wp_mods_post2', true );
		$wp_mods_post3		= get_post_meta( $post_ids, 'wp_mods_post3', true );
		$wp_title_wp_mods	= wp_strip_all_tags(get_post_meta( $post_ids, 'wp_title_wp_mods', true ));
		$wp_title_wp_mods_2	= wp_strip_all_tags(get_post_meta( $post_ids, 'wp_title_wp_mods_2', true ));
		$wp_title_wp_mods_3	= wp_strip_all_tags(get_post_meta( $post_ids, 'wp_title_wp_mods_3', true )); 
		$tipes				= wp_strip_all_tags(trim(get_post_meta( $post_ids, 'wp_tipes', true )));
		$cpu				= get_post_meta( $post_ids, 'wp_cpu', true ); 
		$wp_playstore_link	= get_post_meta( $post_ids, 'wp_playstore_link', true );
		$gp_prices			= get_post_meta( $post_ids, 'wp_prices_gp', true );
		$article_content	= get_post_meta( $post_ids, 'wp_article_content',  true );
		$article_content	= wp_kses_post( $article_content );

		$is_ads				= get_post_meta( $post_ids );
		$is_premium			= get_post_meta( $post_ids );
		$is_free			= get_post_meta( $post_ids ); 
		$is_ads_value 		= get_post_meta( $post_ids, 'is_ads', true );
		
		// For new posts: default to checked (YES)
		// For existing posts: checked only if saved value is not 'no'
		$should_be_checked 	= ( $is_ads_value !== 'no' );

		$label_1			= wp_strip_all_tags(trim(get_post_meta( $post_ids, 'label_1', true )));
		$label_2			= wp_strip_all_tags(trim(get_post_meta( $post_ids, 'label_2', true )));
		
		 
		?>  

		<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> 
		
		<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.14.0/jquery-ui.min.js" integrity="sha512-MlEyuwT6VkRXExjj8CdBKNgd+e2H+aYZOCUaCrt9KRk6MlZDOs91V1yK22rwm8aCIsb5Ec1euL8f0g58RKT/Pg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
		
		<div class="admin-inside-box clearfix">
		
		<div class="aps-wrap">		
		
		<ul class="aps-data-tabs">
			<li class="<?php echo $is_new_post ? 'active' : ''; ?>" data-tab="#aps-tb-general">General</li>
			<li class="" data-tab="#aps-tb-desc">Summary</li>
			<?php if ( $is_new_post ) : ?>
			<li class="" data-tab="#aps-tb-mods">Modder</li>
			<?php endif; ?>
			<li class="" data-tab="#aps-tb-img">Gallery Images</li>
			<li class="<?php echo $is_edit ? 'active' : ''; ?>" data-tab="#aps-tb-download">Download Link</li>
			<li id="donate" class="" data-tab="#aps-tb-donate">Support</li>
		</ul>
		
		<!-- open tab container -->
		<div class="aps-tabs-container">
		
		
		<?php if ( $is_edit ) : ?>
		<button class="button" id="dismissible-button" type="button">HIDE</button>
		<?php endif; ?>
		
		<!-- tab 0 -->
		<div id="dismissible-alert">
		
		<?php if ( $is_edit ) : ?>
		
		<div class="aps-group-inputs" style="padding: 10px;">
		<ul class="aps-features">
		
		<li style="background-color: cornsilk;padding-bottom: 10px;">	 
		
		<div class="aps-col-3">
		<label for="aps-sale-start" style="text-transform:uppercase;padding: 5px 0;font-weight: bold;display: block;">Enable Ads</label>	
		<label class="toggle_input" for="is_ads" style="background:unset;padding: 8px 9px;">
		<input type="checkbox" value="yes" id="is_ads" name="is_ads" <?php if ( isset ( $is_ads['is_ads'] ) ) checked( $is_ads['is_ads'][0], 'yes' ); ?> checked> 
		<span data-unchecked="no" data-checked="yes"></span>
		</label>
		<p><b>YES</b> to showing all ads on single post</p> 
		</div>
		
		
		</li>
		
		<li style="background-color: cornsilk;padding-bottom: 10px;">	 
		 
		
		<div class="aps-col-2" style="text-transform:uppercase">
			<label for="wp_version_GP" style="padding: 5px 0;font-weight: bold;display: block;">Version <small>(Playstore)</small></label>
			<input type="text" id="wp_version_GP" class="aps-date-input aps-text-input" name="wp_version_GP" value="<?= $version ?>" placeholder="example : 2.522.280" />
		</div>
		
		<div class="aps-col-2" style="text-transform:uppercase">
			<label for="wp_sizes" style="padding: 5px 0;font-weight: bold;display: block;">Size</label>
			<input type="text" id="wp_sizes" class=" aps-text-input" name="wp_sizes" value="<?php echo $sizes; ?>" placeholder="example : 250 mb"/>
		</div>
		
		<div class="aps-col-2" style="text-transform:uppercase">
			<label for="wp_tipes" style="padding: 5px 0;font-weight: bold;display: block;">Type <small>(if empty default use mod) </small></label> 
			<input type="text" id="wp_tipes" class=" aps-text-input" name="wp_tipes" value="<?= $tipes ?>" placeholder="example : free, premium or else"/>  
		</div> 
		
		</li>	
		
		<li style="background-color: cornsilk;padding-bottom: 10px;">	 	 
		
		<div class="aps-col-3" style="text-transform:uppercase">
		<label for="wp_mods" style="padding: 5px 0;font-weight: bold;display: block;">Short Mod</label>
		
		<input type="text" id="wp_mods" class=" aps-text-input" name="wp_mods" value="<?= $modfeatures ?>" placeholder="example : Mod menu"/>   
		
		</div>	
		
		<div class="aps-col-3" style="text-transform:uppercase">
			<label for="wp_updates_GP" style="padding: 5px 0;font-weight: bold;display: block;">updates</label>
			<div style="display: flex; gap: 5px;">
			<input type="text" id="wp_updates_GP" class=" aps-text-input" name="wp_updates_GP" value="<?php echo $updates; ?>" placeholder="example : <?php echo get_the_date(); ?>"/>
			<button type="button"  onclick="updateDate()"  style="padding: 5px 10px; cursor: pointer; width:150px;">
			Current Date
			</button>
			</div>
		</div>
		
		</li> 
		
		<li style="background-color: cornsilk;padding-bottom: 10px;">	 
		
		<div class="aps-col-6" style="text-transform:uppercase">
		<label for="wp_mods2" style="padding: 5px 0;font-weight: bold;display: block;">Full Mod</label>

		<?php 
		/* wp_editor( ($wp_mods2), 'wp_mods2', 
			array(
				'textarea_name' => 'wp_mods2',
				'wpautop' => true,
				'media_buttons' => false, 
				'tabindex' => 1, 
				'textarea_rows' => 7, 
				'tinymce'	=> array(
					'toolbar1'	=> 'bold, italic, underline, link, bullist, numlist,strikethrough,blockquote,forecolor,undo,redo,',
					'toolbar2'	=> '',
					'toolbar3'	=> '',  
				), 		
			)
		); */
		?>
		<?php
		wp_editor(
			$wp_mods2,
			'wp_mods2',
			array(
				'textarea_name' => 'wp_mods2',
				'media_buttons' => false,
				'textarea_rows'  => 8,
				'teeny'          => true,                    // Enables a simpler ("teeny") editor
				'tinymce'        => array(
					'toolbar1' => 'bold,italic,underline,link,bullist,numlist,strikethrough,blockquote,forecolor,undo,redo',
					'toolbar2' => '',
					'toolbar3' => '',
					'plugins'  => 'lists,paste,textcolor',   // Required for the tools to work properly
					'branding' => false,
				),
				'quicktags' => array(
					'buttons' => 'strong,em,link,block,del,ins,img,ul,ol,li,code,close'
				),
			)
		);
		?>
		</div>
		
		</li> 
		
		</ul>
		</div>

		<?php endif; ?>
		
		</div>
		
		<!-- tab 1 -->		
		<div id="aps-tb-general" class="aps-tab-content <?php echo $is_new_post ? 'active' : ''; ?>">
		
		<div class="aps-group-inputs">
		
		<ul class="aps-features">
		
		<?php if ( $is_new_post ) : ?>	
		<li>	
		<div class="aps-col-3" style="">
		<label for="aps-sale-start">Enable Ads</label>	
		<label class="toggle_input" for="is_ads" style="text-transform:uppercase;background:unset;padding: 8px 9px;">
		<input type="checkbox" value="yes" id="is_ads" name="is_ads" <?php if ( isset ( $is_ads['is_ads'] ) ) checked( $is_ads['is_ads'][0], 'yes' ); ?> checked> 
		<span data-unchecked="no" data-checked="yes"></span>
		</label>
		<p><b>YES</b> to showing all ads on single post</p> 
		</div>
		</li>	
		<?php endif; ?>
		
		
		<li> 	
		<div class="aps-col-6" style="text-transform:uppercase">
		<label>Google Play Url</label> 
		<textarea class="aps-textarea"  id="wp_playstore_link" name="wp_playstore_link" placeholder="example : https://play.google.com/store/apps/details?id=com.roblox.client"><?= $wp_playstore_link ?></textarea>      
		</div>
		</li> 	
		
		<li>  
		<div class="aps-col-2" style="text-transform:uppercase">
		<label for="wp_GP_ID">Package name</label>
		<input type="text" id="wp_GP_ID" class=" aps-text-input" name="wp_GP_ID" value="<?php echo $titleID; ?>" placeholder="example : com.roblox.client" />  
		</div> 
		<div class="aps-col-2" style="text-transform:uppercase">
		<label for="wp_title_GP">apps Name</label>
		<input type="text" id="wp_title_GP" class=" aps-text-input" name="wp_title_GP" value="<?php echo $judul; ?>" placeholder="example : Roblox" />  
		</div>  
		<div class="aps-col-2" style="text-transform:uppercase">
		<label for="wp_developers_GP">developers</label>
		<input type="text" id="wp_developers_GP" class=" aps-text-input"  name="wp_developers_GP" value="<?php echo $developer; ?>" placeholder="example : Roblox Corporation" />
		</div>
		 
		</li> 	
		
		
		<li>  	
		
		
		<?php if ( $is_new_post ) : ?>	 
		<div class="aps-col-2" style="text-transform:uppercase">
		<label for="wp_version_GP">Version <small>(Playstore)</small></label>
		<input type="text" id="wp_version_GP" class="aps-date-input aps-text-input" name="wp_version_GP" value="<?php echo $version; ?>" placeholder="example : 2.522.280" />
		</div>	
		<?php endif; ?>
		
		<div class="aps-col-2" style="text-transform:uppercase">
		<label for="wp_version">version <small>(Sources) just ignore this</small></label>
		<input type="text" id="wp_version" class="aps-date-input aps-text-input" name="wp_version" value="<?php echo $version_web; ?>" placeholder="example : 2.522.280" /> 
		</div>
		
		
		<?php if ( $is_new_post ) : ?>	
		<div class="aps-col-2" style="text-transform:uppercase">
		<label for="wp_sizes">Size</label>
		<input type="text" id="wp_sizes" class=" aps-text-input" name="wp_sizes" value="<?php echo $sizes; ?>" placeholder="example : 250 mb"/>
		</div>		
		<?php endif; ?>	
		
		</li> 		
		
		<li>  
		<div class="aps-col-2" style="text-transform:uppercase">
		<label for="wp_requires_GP">OS </label>
		<input type="text" id="wp_requires_GP" class=" aps-text-input" name="wp_requires_GP" value="<?php echo $requires; ?>" placeholder="example : 4.4"/>
		</div>
		

		<?php if ( $is_new_post ) : ?>	
		<div class="aps-col-2" style="text-transform:uppercase">
		<label for="wp_updates_GP">updates</label>
		<input type="text" id="wp_updates_GP" class=" aps-text-input" name="wp_updates_GP" value="<?php echo $updates; ?>" placeholder="example : <?php echo get_the_date(); ?>"/>
		</div>	
		<?php endif; ?>	
		
		<div class="aps-col-2" style="text-transform:uppercase">
		<label for="wp_youtube_GP">youtube id</label>
		<input type="text" id="wp_youtube_GP" class=" aps-text-input" name="wp_youtube_GP" value="<?php echo $youtube; ?>" placeholder="example : T_rkoL9vt3g"/>
		</div> 
		</li> 	
		
		
		<li>
		<!--
		<div class="aps-col-2" style="text-transform:uppercase">
		<label for="wp_rated_GP">Rated</label>
		<input type="text" id="wp_rated_GP" class=" aps-text-input" name="wp_rated_GP" value="<?= $rated ?>" placeholder="example : 4.5"/>
		</div>
		
		<div class="aps-col-2" style="text-transform:uppercase">
		<label for="wp_ratings_GP">Voted</label>
		<input type="text" id="wp_ratings_GP" class=" aps-text-input" name="wp_ratings_GP" value="<?= $ratings ?>" placeholder="example : 123456"/> 
		</div>
		--> 
		
		<div class="aps-col-2" style="text-transform:uppercase">
		<label for="wp_prices_gp">prices</label>
		<input type="text" id="wp_prices_gp" class=" aps-text-input" name="wp_prices_gp" value="<?= $gp_prices ?>" placeholder="example : $4.99"/> 
		</div>	
		
		<?php if ( $is_new_post ) : ?>	
		<div class="aps-col-2" style="text-transform:uppercase">
		<label>Type <small>(if empty default use mod) </small></label> 
		<input type="text" id="wp_tipes" class=" aps-text-input" name="wp_tipes" value="<?= $tipes ?>" placeholder="example : free, premium or else"/>    
		</div> 
		<?php endif; ?>	
		
		
		</li> 	
		 
		
		</ul>
		
		</div>
		
		</div>

		<!-- tab 2 -->
		<div id="aps-tb-desc" class="aps-tab-content"> 
		<div class="aps-group-inputs">
		
		<ul class="aps-features">
		
		<li>
		<div class="aps-col-2" style="text-transform:uppercase">
		<label>Desc summary</label>
		</div>				
		<div class="aps-col-4"> 
		<textarea class="aps-textarea" name="wp_desck_GP" placeholder="example : Desc summary"><?= $desck ?></textarea>
		</div>
		</li>		
		
		<li>
		<div class="aps-col-2" style="text-transform:uppercase">
		<label>What's Latest News</label>
		</div>				
		<div class="aps-col-4">
		<?php 
		wp_editor( ($whatnews), 'wp_whatnews_GP', array(
			'textarea_name' => 'wp_whatnews_GP',
			'wpautop' => true,
			'media_buttons' => false, 
			'tabindex' => 1, 
			'textarea_rows' => 7, 
			'tinymce'       => array(
				'toolbar1'      => 'bold, italic, underline, link, bullist, numlist,strikethrough,blockquote,forecolor,undo,redo,',
				'toolbar2'      => '',
				'toolbar3'      => '',  
			), 		
		)); ?>
		</div>
		</li>	

		
		<?php if ( !empty($article_content) ) { ?> 
		<li>
		<div class="aps-col-2" style="text-transform:uppercase">
		<label>Article (Sources)</label>
		</div>				
		<div class="aps-col-4"> 
		<textarea onclick="this.select()" rows="6" readonly class="aps-textarea" name="wp_article_content" placeholder="example : Desc summary"><?= $article_content ?></textarea>
		</div>
		</li>		
		<?php } ?>
		</ul>
		
		</div>
		</div>		
		
		<!-- tab 3 -->
		<?php if ( $is_new_post ) : ?>	
		<div id="aps-tb-mods" class="aps-tab-content">
		<div class="aps-group-inputs">
		
		<ul class="aps-features">
		
		<li>
		<div class="aps-col-2" style="text-transform:uppercase">
		<label>Short Mod</label>
		</div>			
		<div class="aps-col-4"> 
		<textarea class="aps-textarea" name="wp_mods" placeholder="example : Mod menu"><?= $modfeatures ?></textarea>
		</div>	
		</li>		 
		
		<li>
		<div class="aps-col-2" style="text-transform:uppercase">
		<label>Full Mod</label>
		</div>				
		<div class="aps-col-4">
		<?php 
		wp_editor( ($wp_mods2), 'wp_mods2', array(
			'textarea_name' => 'wp_mods2',
			'wpautop' => true,
			'media_buttons' => false, 
			'tabindex' => 1, 
			'textarea_rows' => 7, 
			'tinymce'       => array(
				'toolbar1'      => 'bold, italic, underline, link, bullist, numlist,strikethrough,blockquote,forecolor,undo,redo,',
				'toolbar2'      => '',
				'toolbar3'      => '',  
			), 		
		)); ?>
		</div>
		</li>		
		</ul>
		
		</div>
		</div>
		<?php endif; ?>	

		<!-- tab 4 -->
		<div id="aps-tb-img" class="aps-tab-content ">
		<div class="aps-group-inputs">
		
		<ul class="aps-features">
		<li>
		<div class="aps-col-2" style="text-transform:uppercase">
		
		<div id="preview_poster_gp" style="margin-top: 15px; max-width: 400px;"> 
		<img src="<?= $postergp ?>" style="display: <?php  if ( !empty($postergp) ) {  ?>block<?php } else { ?>none<?php } ?>;margin-left: auto;margin-right: auto;width: 50%;" />
		</div>
		
		<!--<label>apps Poster</label>-->
		<a style="left: 5px !important;top: -10px !important;color: white;position: absolute;cursor: pointer;text-decoration: none;background: black;padding: 3px 15px;font-weight: 700;border-radius: 5px;">Poster img</a>
		</div>				
		<div class="aps-col-4">
		<textarea rows="4"  class="aps-textarea wp_poster_gp" name="wp_poster_GP" placeholder="example : https://play-lh.googleusercontent.com/xxxxxx"><?= $postergp ?></textarea>   
		</div>
		
		<div>  
		<a title="upload" class="delete-fieldset aps-btn-add upload_poster_gp" style="right: 16px !important;top: -10px !important;color: dodgerblue;position: absolute;cursor: pointer;"><span class="dashicons dashicons-cloud-upload"></span></a>
		</div>
		
		</li>
		
		<li>
		<div class="aps-col-2" style="text-transform:uppercase">
		
		<div id="preview_backgrounds_gp" style="margin-top: 15px; max-width: 400px;"> 
		<img src="<?= $background_gp ?>" style="display: <?php  if ( !empty($background_gp) ) {  ?>block<?php } else { ?>none<?php } ?>;margin-left: auto;margin-right: auto;width: 100%;" />
		</div>
		 
		
		  
		<!--<label>apps background images</label>-->
		<a style="left: 5px !important;top: -10px !important;color: white;position: absolute;cursor: pointer;text-decoration: none;background: black;padding: 3px 15px;font-weight: 700;border-radius: 5px;">background img</a>
		</div>				
		<div class="aps-col-4">
		<textarea rows="4"  class="aps-textarea wp_backgrounds_gp" name="wp_backgrounds_GP" placeholder="you can put the link image here or upload on background images"><?= $background_gp ?></textarea>   
		</div>
		
		<div>  
		<a title="upload" class="delete-fieldset aps-btn-add upload_backgrounds_gp" style="right: 16px !important;top: -10px !important;color: dodgerblue;position: absolute;cursor: pointer;"><span class="dashicons dashicons-cloud-upload"></span></a>
		</div>
		
		</li>	
		</ul>
		 
		<?php
		global $post;
		$gallery_data = get_post_meta( $post->ID, 'gallery_data', true ); // Perbaiki: $post_ids → $post->ID

		wp_nonce_field( 'gallery_img_list_nonce', 'gallery_img_list_nonce' );
		wp_enqueue_media(); // Penting untuk wp.media
		?>

		<ul id="gallery_images" class="aps-features">
			<?php
			if ( ! empty( $gallery_data['image_url'] ) && is_array( $gallery_data['image_url'] ) ) {
				foreach ( $gallery_data['image_url'] as $index => $image_url ) {
					if ( empty( $image_url ) ) continue;
					$image_url = esc_url( $image_url );
					?>
					<li class="field_row">
						<div class="aps-col-2 image_wrap" style="text-transform:uppercase">
							<img src="<?php echo $image_url; ?>" style="display:block;margin:10px auto;max-height:100px;width:auto;max-width:100%;" alt="Gallery Image" />
							<a class="image-number" style="left:5px;top:-10px;color:white;position:absolute;background:black;padding:3px 15px;font-weight:700;border-radius:5px;">
								Image #<?php echo $index + 1; ?>
							</a>
						</div>
						<div class="aps-col-4">
							<textarea class="aps-textarea meta_image_url" name="gallery[image_url][]" placeholder="Image URL will appear here"><?php echo $image_url; ?></textarea>
						</div>
						<div>
							<a title="Remove" class="delete-fieldset aps-btn-del" style="right:-10px;top:-10px;position:absolute;cursor:pointer;">
								<span class="dashicons dashicons-dismiss"></span>
							</a>
							<a title="Upload/Change Image" class="upload-gallery-image" style="right:20px;top:-10px;color:dodgerblue;position:absolute;cursor:pointer;">
								<span class="dashicons dashicons-cloud-upload"></span>
							</a>
						</div>
					</li>
					<?php
				}
			}
			?>
		</ul>

		<div id="new-rows-container"></div>

		<a id="add_gallery_new" class="aps-btn add-fieldset" style="color:#fff;background:#000;border:1px solid #000;padding:10px 20px;margin-top:15px;display:inline-block;text-decoration:none;border-radius:4px;cursor:pointer;">
			➕ Add New Image
		</a>

		<script type="text/javascript">
		// Vanilla JavaScript Only
		document.addEventListener('DOMContentLoaded', function () {
			const container     = document.getElementById('gallery_images');
			const newContainer  = document.getElementById('new-rows-container');
			const addButton     = document.getElementById('add_gallery_new');

			let imageCount = container.querySelectorAll('.field_row').length;

			// Update semua nomor gambar
			function updateImageNumbers() {
				const allRows = container.querySelectorAll('.field_row');
				allRows.forEach((row, index) => {
					const numberEl = row.querySelector('.image-number');
					if (numberEl) {
						numberEl.textContent = 'Image #' + (index + 1);
					}
				});
				imageCount = allRows.length;
			}

			// Tambah baris baru
			addButton.addEventListener('click', function (e) {
				e.preventDefault();
				imageCount++;

				const newRow = document.createElement('li');
				newRow.className = 'field_row';
				newRow.innerHTML = `
					<div class="aps-col-2 image_wrap" style="text-transform:uppercase">
						<div style="height:100px;background:#f1f1f1;border:2px dashed #ccc;display:flex;align-items:center;justify-content:center;color:#999;">
							No image yet
						</div>
						<a class="image-number" style="left:5px;top:-10px;color:white;position:absolute;background:black;padding:3px 15px;font-weight:700;border-radius:5px;">
							Image #${imageCount}
						</a>
					</div>
					<div class="aps-col-4">
						<textarea class="aps-textarea meta_image_url" name="gallery[image_url][]" placeholder="Image URL will appear after upload"></textarea>
					</div>
					<div>
						<a title="Remove" class="delete-fieldset aps-btn-del" style="right:-10px;top:-10px;position:absolute;cursor:pointer;">
							<span class="dashicons dashicons-dismiss"></span>
						</a>
						<a title="Upload Image" class="upload-gallery-image" style="right:20px;top:-10px;color:dodgerblue;position:absolute;cursor:pointer;">
							<span class="dashicons dashicons-cloud-upload"></span>
						</a>
					</div>`;

				container.appendChild(newRow);
			});

			// Event delegation untuk upload dan hapus
			document.addEventListener('click', function (e) {
				const target = e.target;

				// Hapus baris
				if (target.closest('.aps-btn-del')) {
					const row = target.closest('.field_row');
					if (row) {
						row.remove();
						updateImageNumbers();
					}
					return;
				}

				// Upload gambar
				if (target.closest('.upload-gallery-image')) {
					e.preventDefault();
					const button = target.closest('.upload-gallery-image');
					const row = button.closest('.field_row');
					const textarea = row.querySelector('.meta_image_url');
					const wrap = row.querySelector('.image_wrap');

					const uploader = wp.media({
						title: 'Choose Gallery Image',
						button: { text: 'Use this image' },
						multiple: false
					})
					.on('select', function () {
						const attachment = uploader.state().get('selection').first().toJSON();
						textarea.value = attachment.url;

						// Update preview
						wrap.innerHTML = `
							<img src="${attachment.url}" style="display:block;margin:10px auto;max-height:100px;width:auto;max-width:100%;" alt="Gallery Image" />
							<a class="image-number" style="left:5px;top:-10px;color:white;position:absolute;background:black;padding:3px 15px;font-weight:700;border-radius:5px;">
								Image #${imageCount}
							</a>`;
					})
					.open();
				}
			});

			// Update nomor saat load pertama
			updateImageNumbers();
		});
		</script>


	 
		
		</div>
		</div>

		<!-- tab 5 -->		
		<div id="aps-tb-download" class="aps-tab-content <?php echo $is_edit ? 'active' : ''; ?>">
		
		<div class="aps-group-inputs"> 

		<ul id="sort_table" class="">
		<?php
		global $opt_themes;
		$download_fields = get_post_meta($post_id, 'repeatable_fields', true);
		wp_nonce_field('download_list_nonce', 'download_list_nonce');
		wp_enqueue_media();

		if ($download_fields && is_array($download_fields)) {
			$number = 0;
			foreach ($download_fields as $row) {
			$number++;
			$file_id = !empty($row['file_id']) ? absint($row['file_id']) : '';
			$file_url = $file_id ? wp_get_attachment_url($file_id) : '';
			$name = !empty($row['name']) ? $row['name'] : (!empty($row['title']) ? $row['title'] : '');
			$url = !empty($row['url']) ? $row['url'] : (!empty($row['links']) ? $row['links'] : $file_url);
			$tipes = !empty($row['tipes']) ? $row['tipes'] : (!empty($row['tipe']) ? $row['tipe'] : '');
			$sizes = !empty($row['sizes']) ? $row['sizes'] : (!empty($row['sizes1']) ? $row['sizes1'] : (!empty($row['size']) ? $row['size'] : ''));
			$notes = !empty($row['notes']) ? $row['notes'] : '';
		?>
		<li class="aps-field-box default_row">
			<div class="aps-box-inside">
			
				<div class="aps-col-3">
					<label>Name</label>
					<textarea placeholder="example: roblox mod menu" class="aps-textarea" name="name[]"><?php echo esc_textarea($name); ?></textarea>
				</div>
				
				<div class="aps-col-3" style="position:relative;">
					<label>Link</label>
					<input type="hidden" name="file_id[]" class="file-id" value="<?php echo esc_attr($file_id); ?>">
					<textarea placeholder="example: your apk link" class="aps-textarea file-url" name="url[]"><?php echo esc_textarea($url); ?></textarea>
					
					<!-- Container tombol otomatis dari kanan -->
					<div class="upload-buttons-auto">
						<a href="<?php echo admin_url('admin.php?page=_options&tab=2'); ?>" target="_blank" class="upload-file-setting button">
							<span class="dashicons dashicons-admin-generic"></span> Setting
						</a>
						<button type="button" class="upload-file-button button">
							<span class="dashicons dashicons-cloud-upload"></span> Wp Media 
						</button>
						<button type="button" class="upload-ftp-button button">
							<span class="dashicons dashicons-cloud-upload"></span> FTP
						</button>
						<button type="button" class="upload-dropbox-button button">
							<span class="dashicons dashicons-cloud-upload"></span> Dropbox
						</button>  
						
					</div>
 
				</div>
				
				<div class="clear"></div>
				
				<div class="aps-col-2">
				<label>Type</label>
				<textarea rows="1" placeholder="apk, zip, obb, xapk" class="aps-textarea" name="tipes[]"><?php echo esc_textarea($tipes); ?></textarea>
				</div>
				
				<div class="aps-col-2">
				<label>Size</label>
				<textarea rows="1" placeholder="100mb" class="aps-textarea" name="sizes[]"><?php echo esc_textarea($sizes); ?></textarea>
				</div>
				
				<div class="aps-col-2">
				<label>Note</label>
				<textarea rows="1" placeholder="mod menu" class="aps-textarea" name="notes[]"><?php echo esc_textarea($notes); ?></textarea>
				</div>
				
				<div class="clear"></div>
			</div>
			<a style="left:5px;top:-10px;color:white;position:absolute;background:black;padding:3px 15px;font-weight:700;border-radius:5px;">Link #<?php echo $number; ?></a>
			<a class="delete-fieldset aps-btn-del" style="right:-10px;top:-10px;position:absolute;cursor:pointer;"><span class="dashicons dashicons-dismiss"></span></a>
		</li>
		<?php
			}
		}
		?>
		</ul>

		<div class="aps-add-download" style="margin-top:20px;">
			<a id="tambah_link_baru" class="aps-btn add-fieldset" style="color:#fff;background:#000;padding:10px 20px;border-radius:4px;cursor:pointer;display:inline-block;">
				Add Link
			</a>
		</div>
				
		<script type="text/javascript">
		jQuery(document).ready(function($) {
			var $list = $('#sort_table');
			var currentFtpRow = null;

			// Nonce AJAX - pastikan di-echo dari PHP
			var extensionNonce = '<?php echo wp_create_nonce("get_file_extension"); ?>';
			var sizeNonce      = '<?php echo wp_create_nonce("get_file_size"); ?>';

			// ========================================
			// DEBOUNCE HELPER
			// ========================================
			function debounce(func, delay) {
				let timer;
				return function(...args) {
					clearTimeout(timer);
					timer = setTimeout(() => func.apply(this, args), delay);
				};
			}

			// ========================================
			// AUTO FETCH EXTENSION
			// ========================================
			const fetchExtension = debounce(function($textarea) {
				const url = $textarea.val().trim();
				if (!url || url.length < 10 || !url.includes('.')) {
					$textarea.closest('.default_row').find('textarea[name="tipes[]"]').val('');
					return;
				}

				const $typeField = $textarea.closest('.default_row').find('textarea[name="tipes[]"]');

				$.post(ajaxurl, {
					action: 'get_file_extension',
					url: url,
					_ajax_nonce: extensionNonce
				}, function(response) {
					if (response.success && response.data.extension) {
						const currentVal = $typeField.val().trim();
						const defaultValues = ['', 'apk, zip, obb, xapk', 'apk, zip, obb, xapk, apks'];
						if (defaultValues.includes(currentVal)) {
							$typeField.val(response.data.extension);
						}
					}
				}, 'json').fail(function() {
					console.warn('Extension fetch failed:', url);
				});
			}, 800);

			// ========================================
			// AUTO FETCH FILE SIZE
			// ========================================
			const fetchFileSize = debounce(function($textarea) {
				const url = $textarea.val().trim();
				if (!url) {
					$textarea.closest('.aps-box-inside').find('textarea[name="sizes[]"]').val('');
					return;
				}

				const $sizeField = $textarea.closest('.aps-box-inside').find('textarea[name="sizes[]"]');
				$sizeField.val('Loading...');

				fetch(ajaxurl, {
					method: 'POST',
					credentials: 'same-origin',
					headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
					body: new URLSearchParams({
						action: 'get_file_size',
						url: url,
						_ajax_nonce: sizeNonce
					})
				})
				.then(r => r.json())
				.then(data => {
					$sizeField.val(data.success ? data.data.size : 'Error fetching size');
				})
				.catch(() => {
					$sizeField.val('Request failed');
				});
			}, 800);

			// ========================================
			// PROCESS URL: Jalankan kedua fitur sekaligus
			// ========================================
			function processUrl($urlTextarea) {
				if (!$urlTextarea || !$urlTextarea.length) return;
				fetchExtension($urlTextarea);
				fetchFileSize($urlTextarea);
			}

			// Trigger saat input/paste/change URL
			$(document).on('input paste change', '.file-url', function() {
				processUrl($(this));
			});

			// Saat load halaman, proses semua URL yang sudah ada
			$('.file-url').each(function() {
				if ($(this).val().trim()) {
					processUrl($(this));
				}
			});

			// ========================================
			// TAMBAH LINK BARU
			// ========================================
			$('#tambah_link_baru').on('click', function(e) {
				e.preventDefault();
				var count = $list.find('.default_row').length + 1;

				var rowHtml = `
				<li class="aps-field-box default_row">
					<div class="aps-box-inside">
						<div class="aps-col-3">
							<label>Name</label>
							<textarea placeholder="e.g. Roblox Mod Menu" class="aps-textarea" name="name[]"></textarea>
						</div>
						<div class="aps-col-3" style="position: relative;">
							<label>Link</label>
							<input type="hidden" name="file_id[]" class="file-id" value="">
							<textarea placeholder="https://domain.com/file.apk" class="aps-textarea file-url" name="url[]"></textarea>
							<div class="upload-buttons-auto">
								<a href="<?php echo admin_url('admin.php?page=_options&tab=2'); ?>" target="_blank" class="button">
									<span class="dashicons dashicons-admin-generic"></span> Setting
								</a>
								<button type="button" class="button upload-file-button" title="WordPress Media">
									<span class="dashicons dashicons-cloud-upload"></span> WP Media
								</button>
								<button type="button" class="button upload-ftp-button" title="FTP Upload">
									<span class="dashicons dashicons-cloud-upload"></span> FTP
								</button>
								<button type="button" class="button upload-dropbox-button" title="Dropbox">
									<span class="dashicons dashicons-cloud-upload"></span> Dropbox
								</button>
							</div>
						</div>
						<div class="clear"></div>
						<div class="aps-col-2">
							<label>Type</label>
							<textarea rows="1" placeholder="apk, zip, obb, xapk" class="aps-textarea" name="tipes[]"></textarea>
						</div>
						<div class="aps-col-2">
							<label>Size</label>
							<textarea rows="1" placeholder="e.g. 150 MB" class="aps-textarea" name="sizes[]"></textarea>
						</div>
						<div class="aps-col-2">
							<label>Note</label>
							<textarea rows="1" placeholder="e.g. Unlimited Money" class="aps-textarea" name="notes[]"></textarea>
						</div>
						<div class="clear"></div>
					</div>
					<a class="link-number" style="left:5px;top:-10px;color:white;position:absolute;background:black;padding:3px 15px;font-weight:700;border-radius:5px;">Link #${count}</a>
					<a class="delete-fieldset aps-btn-del" title="Hapus link ini">
						<span class="dashicons dashicons-dismiss"></span>
					</a>
				</li>`;

				$list.append(rowHtml);
			});

			// ========================================
			// HAPUS LINK & RENUMBER
			// ========================================
			$(document).on('click', '.delete-fieldset', function(e) {
				e.preventDefault();
				$(this).closest('.default_row').remove();

				$list.find('.default_row').each(function(i) {
					$(this).find('.link-number').text('Link #' + (i + 1));
				});
			});

			// ========================================
			// UPLOAD WORDPRESS MEDIA
			// ========================================
			$(document).on('click', '.upload-file-button', function(e) {
				e.preventDefault();
				var $row     = $(this).closest('.default_row');
				var $fileId  = $row.find('.file-id');
				var $fileUrl = $row.find('.file-url');

				var frame = wp.media({
					/* 
					title: 'Pilih atau Upload File',
					button: { text: 'Gunakan file ini' }, 
					*/
					multiple: false
				});

				frame.on('select', function() {
					var attachment = frame.state().get('selection').first().toJSON();
					$fileId.val(attachment.id);
					$fileUrl.val(attachment.url);
					processUrl($fileUrl); // Otomatis isi extension + size
				});

				frame.open();
			});

			// ========================================
			// UPLOAD DROPBOX
			// ========================================
			// Dropbox
			$(document).on('click', '.upload-dropbox-button', function(e) {
				e.preventDefault();
				var $row = $(this).closest('.default_row');
				Dropbox.choose({
					success: function(files) {
						$row.find('.file-url').val(files[0].link.replace('?dl=0','?dl=1'));
					},
					linkType: "direct",
					multiselect: false
				});
			});

			// ========================================
			// FTP MODAL & UPLOAD
			// ========================================
			$(document).on('click', '.upload-ftp-button', function(e) {
				e.preventDefault();
				currentFtpRow = $(this).closest('.default_row');
				$('#ftp-upload-modal').fadeIn(200);				
				$('#ftp-status').hide(); // Pastikan status hidden saat modal dibuka
				$('#ftp_files').hide();
			});

			// Tutup modal
			$('#ftp-upload-modal, .close-modal').on('click', function(e) {
				if ($(e.target).is('#ftp-upload-modal') || $(e.target).is('.close-modal')) {
					closeFtpModal();
				}
			});

			$(document).on('keyup', function(e) {
				if (e.key === "Escape" && $('#ftp-upload-modal').is(':visible')) {
					closeFtpModal();
				}
			});

			function closeFtpModal() {
				$('#ftp-upload-modal').fadeOut(200);
				$('#ftp-status').hide().html('').removeAttr('style'); // Hide & reset saat tutup 
				$('#ftp_files').hide(); // Hide lagi saat modal ditutup
				$('#ftp-host, #ftp-user, #ftp-pass, #ftp-port, #ftp-path, #ftp-public-domain, #ftp-file').val('');
			}

			// Cek Koneksi FTP
			$('#ftp-check-btn').on('click', function(e) {
				e.preventDefault();
				var host = $('#ftp-host').val().trim();
				var user = $('#ftp-user').val().trim();
				var pass = $('#ftp-pass').val();
				var port = $('#ftp-port').val().trim() || '21';

				if (!host || !user || !pass) {
					$('#ftp-status').show().html('Fill in Host, Username, and Password first!').css({color:'#d63638', background:'#fcecea'});
					$('#ftp_files').hide(); 
					return;
				}

				$('#ftp-status').show().html('Checking connection...').css({color:'#2271b1', background:'#e7f3fe'});

				$.post(ajaxurl, {
					action: 'check_ftp_connection',
					ftp_nonce: '<?php echo wp_create_nonce("ftp_upload_nonce"); ?>',
					host: host,
					user: user,
					pass: pass,
					port: port
				}, function(res) {
					if (res.success) {
						$('#ftp-status').show().html('Connection successful! Ready to upload.').css({color:'#46b450', background:'#e8f5e9'});
						$('#ftp_files').fadeIn(300);
					} else {
						$('#ftp-status').show().html('Error: ' + (res.data?.message || 'Login error')).css({color:'#d63638', background:'#fcecea'});
						$('#ftp_files').hide(); // Sembunyikan lagi kalau gagal
					}
				}, 'json');
			});

			// Upload FTP
			$('#ftp-upload-btn').on('click', function(e) {
				e.preventDefault();

				var fileInput = $('#ftp-file')[0];
				if (!fileInput.files.length) {
					alert('Select the file first!');
					return;
				}

				var publicDomain = $('#ftp-public-domain').val().trim();
				if (!publicDomain) {
					alert('Public domain URL is required!');
					return;
				}

				var fd = new FormData();
				fd.append('action', 'handle_ftp_upload');
				fd.append('ftp_nonce', '<?php echo wp_create_nonce("ftp_upload_nonce"); ?>');
				fd.append('file', fileInput.files[0]);
				fd.append('host', $('#ftp-host').val().trim());
				fd.append('user', $('#ftp-user').val().trim());
				fd.append('pass', $('#ftp-pass').val());
				fd.append('port', $('#ftp-port').val().trim() || '21');
				fd.append('path', $('#ftp-path').val().trim());
				fd.append('public-domain', publicDomain);

				$('#ftp-status').show().html('Uploading files... Don\'t close the page.').css({color:'#2271b1', background:'#e7f3fe'});

				$.ajax({
					url: ajaxurl,
					type: 'POST',
					data: fd,
					processData: false,
					contentType: false,
					timeout: 600000,
					success: function(res) {
						if (res.success) {
							currentFtpRow.find('.file-url').val(res.data.url);
							processUrl(currentFtpRow.find('.file-url')); // Otomatis isi extension + size
							closeFtpModal();
							alert('Upload successful! Type and Size are automatically filled in.');
						} else {
							$('#ftp-status').show().html('Upload failed: ' + (res.data?.message || 'Error')).css({color:'#d63638', background:'#fcecea'});
						}
					},
					error: function() {
						$('#ftp-status').show().html('Connection/upload error.').css({color:'#d63638', background:'#fcecea'});
					}
				});
			});
		});
		</script>
		
		</div>
		</div>
		
		<!-- tab 7 -->
		<div id="aps-tb-donate" class="aps-tab-content">
		<div class="aps-group-inputs"> 	 
		
		<?php echo do_shortcode('[donasi]'); ?>	
	 
		</div>
		</div>
		 
		</div>
		<!-- close tab container -->

		</div>
		
		</div>

	
	<?php 
	}
}

if ( !function_exists( 'upload_modal' ) ) 
{	
	add_action( 'admin_footer-post.php', 'upload_modal',  );
	add_action( 'admin_footer-post-new.php', 'upload_modal',  );

	function upload_modal() 
	{ 
		global $opt_themes;
	?>

		<!-- CSS Responsif: Hanya ubah tombol saat layar kecil -->
		<style type="text/css">
		.upload-buttons-auto {position: absolute;top: 3px;left: 50px;display: flex;gap: 12px;z-index: 10;}.upload-buttons-auto .button {color: dodgerblue;background: transparent;border: none;padding: 0;font-size: 14px;line-height: 1.6;cursor: pointer;display: flex;align-items: center;gap: 5px;box-shadow: none;min-height: auto;}.upload-buttons-auto .button:hover {color: #0066cc;text-decoration: none;}.upload-buttons-auto .dashicons {font-size: 16px;width: 16px;height: 16px;}@media (max-width: 768px) {.upload-buttons-auto {position: static;display: block;margin-top: 10px;}.upload-buttons-auto .button {display: block !important;width: 100% !important;margin-bottom: 6px !important;text-align: left !important;background: #f9f9f9 !important;border: 1px solid #ddd !important;border-radius: 4px !important;padding: 10px 12px !important;color: dodgerblue;font-size: 14px;justify-content: flex-start;}.upload-buttons-auto .dashicons {margin-right: 10px;font-size: 18px;}}.upload-file-button, .upload-gdrive-button, .upload-dropbox-button, .upload-ftp-button {}@media (max-width: 768px) {.aps-col-3 {position: relative !important;}.upload-file-button, .upload-gdrive-button, .upload-dropbox-button, .upload-ftp-button, .upload-ftp-setting {position: static !important;display: block !important;width: 100% !important;margin-bottom: 4px !important;text-align: left !important;background: #f9f9f9 !important;border: 1px solid #ddd !important;border-radius: 4px !important;top: auto !important;right: auto !important;box-sizing: border-box !important;}.upload-file-button span, .upload-gdrive-button span, .upload-dropbox-button span, .upload-ftp-button span, .upload-ftp-setting span {margin-right: 8px;}}@keyframes fadeIn {from {opacity: 0;transform: scale(0.95);}to {opacity: 1;transform: scale(1);}}		 
		</style> 
		
		<!-- Modal FTP Upload - Sudah Tengah Layar -->
		<div id="ftp-upload-modal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.7); z-index:9999;">
			<div style="background:#fff; width:90%; max-width:500px; margin:50px auto; padding:20px; border-radius:8px; position:relative;">
			
			<h3 style="text-align:center;">Upload via FTP</h3>

			<div id="ftp-status" style="
				padding:14px;
				border-radius:6px;
				text-align:center;
				font-weight:600;
				min-height:50px;
				display:flex;
				align-items:center;
				justify-content:center;
			"></div>
			
			<div style="display:flex; gap:15px; flex-wrap:wrap;margin-bottom:20px;">
				<div style="flex:2; min-width:280px;">
				<label>Server (Host)</label>
				<input type="text" id="ftp-host" placeholder="103.123.45.67 or ftp.domain.com" style="width:100%;border:1px solid #ccc; border-radius:8px; box-sizing:border-box;" value="<?php echo $opt_themes['ftp_host']; ?>" >
				</div>
				<div style="flex:1; min-width:120px;">
				<label>Port</label>
				<input type="number" id="ftp-port" style="width:100%;border:1px solid #ccc; border-radius:8px; box-sizing:border-box;" value="<?php echo $opt_themes['ftp_port']; ?>" >
				</div>
			</div>

			<div style="display:flex; gap:15px; flex-wrap:wrap;margin-bottom:20px;">
			<!-- Username -->
			<div style="flex:2; min-width:200px;">
				<label>Username</label>
				<input type="text" id="ftp-user" style="width:100%;border:1px solid #ccc; border-radius:8px; box-sizing:border-box;" value="<?php echo $opt_themes['ftp_username']; ?>" >
			</div>

			<!-- Password -->
			<div style="flex:1; min-width:200px;">
				<label>Password</label>
				<input type="password" id="ftp-pass" style="width:100%;border:1px solid #ccc; border-radius:8px; box-sizing:border-box;" value="<?php echo $opt_themes['ftp_password']; ?>" >
			</div>
			
			</div>

			<div style="display:flex; gap:15px; flex-wrap:wrap;margin-bottom:20px;">
			<div style="flex:1; min-width:240px;">
			<!-- Remote Path -->
				<label>Remote Path</label>
				<input type="text" id="ftp-path" placeholder="/www/wwwroot/domain.com/" style="width:100%;border:1px solid #ccc; border-radius:8px; box-sizing:border-box;" value="<?php echo $opt_themes['ftp_path']; ?>" >
			</div>
			<div style="flex:1; min-width:160px;">
			<!-- Public Domain -->
				<label>Public Domain</label>
				<input type="text" id="ftp-public-domain" placeholder="https://domain.com" style="width:100%;border:1px solid #ccc; border-radius:8px; box-sizing:border-box;" value="<?php echo $opt_themes['ftp_public_domain']; ?>" >
			</div>
			</div>
			
			<div style="display:flex; gap:15px; flex-wrap:wrap;margin-bottom:20px;">
				<div style="flex:1; max-width: 70px;line-height: 1.5rem;">
				<label>Select File</label>
				</div>
				
				<div style="flex:1; min-width:160px;" id="ftp_filesx" >
				<!-- Pilih File -->				
				<input type="file" id="ftp-file" style="width:100%;border:1px solid #ccc; border-radius:8px; box-sizing:border-box;">
				</div>
			
			</div>

			<!-- Tombol Aksi -->
			<div style="text-align:right;margin-top:20px; ">
				<button type="button" id="ftp-check-btn" class="button" style="padding:12px 24px; margin-right:12px; border-radius:8px; font-size:15px;">Check FTP Status</button>
				<button type="button" id="ftp-upload-btn" class="button button-primary" style="padding:12px 28px; border-radius:8px; font-size:15px;">Upload File</button>
			</div>
			</div>
		</div>
	 
		
		<!-- Dropbox Script -->
		<script src="https://www.dropbox.com/static/api/2/dropins.js" id="dropboxjs" data-app-key="<?php echo $opt_themes['dropbox_app_key']; ?>"></script>
		
		
		<!-- google Script -->
		<script src="https://apis.google.com/js/api.js"></script>
		<script src="https://apis.google.com/js/platform.js"></script>

	<?php	
	}	
}
	
if ( !function_exists( 'save_info_post' ) ) 
{
	function save_info_post( $post_id ) 
	{ 
		if ( 'page' == @$_REQUEST['post_type'] ) {
			if ( ! current_user_can( 'edit_page', $post_id ) )
				return;
		} else {
			if ( ! current_user_can( 'edit_post', $post_id ) )
				return;
		}
		$wpwm_meta = array( 
			'post_ID', 
			'wp_GP_ID',  
			'wp_title_GP',
			'wp_developers_GP',
			'wp_version_GP',
			'wp_version', 
			'wp_sizes',
			'wp_sizes_GP',
			'wp_installs_GP',
			'wp_requires_GP',
			'wp_updates_GP',
			'wp_rated_GP',
			'wp_ratings_GP',
			'wp_persen_GP',
			'wp_whatnews_GP',
			'wp_youtube_GP',
			'wp_desck_GP',
			'wp_poster_GP',
			'wp_backgrounds_GP',
			'wp_images_GP',
			'wp_newupdates', 
			'wp_mods',
			'wp_mods2',
			'wp_mods_post',
			'wp_mods_post2',
			'wp_mods_post3',
			'wp_title_wp_mods',
			'wp_title_wp_mods_2',
			'wp_title_wp_mods_3',
			'wp_tipes',
			'wp_cpu',
			'wp_playstore_link',
			'wp_prices_gp',
			'wp_article_content',
			'label_1',
			'label_2',
		);
		 
		$post_ID = @$_POST['post_ID'];
		foreach ($wpwm_meta as $meta_key) {
			if(isset($_POST[$meta_key])) update_post_meta($post_ID, $meta_key, $_POST[$meta_key]);
		}
		if( isset( $_POST[ 'is_premium' ] ) ) {
			update_post_meta( $post_id, 'is_premium', 'yes' );
		} else {
			update_post_meta( $post_id, 'is_premium', 'no' );
		}
		if( isset( $_POST[ 'is_free' ] ) ) {
			update_post_meta( $post_id, 'is_free', 'yes' );
		} else {
			update_post_meta( $post_id, 'is_free', 'no' );
		}
		
		if( isset( $_POST[ 'is_ads' ] ) ) {
			update_post_meta( $post_id, 'is_ads', 'yes' );
		} else {
			update_post_meta( $post_id, 'is_ads', 'no' );
			//delete_post_meta( $post_id, 'is_ads');
		}
		
		
		// Save the checkbox: 'yes' if checked, 'no' if unchecked
		//$is_ads = isset( $_POST['is_ads'] ) ? 'yes' : 'no';
		//$is_ads = isset( $_POST['is_ads'] ) && $_POST['is_ads'] === 'yes' ? 'yes' : 'no';
		//update_post_meta( $post_id, 'is_ads', $is_ads );

		/* if ( isset( $_POST['is_ads'] ) ) {
			update_post_meta( $post_id, 'is_ads', 'yes' );
		} else {
			update_post_meta( $post_id, 'is_ads', 'no' );  // Explicitly save 'no'
		} */
		// Checkbox (is_ads)
		//$is_ads = isset( $_POST['is_ads'] ) && $_POST['is_ads'] === 'yes' ? 'yes' : 'no';
		//update_post_meta( $post_id, 'is_ads', $is_ads );

		if( isset( $_POST[ 'wp_version_GP' ] ) ) {
			//delete_post_meta( $post_id, 'update_available' );
			//delete_post_meta( $post_id, 'available_version' );
		}
		  
		  
	}
	add_action( 'save_post', 'save_info_post' );
}

if ( !function_exists( 'download_list_meta_box_save' ) ) 
{
    add_action('save_post', 'download_list_meta_box_save');
    function download_list_meta_box_save( $post_id ) 
	{
        if ( ! isset( $_POST['download_list_nonce'] ) || ! wp_verify_nonce( $_POST['download_list_nonce'], 'download_list_nonce' ) ) return;
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
        if ( ! current_user_can( 'edit_post', $post_id ) ) return;

        $meta_key = 'repeatable_fields';
        $new = array(); 
		
        if (isset($_POST['name'])) {
            $names = $_POST['name'] ?? [];
			$urls  = $_POST['url'] ?? [];
			$tipes = $_POST['tipes'] ?? [];
			$sizes = $_POST['sizes'] ?? [];
			$notes = $_POST['notes'] ?? [];
			$file_ids = $_POST['file_id'] ?? [];

            foreach ( $names as $i => $name ) {
                $name = trim( $name );
                $url  = trim( $urls[ $i ] ?? '' );

                if ( $name === '' && $url === '' ) continue;

                $new[] = array(
                    'name'    => sanitize_text_field( $name ),
                    'url'     => esc_url_raw( $url ),
                    'tipes'   => sanitize_text_field( $tipes[ $i ] ?? '' ),
                    'sizes'   => sanitize_text_field( $sizes[ $i ] ?? '' ),
                    'notes'   => sanitize_textarea_field( $notes[ $i ] ?? '' ),
                    'file_id' => ! empty( $file_ids[ $i ] ) ? absint( $file_ids[ $i ] ) : '',
                );
            }
        }

        if ( ! empty( $new ) ) {
            update_post_meta( $post_id, $meta_key, $new );
        } else {
            delete_post_meta( $post_id, $meta_key );
        }
    }
}

if ( !function_exists( 'list_gallery_image_updates' ) ) 
{
    add_action( 'save_post', 'list_gallery_image_updates', 10, 2 );

    /**
     * Save gallery images meta data
     *
     * @param int     $post_id Post ID.
     * @param WP_Post $post    Post object.
     */
    function list_gallery_image_updates( $post_id, $post ) 
	{
        // Verify nonce
        if ( ! isset( $_POST['gallery_img_list_nonce'] ) || ! wp_verify_nonce( $_POST['gallery_img_list_nonce'], 'gallery_img_list_nonce' ) ) {
            return;
        }

        // Skip autosaves
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }

        // Skip revisions
        if ( 'revision' === $post->post_type ) {
            return;
        }

        // Check permissions
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }

		$meta_key 	= 'gallery_data';
        $old_data 	= get_post_meta( $post_id, $meta_key, true );
        $new_data 	= array( 'image_url' => array() );

        // Process submitted gallery URLs
        if ( ! empty( $_POST['gallery']['image_url'] ) && is_array( $_POST['gallery']['image_url'] ) ) {
            foreach ( $_POST['gallery']['image_url'] as $image_url ) {
                $image_url = trim( $image_url );

                // Only save valid, non-empty URLs
                if ( '' !== $image_url && esc_url_raw( $image_url ) === $image_url ) {
                    $new_data['image_url'][] = esc_url_raw( $image_url );
                }
            }
        }

        // Update or delete meta
        if ( ! empty( $new_data['image_url'] ) ) {
            if ( $new_data !== $old_data ) {
                update_post_meta( $post_id, $meta_key, $new_data );
            }
        } else {
            // No images left → delete meta
            delete_post_meta( $post_id, $meta_key );
        }
    }
}

if ( !function_exists( 'get_file_extension_callback' ) ) 
{
    add_action('wp_ajax_get_file_extension', 'get_file_extension_callback');

    function get_file_extension_callback()
    {
        // Cek hak akses
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(['message' => 'Permission denied']);
        }

        $url = isset($_POST['url']) ? esc_url_raw($_POST['url']) : '';
        if (empty($url)) {
            wp_send_json_error(['message' => 'Invalid URL']);
        }

        $extension = '';

        // 1. Ambil dari path URL
        $path = parse_url($url, PHP_URL_PATH);
        if ($path) {
            $extension = pathinfo($path, PATHINFO_EXTENSION);
        }

        // 2. Jika kosong, coba dari query string (contoh: ?ext=apk)
        if (empty($extension)) {
            parse_str(parse_url($url, PHP_URL_QUERY), $query);
            if (isset($query['ext'])) {
                $extension = $query['ext'];
            }
        }

        // Bersihkan dan ubah ke lowercase
        $extension = strtolower(trim($extension));

        // Daftar ekstensi yang diizinkan (khusus download APK/mod)
        $valid_extensions = ['apk', 'zip', 'obb', 'xapk', 'apks', 'rar', '7z' ];
		
		wp_send_json_success(['extension' => $extension]);		
		
        /* 
		if (in_array($extension, $valid_extensions, true)) {
            wp_send_json_success(['extension' => $extension]);
        } else {
            wp_send_json_success(['extension' => '']); // Bukan ekstensi yang diharapkan
        } 
		*/
    }
}

if ( !function_exists( 'add_file_extension_js' ) ) 
{
    add_action('admin_footer-post.php', 'add_file_extension_js');
    add_action('admin_footer-post-new.php', 'add_file_extension_js');

    function add_file_extension_js()
    {
        // Pastikan hanya dijalankan di layar edit post
        $screen = get_current_screen();
        if (!$screen || $screen->base !== 'post') {
            return;
        }
        ?>
		<script type="text/javascript">
        jQuery(document).ready(function($) {
            function debounce(func, delay) {
                let timer;
                return function(...args) {
                    clearTimeout(timer);
                    timer = setTimeout(() => func.apply(this, args), delay);
                };
            }

            const fetchExtension = debounce(function($textarea) {
                const url = $textarea.val().trim();
                const $row = $textarea.closest('.default_row');
                if (!$row.length) return;

                const $typeField = $row.find('textarea[name="tipes[]"]');
                if (!$typeField.length) return;

                // Kosongkan jika URL kosong
                if (url === '') {
                    $typeField.val('');
                    return;
                }

                // Validasi sederhana
                if (url.length < 10 || !url.includes('.')) return;

                $.post(ajaxurl, {
                    action: 'get_file_extension',
                    url: url
                }, function(response) {
                    if (response.success) {
                        const ext = response.data.extension || '';
                        if (ext) {
                            const currentVal = $typeField.val().trim();
                            const defaultValues = ['', 'apk, zip, obb, xapk', 'apk, zip, obb, xapk, apks'];

                            if (defaultValues.includes(currentVal)) {
                                $typeField.val(ext);
                            }
                        }
                        // Jika ext kosong (tidak valid), biarkan field tetap (jangan kosongkan paksa)
                    }
                }, 'json').fail(function() {
                    console.warn('Failed to retrieve file extension from URL');
                });
            }, 800);

            // Saat halaman dimuat: cek semua URL yang sudah ada
            $('.file-url').each(function() {
                if ($(this).val().trim() !== '') {
                    fetchExtension($(this));
                }
            });

            // Event listener untuk perubahan URL (manual input/paste)
            $(document).on('input paste change', '.file-url', function() {
                fetchExtension($(this));
            });
        });
        </script>
        <?php
    }
}

if ( !function_exists( 'get_file_size_callback' ) ) 
{
    add_action('wp_ajax_get_file_size', 'get_file_size_callback');

    function get_file_size_callback() 
	{
        // Check permissions
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(['message' => 'Permission denied']);
        }

        $url = isset($_POST['url']) ? esc_url_raw($_POST['url']) : '';
        if (empty($url)) {
            wp_send_json_error(['message' => 'Invalid URL']);
        }

        // Create context for HEAD request
        $context = stream_context_create([
            'http' => [
                'method' => 'HEAD',
                'timeout' => 25,
                'follow_location' => 1,
                'header' => "User-Agent: Mozilla/5.0 (WordPress File Size Checker)\r\n" .
                            "Referer: " . home_url() . "\r\n"
            ],
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            ]
        ]);

        $headers = @get_headers($url, true, $context);

        if ($headers && isset($headers['Content-Length'])) {
            $bytes = is_array($headers['Content-Length']) 
                ? end($headers['Content-Length']) 
                : $headers['Content-Length'];

            $size = format_download_size((int)$bytes);
            wp_send_json_success(['size' => $size]);
        } else {
            wp_send_json_error(['message' => '']);
        }
    }
}

if ( !function_exists( 'format_download_size' ) ) 
{
    function format_download_size($bytes) 
	{
        $bytes = max((int)$bytes, 0);
        $units = ['bytes', 'KB', 'MB', 'GB', 'TB'];
        $i = 0;
        while ($bytes >= 1024 && $i < count($units) - 1) {
            $bytes /= 1024;
            $i++;
        }
        return round($bytes, 2) . ' ' . $units[$i];
    }
}

if ( !function_exists( 'add_file_size_js' ) ) 
{
    add_action('admin_footer-post.php', 'add_file_size_js');
    add_action('admin_footer-post-new.php', 'add_file_size_js');

    function add_file_size_js() 
	{
        // Only run on relevant screens
        $screen = get_current_screen();
        if (!$screen || $screen->base !== 'post') return;
        ?>
        <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', function () {
            const table = document.getElementById('sort_table');
            if (!table) return;

            // Debounce helper
            function debounce(func, wait) {
                let timeout;
                return function executedFunction(...args) {
                    const later = () => {
                        clearTimeout(timeout);
                        func(...args);
                    };
                    clearTimeout(timeout);
                    timeout = setTimeout(later, wait);
                };
            }

            // Main handler
            const handleUrlChange = debounce(function(textarea) {
                const url = textarea.value.trim();
                const box = textarea.closest('.aps-box-inside');
                if (!box) return;

                const sizeTextarea = box.querySelector('textarea[name="sizes[]"]');
                if (!sizeTextarea) return;

                if (!url) {
                    sizeTextarea.value = '';
                    return;
                }

                sizeTextarea.value = 'Loading...';

                fetch(ajaxurl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'get_file_size',
                        url: url,
                        _ajax_nonce: '<?php echo wp_create_nonce("get_file_size"); ?>' // Optional: add nonce for extra security
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        sizeTextarea.value = data.data.size;
                    } else {
                        sizeTextarea.value = data.data?.message || 'Error fetching size';
                    }
                })
                .catch(() => {
                    sizeTextarea.value = 'Request failed';
                });
            }, 600);

            // Use event delegation
            table.addEventListener('input', function(e) {
                if (e.target.matches('textarea[name="url[]"]')) {
                    handleUrlChange(e.target);
                }
            });

            table.addEventListener('paste', function(e) {
                if (e.target.matches('textarea[name="url[]"]')) {
                    // Small delay to let paste complete
                    setTimeout(() => handleUrlChange(e.target), 100);
                }
            });
        });
        </script>
        <?php
    }
}

if ( !function_exists( 'check_ftp_connection_callback' ) ) 
{
	add_action('wp_ajax_check_ftp_connection', 'check_ftp_connection_callback');
	function check_ftp_connection_callback() 
	{
		// Verifikasi nonce untuk keamanan
		check_ajax_referer('ftp_upload_nonce', 'ftp_nonce');

		// Pastikan user punya hak upload
		if (!current_user_can('upload_files')) {
			wp_send_json_error(['message' => 'Permission denied: You do not have permission to upload the file.']);
		}

		// Ambil data dari POST
		$host = sanitize_text_field($_POST['host'] ?? '');
		$user = sanitize_text_field($_POST['user'] ?? '');
		$pass = $_POST['pass'] ?? ''; 
		$port = intval($_POST['port'] ?? 21);

		if (empty($host) || empty($user)) {
			wp_send_json_error(['message' => 'Host and Username are required.']);
		}

		// Tes koneksi FTP (timeout 10 detik)
		$conn = @ftp_connect($host, $port, 10);
		if (!$conn) {
			wp_send_json_error(['message' => 'Failed to connect to server. Check host/port or firewall.']);
		}

		// Tes login
		if (!@ftp_login($conn, $user, $pass)) {
			@ftp_close($conn);
			wp_send_json_error(['message' => 'Incorrect username or password.']);
		}

		// Jika sampai sini → sukses
		@ftp_close($conn);
		wp_send_json_success(['message' => 'FTP connection successful!']);
	}
}

if ( !function_exists( 'handle_ftp_upload_callback' ) ) 
{
	add_action('wp_ajax_handle_ftp_upload', 'handle_ftp_upload_callback');
	function handle_ftp_upload_callback() 
	{
		// Verifikasi nonce
		check_ajax_referer('ftp_upload_nonce', 'ftp_nonce');

		// Cek hak user
		if (!current_user_can('upload_files')) {
			wp_send_json_error(['message' => 'Permission denied: You do not have permission to upload the file.']);
		}

		// Ambil data
		$host 			= sanitize_text_field($_POST['host'] ?? '');
		$user 			= sanitize_text_field($_POST['user'] ?? '');
		$pass 			= $_POST['pass'] ?? '';
		$port 			= intval($_POST['port'] ?? 21);
		$public_domain 	= $_POST['public-domain'];

		if (empty($host) || empty($user)) {
			wp_send_json_error(['message' => 'Host and Username are required.']);
		}

		if (empty($_FILES['file']['name'])) {
			wp_send_json_error(['message' => 'No files uploaded.']);
		}

		$uploaded_file = $_FILES['file'];
		$filename      = sanitize_file_name($uploaded_file['name']);
		$tmp_path      = $uploaded_file['tmp_name'];

		$conn = @ftp_connect($host, $port, 15);
		if (!$conn) {
			wp_send_json_error(['message' => 'Failed to connect to FTP server. Check host/port/firewall.']);
		}

		if (!@ftp_login($conn, $user, $pass)) {
			@ftp_close($conn);
			wp_send_json_error(['message' => 'FTP login failed (wrong username/password).']);
		}

		@ftp_set_option($conn, FTP_USEPASVADDRESS, false);

		if (!@ftp_pasv($conn, true)) {
			@ftp_close($conn);
			wp_send_json_error(['message' => 'Failed to enable passive mode. Firewall issue?']);
		}

		// Upload langsung ke home directory FTP (tanpa chdir)
		if (!@ftp_put($conn, $filename, $tmp_path, FTP_BINARY)) {
			@ftp_close($conn);
			wp_send_json_error(['message' => 'Upload failed. Check write permissions on the FTP home folder.']);
		}

		@ftp_close($conn);

		// === OTOMATIS ISI FIELD LINK ===
		// Ganti https://demo88.com/ dengan domain utama situs kamu
		$public_url = $public_domain . '/' . $filename;

		// Jika kamu upload ke subfolder manual (misal /files), ubah jadi:
		// $public_url = 'https://file.exthem.es/' . $filename;

		wp_send_json_success([
			'url' => $public_url,
			'message' => 'File uploaded successfully! Link filled automatically.'
		]);
	}
}

if ( !function_exists( 'metabox_scripts' ) ) 
{
	add_action( 'admin_footer-post.php', 'metabox_scripts',  );
	add_action( 'admin_footer-post-new.php', 'metabox_scripts',  );

	function metabox_scripts() 
	{ 
		global $post;
		if( 'post' != $post->post_type ) 
		return;
		?>  
		<link rel="stylesheet" href="<?php echo EX_THEMES_URI; ?>/libs/addons/assets/css_2/aps-admin.css">  
		 
		<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> 

		<!--
		<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.14.0/jquery-ui.min.js" integrity="sha512-MlEyuwT6VkRXExjj8CdBKNgd+e2H+aYZOCUaCrt9KRk6MlZDOs91V1yK22rwm8aCIsb5Ec1euL8f0g58RKT/Pg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
		-->

		<style>
		.toggle_input {display: block;width: 15em;background: lavender;padding: 0.125em;cursor: pointer;}.toggle_input input {position: absolute;visibility: hidden;}.toggle_input span {position: relative;left: 0%;display: block;text-transform: uppercase;text-align: center;-webkit-transition: left 200ms ease-out;-moz-transition: left 200ms ease-out;-o-transition: left 200ms ease-out;transition: left 200ms ease-out;}.toggle_input :checked ~ span {left: 50%;}.toggle_input span:before {content: attr(data-unchecked);display: block;width: 50%;background-color: red;border-radius: 0.15em;box-shadow: inset 0 0.1em 0 rgba(255, 255, 255, 0.3);color: #fff;}.toggle_input :checked ~ span:before {content: attr(data-checked);background-color: green;}.tb-title {display: none;}.aps-box-inside {padding-left: unset;cursor: move;}.aps-field-box .aps-btn-del {right: -10px!important;top: -10px!important;color: red!important;}div.aps-box-inside div label {text-transform: capitalize !important;}.ignielDonasi {--background: #f9f9f9;--backgroundHover: #f0f0f0;--color: #2f2f2f;--colorHover: #2f2f2f;--icon: #5c5c5c;--col: 2;margin-top: 2rem;}.ignielDonasi path {fill: none;stroke: var(--icon);stroke-width: 1.5px;stroke-linecap: round;stroke-linejoin: round;stroke-miterlimit: 10;}.ignielDonasi svg:first-child {height: 2rem;width: 35px;}.ignielDonasi svg:last-child {height: 1rem;width: 1rem;}.ignielDonasi-judul {font-weight: 700;margin-bottom: 1rem;}.ignielDonasi img {width: 35px;}.ignielDonasi-ikon {margin-right: 1rem;}.ignielDonasi-isi {display: grid;gap: 1rem;grid-template-columns: repeat(var(--col), 1fr);}.ignielDonasi-isi a {align-items: center;background-color: var(--background);border-radius: 7px;color: var(--color);display: flex;gap: 1rem;padding: .75rem 1.25rem;text-decoration: none;transition: all .3s;}.ignielDonasi-isi a:hover {background-color: var(--backgroundHover);color: var(--colorHover);text-decoration: none;}.ignielDonasi-isi .wallet {flex-direction: column;}.ignielDonasi-isi .wallet i {display: block;font-size: 11px;font-style: normal;line-height: 13px;}.ignielDonasi-isi a, .ignielDonasi-isi a span {flex-grow: 1;}@media screen and (max-width: 768px) {.ignielDonasi-isi {grid-template-columns: repeat(2, 1fr);}}@media screen and (max-width: 568px) {.ignielDonasi-isi {grid-template-columns: repeat(1, 1fr);}}.ignielDonasi-isi a span {font-weight: 700;}
		</style>

		<script> 
		//<![CDATA[
		eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('6 $k=l.m();$(\'7#n\').o(1(){$(0).8({9:c.p(4,c.q($(0).r().s/0.t))},d)});$(\'7#n\').u(1(){$(0).8({9:2},d);$(0).f({v:\'\'});$(0).f({w:\'\'})});$("x.h-i-y z").K(1(){6 a=$(0);L(!a.M("3")){$("x.h-i-y z").A("3");a.B("3");$(".h-C-N").A("3");6 b=a.i("C");$(b).B("3")}});6 $k=l.m();$("#j").O({P:1(){$("#j").D("E").F(\'G.g-5 H.g-5\',1(e){e.I()})}}).5();$("#j").D("E").F(\'G.g-5 H.g-5\',1(e){e.I()});$(\'7#J\').o(1(){$(0).8({9:c.p(4,c.q($(0).r().s/0.t))},d)});$(\'7#J\').u(1(){$(0).8({9:4},d);$(0).f({v:\'\'});$(0).f({w:\'\'})});',52,52,'this|function||active||disableSelection|var|textarea|animate|rows|||Math|500||css|ui|aps|data|sort_table|EXHEMES_DEV_BLOG|jQuery|noConflict|autoheight|focus|max|ceil|val|length|cols|blur|height|width|ul|tabs|li|removeClass|addClass|tab|find|input|bind|mousedown|selectstart|stopImmediatePropagation|autoheights_img|click|if|hasClass|content|sortable|stop'.split('|'),0,{}));
		//]]>
		</script>

		<script>
		//<![CDATA[
		eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('3.5(\'g\').h(\'i\',7(e){j 0=e.8.0;k(0.9(\'v\')||0.9(\'l\')){0=0.m(1);e.8.0=0}3.5(\'n\').0=0});7 o(){2 a=3.5(\'b\');2 6=3.p(\'b\');2 c=q r();2 d={s:\'t\',u:\'f\',w:\'f\'};2 4=c.x(\'y-z\',d);a.0=4;6.0=4;6.A(4)}',37,37,'value||const|document|formattedDate|getElementById|dateField2|function|target|startsWith|dateField|wp_updates_GP|currentDate|options||numeric|wp_version|addEventListener|input|let|if|V|substring|wp_version_GP|updateDate|getElementsByClassName|new|Date|month|short|day||year|toLocaleDateString|en|US|val'.split('|'),0,{}));
		//]]>
		</script>
				
		<script>
		//<![CDATA[
		eval(function(p,a,c,k,e,r){e=function(c){return c.toString(a)};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('$(2).b(3(){0 4=2.c(\'5\');0 6=2.d(\'5\');$("#e").f("g",3(){0 7=h i();0 8={j:\'k\',l:\'9\',m:\'9\'};0 1=7.n(\'o-p\',8);$("#q").r("s t: "+1);4.a=1;6.a=1})});',30,30,'const|formattedDate|document|function|dateField|wp_updates_GP|dateField2|currentDate|options|numeric|value|ready|getElementById|getElementsByClassName|updateButton|on|click|new|Date|month|short|day|year|toLocaleDateString|en|US|dateDisplay|text|Last|updated'.split('|'),0,{}));
		//]]>
		</script>
		
		<script>
		//<![CDATA[
		$(document).ready(function() {
			$('#dismissible-button').click(function() {
			$('#dismissible-alert').slideToggle(400);
			if ($(this).text() === "SHOW") {
				$(this).text("HIDE")
			} else {
				$(this).text("SHOW")
			}
			})
		});
		//]]>
		</script>

		<script>
		//<![CDATA[
		(function($) {
		$(document).ready(function() {
			var c = $('.upload_poster_gp');
			var d = $('.wp_poster_gp');
			var f = $('#preview_poster_gp');
			var g = f.find('img');
			var h = wp.media({
				title: 'Select or Upload Image',
				button: {
				text: 'Use this image'
				},
				multiple: false,
				library: {
				type: 'image'
				}
			});
			c.on('click', function(e) {
				e.preventDefault();
				h.open()
			});
			h.on('select', function() {
				var a = h.state().get('selection').first().toJSON();
				var b = a.url;
				d.val(b);
				g.attr('src', b);
				f.show()
			});
			d.on('input', function() {
				var a = $(this).val().trim();
				if (a && (a.match(/\.(jpeg|jpg|gif|png|webp)$/i) || a.includes('wp-content/uploads'))) {
				g.attr('src', a);
				f.show()
				} else if (!a) {
				f.hide()
				}
			})
			})
		})(jQuery);
		//]]>
		</script>
			
		<script>
		//<![CDATA[
		(function($) {
		$(document).ready(function() {
			var c = $('.upload_backgrounds_gp');
			var d = $('.wp_backgrounds_gp');
			var f = $('#preview_backgrounds_gp');
			var g = f.find('img');
			var h = wp.media({
				title: 'Select or Upload Image',
				button: {
				text: 'Use this image'
				},
				multiple: false,
				library: {
				type: 'image'
				}
			});
			c.on('click', function(e) {
				e.preventDefault();
				h.open()
			});
			h.on('select', function() {
				var a = h.state().get('selection').first().toJSON();
				var b = a.url;
				d.val(b);
				g.attr('src', b);
				f.show()
			});
			d.on('input', function() {
				var a = $(this).val().trim();
				if (a && (a.match(/\.(jpeg|jpg|gif|png|webp)$/i) || a.includes('wp-content/uploads'))) {
				g.attr('src', a);
				f.show()
				} else if (!a) {
				f.hide()
				}
			})
			})
		})(jQuery);
		//]]>
		</script>

		<style>
		@media only screen and (max-width: 600px) {#dismissible-button.button{top: -45px!important;right: 90px!important;}#donate{display:none }}#dismissible-button.button {font-size: 13px;cursor: pointer;float: right;position: absolute;top: 20px;right: 10px;z-index: 9999;background: white;color: black;}
		</style>
		
	<?php
	}
}

 