<?php
/*-----------------------------------------------*/
/*  EXTHEM.ES
/*  PREMIUM WORDRESS THEMES
/*
/*  STOP DON'T TRY EDIT
/*  IF YOU DON'T KNOW PHP 
/*
/*  As Errors In Your Themes
/*  Are Not The Responsibility
/*  Of The DEVELOPERS
/*  @EXTHEM.ES
/*  
/*  Follow Social Media Exthem.es
/*  Youtube : https://www.youtube.com/channel/UCpcZNXk6ySLtwRSBN6fVyLA
/*  Facebook : https://www.facebook.com/groups/exthem.es
/*  Twitter : https://x.com/bangreyblog
/*  Instagram : https://www.instagram.com/exthem.es/
/*  Telegram : https://t.me/exthemes_helps
/*  TikTok : https://www.tiktok.com/@exthemes
/*	More Premium Themes Visit Now On https://exthem.es/
/*-----------------------------------------------*/
if ( ! defined( 'ABSPATH' ) ) exit; 
// Silence is golden.

/* --------------------------------------------------------------------
* Add the dashboard widget
* ------------------------------------------------------------------ 
*/	   
if ( ! function_exists( 'apk_updates_dashboard_widget' ) ) 
{
	add_action( 'wp_dashboard_setup', 'apk_updates_dashboard_widget' );
	function apk_updates_dashboard_widget() 
	{
		wp_add_dashboard_widget(
			'apk_updates_widget',
			'Apps Updates Available',
			'apk_updates_widget_display',
			null,	// control callback (optional)
			null,	// args (optional)
			'side',	// ← context: 'side' instead of default 'normal'
			'high'	// ← priority: 'core', 'high', 'low'
		);
	}
}
 
if ( ! function_exists( 'apk_updates_widget_display' ) ) 
{
	function apk_updates_widget_display() 
	{
		$widget_id = 'apk_updates_widget'; // Must match the ID from wp_add_dashboard_widget
		?>
		<div id="<?php echo $widget_id; ?>-container">
			<div id="<?php echo $widget_id; ?>-content">
				<?php apk_update_render_table(); // Initial load ?>
			</div>
			 
			
			<div style="text-align:center; padding:10px 0; font-size:12px; color:#666;">
				<span id="<?php echo $widget_id; ?>-status">
					Auto-refresh in <span id="<?php echo $widget_id; ?>-countdown">60</span>s
				</span>
				<span id="<?php echo $widget_id; ?>-spinner" style="display:none; margin-left:8px;">
					Loading...
				</span>
			</div>
		</div>

		<script type="text/javascript">
			(function() {
				const widgetId = '<?php echo $widget_id; ?>';
				const container = document.getElementById(widgetId + '-container');
				const contentDiv = document.getElementById(widgetId + '-content');
				const statusText = document.getElementById(widgetId + '-status');
				const spinner = document.getElementById(widgetId + '-spinner');
				const countdownEl = document.getElementById(widgetId + '-countdown');

				let countdown = 60;

				function refreshWidget() {
					spinner.style.display = 'inline';
					statusText.style.display = 'none';

					fetch(ajaxurl, {
						method: 'POST',
						credentials: 'same-origin',
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded',
						},
						body: 'action=apk_updates_widget_refresh&_wpnonce=<?php echo wp_create_nonce('apk_widget_refresh'); ?>'
					})
					.then(response => response.text())
					.then(html => {
						contentDiv.innerHTML = html;
						spinner.style.display = 'none';
						statusText.style.display = 'block';
						countdown = 60;
						countdownEl.textContent = countdown;
						startCountdown();
					})
					.catch(err => {
						contentDiv.innerHTML = '<p style="color:red;">Refresh failed. Retrying...</p>';
						spinner.style.display = 'none';
						setTimeout(refreshWidget, 10000); // retry in 10s
					});
				}

				function startCountdown() {
					const interval = setInterval(() => {
						countdown--;
						countdownEl.textContent = countdown;
						if (countdown <= 0) {
							clearInterval(interval);
							refreshWidget();
						}
					}, 1000);
				}

				// Start countdown on load
				startCountdown();

				// Optional: manual refresh button
				const refreshBtn = document.createElement('a');
				refreshBtn.href = '#';
				refreshBtn.textContent = 'Refresh now';
				refreshBtn.style = 'margin-left:15px; font-size:11px; color:#0073aa;';
				refreshBtn.onclick = (e) => {
					e.preventDefault();
					countdown = 0;
					refreshWidget();
				};
				statusText.appendChild(refreshBtn);
			})();
		</script>
		<?php
	}
}

// Render the actual table (used both on load and AJAX)

// Render the actual table (used both on load and AJAX)

if ( ! function_exists( 'apk_update_render_table' ) ) 
{
	function apk_update_render_table() 
	{
		$updates = apk_get_update_posts_list(100); // maksimal 100 item
		$total   = apk_update_count_posts();

		if ( $total === 0 ) {
			echo '<p><strong>' . esc_html__( 'All apps are up to date!', TEXT_DOMAIN ) . '</strong> ';
			echo '<a style="float: right;" href="' . esc_url( admin_url('admin.php?page=app-update-list') ) . '">';
			echo esc_html__( 'Check All Apps Now →', TEXT_DOMAIN ) . '</a></p>';
			return;
		}

		echo '<p><strong>' . sprintf( _n( '%s app has an update!', '%s apps have updates!', $total, TEXT_DOMAIN ), number_format_i18n( $total ) ) . '</strong> ';
		echo '<a style="float: right;" href="' . esc_url( admin_url('admin.php?page=app-update-list') ) . '">';
		echo esc_html__( 'View all →', TEXT_DOMAIN ) . '</a></p>';

		?>
		<div style="max-height:300px; overflow-y:auto; border:1px solid #c3c4c7; border-radius:8px; box-shadow:0 1px 1px rgba(0,0,0,.04);">
			<table class="widefat striped" style="margin:0; font-size:13px;">
				<thead style="position:sticky; top:0; background:#f6f7f7; z-index:10;">
					<tr>
						<th style="padding:10px 12px; width:45%;"><?php esc_html_e( 'App', TEXT_DOMAIN ); ?></th>
						<th style="padding:10px 12px;"><?php esc_html_e( 'Current', TEXT_DOMAIN ); ?></th>
						<th style="padding:10px 12px; color:#2271b1;"><?php esc_html_e( 'New Version', TEXT_DOMAIN ); ?></th>
						<th style="padding:10px 12px; text-align:center;"><?php esc_html_e( 'Actions', TEXT_DOMAIN ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php foreach ( $updates as $app ) :
						$post_id = intval( $app->ID );
						$title   = esc_html( $app->display_title );
						$edit    = get_edit_post_link( $post_id );
						$view    = get_permalink( $post_id );
						$current = $app->current_version ? esc_html( $app->current_version ) : '—';
						$new     = esc_html( $app->available_version );

						$thumb = get_the_post_thumbnail_url( $post_id, 'thumbnail' );
						if ( ! $thumb && ! empty( $app->poster_url ) ) {
							$thumb = esc_url( $app->poster_url );
						}
					?>
						<tr>
							<td style="padding:10px 12px; vertical-align:middle;">
								<?php if ( $thumb ) : ?>
									<img src="<?php echo esc_url( $thumb ); ?>" style="width:32px;height:32px;border-radius:4px;object-fit:cover;float:left;margin-right:10px;">
								<?php endif; ?>
								<a href="<?php echo esc_url( $edit ); ?>"><strong><?php echo $title; ?></strong></a>
							</td>
							<td style="padding:10px 12px; vertical-align:middle; color:#666;">
								<?php echo $current; ?>
							</td>
							<td style="padding:10px 12px; vertical-align:middle; font-weight:bold;">
								<?php echo $new; ?>
							</td>
							<td style="padding:10px 12px; text-align:center; vertical-align:middle;">
								<a href="<?php echo esc_url( $edit ); ?>" target="_blank"><?php esc_html_e( 'Edit', TEXT_DOMAIN ); ?></a> |
								<a href="<?php echo esc_url( $view ); ?>" target="_blank"><?php esc_html_e( 'View', TEXT_DOMAIN ); ?></a>
							</td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>
		</div>
		<?php
	}
}

// AJAX refresh endpoint
if ( ! function_exists( 'apk_updates_widget_ajax_refresh' ) ) 
{
	add_action( 'wp_ajax_apk_updates_widget_refresh', 'apk_updates_widget_ajax_refresh' );
	function apk_updates_widget_ajax_refresh() 
	{
		check_ajax_referer( 'apk_widget_refresh' );
		apk_update_render_table(); // This outputs the table only
		wp_die();
	}
}

