<?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 		
		$download_fields	= get_post_meta( $post_id, 'repeatable_fields', true); 
		wp_nonce_field( 'download_list_nonce', 'download_list_nonce' );    
		if ( $download_fields ) {		
		wp_enqueue_media();
		$number = 0;
		//foreach ( $download_fields as $items ) { 
		foreach ( $download_fields as $items => $row ) {
		$number++;
			
		$file_id 	= ! empty( $row['file_id'] ) ? $row['file_id'] : '';
		$file_url 	= $file_id ? wp_get_attachment_url( $file_id ) : '';
		
		// Prioritize current field names, fall back to old ones if needed
		$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" id="item_download_links">
		<div class="aps-box-inside">
			<!--<span class="tb-title"><span class="dashicons dashicons-menu"></span></span>-->
			<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">
				<label>link</label>
				<input id="file_id" type="hidden" name="file_repeater[<?php echo $items; ?>][file_id]" class="file-id" value="<?php echo esc_attr( $file_id ); ?>">
				<textarea id="file_url" placeholder="example : your apk link" class="aps-textarea" name="url[]" ><?php echo esc_textarea( $url ); ?></textarea>   
				<button style="right: 15px !important; top: -25px !important; color: dodgerblue; position: absolute;cursor: pointer;line-height: 1.6;" type="button" class="upload-file-button button"><span class="dashicons dashicons-cloud-upload"></span> Upload File</button>			 
			</div>
			<div class="clear"></div>
			
			<div class="aps-col-2">
				<label>Type</label>
				<textarea rows="1" placeholder="example : 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="example : 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="example : mod menu" class="aps-textarea" name="notes[]" ><?php echo esc_textarea( $notes ); ?></textarea>   
			</div>
			<div class="clear"></div>
			
		</div>
		
			<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;">Link #<?php echo $number; ?></a>
			<a id="hapus_link" class="delete-fieldset aps-btn-del" style="right: -10px !important;top: -10px !important;position: absolute;cursor: pointer;text-decoration: none;"><span class="dashicons dashicons-dismiss"></span></a>

		</li> 
		<?php }} ?>
		
		  
		</ul>  
		
		<div class="aps-add-download">
		<a id="tambah_link_baru" class="aps-btn add-fieldset" style="color: #fff;border: 1px solid #000000;background: #000000;cursor: pointer;" ><i class="aps-icon-plus"></i> Add Link</a>
		</div>
		
		 
		<script type="text/javascript">
		//<![CDATA[
		
		
		$('a#tambah_link_baru').click(function() {
			var index = $('.default_row').length; 
			var row = `
		<li class="aps-field-box default_row" id="item_download_links">
		<div class="aps-box-inside">
			<!--<span class="tb-title"><span class="dashicons dashicons-menu"></span></span>-->
			<div class="aps-col-3">
				<label>name </label> 
				<textarea placeholder="example : roblox mod menu" class="aps-textarea" name="name[]" ></textarea>  
			</div>
			<div class="aps-col-3">
				<label>link</label>
				<input id="file_id" type="hidden" name="file_repeater[${index}][file_id]" class="file-id">
				<textarea id="file_url" placeholder="example : your apk link" class="aps-textarea" name="url[]" ></textarea>   
				<button style="right: 15px !important; top: -25px !important; color: dodgerblue; position: absolute;cursor: pointer;line-height: 1.6;" type="button" class="upload-file-button button"><span class="dashicons dashicons-cloud-upload"></span> Upload File</button>
				
			 
			</div>
			<div class="clear"></div>
			
			<div class="aps-col-2">
				<label>Type</label>
				<textarea rows="1" placeholder="example : apk, zip, obb, xapk" class="aps-textarea" name="tipes[]" ></textarea>  
			</div>
			<div class="aps-col-2">
				<label>size</label>
				<textarea rows="1" placeholder="example : 100mb" class="aps-textarea" name="sizes[]" ></textarea>   
			</div>
			<div class="aps-col-2">
				<label>note</label>	
				<textarea rows="1" placeholder="example : mod menu" class="aps-textarea" name="notes[]" ></textarea>   
			</div>
			<div class="clear"></div>
			
		</div>
		<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;">Link #</a>
		<a id="hapus_link" class="delete-fieldset aps-btn-del" style="right: -10px !important;top: -10px !important;position: absolute;cursor: pointer;text-decoration: none;"><span class="dashicons dashicons-dismiss"></span></a>

		</li> `;
		$('#sort_table').append(row);
		});

		$(document).on('click', 'a#hapus_link', function() {
			$(this).closest('.default_row').remove();
		}); 
	 
		jQuery(document).ready(function($) {
			/* 
			$('a#tambah_link_baru').on('click', function() {
				var a = $('.default_row.screen-reader-text').clone(true);
				a.removeClass('default_row screen-reader-text');
				a.insertBefore('ul#sort_table>li#item_download_link:last')
			});
			$('a#hapus_link').on('click', function() {
				$(this).parent().remove()
			}) 
			*/
		
			// File upload handler
			$(document).on('click', '.upload-file-button', function(e) {
				e.preventDefault();
				var $button = $(this);
				var $row = $button.closest('.default_row');
				var $file_id_input = $row.find('#file_id');
				var $file_url_input = $row.find('#file_url');

				var uploader = wp.media({
					/* 
					title: 'Select File',
					button: { text: 'Select File' }, 
					*/
					multiple: false,
					/* 
					library: { type: ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip'] } // Restrict file types
					*/
				}).on('select', function() {
					var attachment = uploader.state().get('selection').first().toJSON();
					$file_id_input.val(attachment.id);
					$file_url_input.val(attachment.url);
					$button.siblings('.remove-file-button').show();
				}).open();
			});

			// Remove file
			$(document).on('click', '.remove-file-button', function() {
				var $row = $(this).closest('.default_row');
				$row.find('#file_id').val('');
				$row.find('#file_url').val('');
				$(this).hide();
			});
			
		});
		
		//]]>
		</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>

		<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 
	}
}

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( '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>
				
	<?php
	}
}

if ( ! function_exists( 'download_list_meta_box_save' ) ) 
{
	// Save function — diperbaiki agar bisa menyimpan file_id juga
	add_action('save_post', 'download_list_meta_box_save');
	function download_list_meta_box_save( $post_id ) 
	{
		// Verifikasi nonce
		if ( ! isset( $_POST['download_list_nonce'] ) || ! wp_verify_nonce( $_POST['download_list_nonce'], 'download_list_nonce' ) ) {
			return;
		}

		// Hindari autosave
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		// Cek permission
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		$meta_key 	= 'repeatable_fields';
		$old      	= get_post_meta( $post_id, $meta_key, true );
		$new      	= array();

		// Ambil data dari POST
		$names  	= isset( $_POST['name'] )  ? $_POST['name']  : array();
		$urls   	= isset( $_POST['url'] )   ? $_POST['url']   : array();
		$tipes  	= isset( $_POST['tipes'] ) ? $_POST['tipes'] : array();
		$sizes  	= isset( $_POST['sizes'] ) ? $_POST['sizes'] : array();
		$notes  	= isset( $_POST['notes'] ) ? $_POST['notes'] : array();

		// Ambil file_id yang tersimpan via media uploader
		$file_ids 	= array();
		if ( isset( $_POST['file_repeater'] ) && is_array( $_POST['file_repeater'] ) ) {
			foreach ( $_POST['file_repeater'] as $idx => $data ) {
				if ( isset( $data['file_id'] ) ) {
					$file_ids[ $idx ] = absint( $data['file_id'] );
				}
			}
		}

		$count 		= max( count( $names ), count( $urls ) ); // ambil yang terpanjang

		for ( $i = 0; $i < $count; $i++ ) {
			// Lewati jika nama dan url kosong
			$name 	= isset( $names[ $i ] ) ? trim( $names[ $i ] ) : '';
			$url  	= isset( $urls[ $i ] )  ? trim( $urls[ $i ] )  : '';

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

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

		// Update atau delete meta
		if ( ! empty( $new ) && $new != $old ) {
			update_post_meta( $post_id, $meta_key, $new );
		} elseif ( empty( $new ) && $old ) {
			delete_post_meta( $post_id, $meta_key, $old );
		}
	}
}

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_size_callback' ) ) 
{
	// Add AJAX action for fetching file size
	add_action('wp_ajax_get_file_size', 'get_file_size_callback');
	function get_file_size_callback() 
	{
		if (!current_user_can('edit_posts')) {
			wp_send_json_error('Permission denied');
		}

		$url = isset($_POST['url']) ? esc_url_raw($_POST['url']) : '';

		if (empty($url)) {
			wp_send_json_error('Invalid URL');
		}

		$context = stream_context_create([
			'http' => [
				'method' => 'HEAD',
				'follow_location' => true,
				'timeout' => 25,
				'header' => "Referer: https://google.com/\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\r\n",
			],
			'ssl' => [
				'verify_peer' => false,
				'verify_peer_name' => false,
			],
		]);

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

		if ($headers && isset($headers['Content-Length'])) {
			$bytes = is_array($headers['Content-Length']) ? end($headers['Content-Length']) : $headers['Content-Length'];
			$size = format_download_size($bytes);
			wp_send_json_success($size);
		} else {
			wp_send_json_error('Unable to fetch file size');
		}
	}
}

if ( ! function_exists( 'format_download_size' ) ) 
{
	// Helper function for formatting download sizes (MB, GB, KB)
	function format_download_size( $bytes ) 
	{
        $units = array( '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', '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() 
	{
	?>
	<script>
	document.addEventListener('DOMContentLoaded', function () {
		const table = document.getElementById('sort_table');

		if (!table) return;

		// Delegate events from the table to all textarea[name="url[]"]
		table.addEventListener('input', handleUrlChange);   // typing
		table.addEventListener('paste', handleUrlChange);   // pasting

		function handleUrlChange(e) {
			const urlTextarea = e.target.closest('textarea[name="url[]"]');
			if (!urlTextarea) return;

			const url = urlTextarea.value.trim();
			const box = urlTextarea.closest('.aps-box-inside');
			if (!box) return;

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

			// Clear size field immediately if URL is empty
			if (!url) {
				sizeTextarea.value = '';
				return;
			}

			// Cancel any previous pending request for this field
			if (urlTextarea.dataset.timeoutId) {
				clearTimeout(parseInt(urlTextarea.dataset.timeoutId));
			}

			// Debounce: wait 500ms after user stops typing/pasting
			const timeoutId = setTimeout(function () {
				fetch(ajaxurl, {  // ajaxurl must be defined globally by WordPress
					method: 'POST',
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded',
					},
					body: new URLSearchParams({
						action: 'get_file_size',
						url: url
					})
				})
				.then(response => response.json())
				.then(data => {
					if (data.success) {
						sizeTextarea.value = data.data;
					} else {
						sizeTextarea.value = 'Error fetching size';
					}
				})
				.catch(() => {
					sizeTextarea.value = 'Error fetching size';
				});
			}, 500);

			// Store timeout ID so we can cancel it later
			urlTextarea.dataset.timeoutId = timeoutId;
		}
	});
	</script>
	 
	<?php
	}
}

