<?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 Admin Menu with Live Update Counter
 * --------------------------------------------------------------------
 * This function creates a custom admin menu item called "Apps Updates"
 * with a live badge showing how many apps currently have updates available.
 * The badge uses WordPress core's "update-plugins" style for consistency.
 */
  
if ( ! function_exists( 'apk_update_add_admin_menu' ) ) 
{
	function apk_update_add_admin_menu() 
	{
		// Hitung jumlah app yang memiliki update tersedia
		$update_count = apk_update_count_posts(); // Pastikan fungsi ini return integer

		// Badge merah seperti update plugin/core WordPress
		$badge = '';
		if ( $update_count > 0 ) {
			$badge_class = ( $update_count > 9 ) ? ' count-10+' : ' count-' . $update_count;
			$badge = '<span class="update-plugins' . $badge_class . '">
						<span class="plugin-count">' . number_format_i18n( $update_count ) . '</span>
					  </span>';
		}

		// Menu Utama (top-level)
		add_menu_page(
			__( 'App Update Cron Status', TEXT_DOMAIN ),   // Page title
			__( 'App Update', TEXT_DOMAIN ) . $badge,      // Menu title + badge
			'manage_options',
			'apps_updates',                                // Slug utama
			'app_update_render_cron_status_page',          // Default: langsung buka Cron Status
			'dashicons-update-alt',                        // Icon refresh/update
			999                                             // Position (di bawah Posts/Pages)
		);

		// Submenu 1: Cron Status (default/halaman utama saat klik menu)
		add_submenu_page(
			'apps_updates',
			__( 'Cron Status & Logs', TEXT_DOMAIN ),
			__( 'Cron Status', TEXT_DOMAIN ),
			'manage_options',
			'apps_updates',                                // Slug sama → jadi default & active
			'app_update_render_cron_status_page'
		);

		// Submenu 2: Daftar App yang Butuh Update
		add_submenu_page(
			'apps_updates',
			__( 'Available Updates', TEXT_DOMAIN ),
			__( 'Available Updates', TEXT_DOMAIN ) . ( $update_count > 0 ? " <span class='update-plugins count-$update_count'><span class='plugin-count'>" . number_format_i18n( $update_count ) . '</span></span>' : '' ),
			'manage_options',
			'app-update-list',
			'apps_updates_page'                            // Fungsi render daftar update
		);
		
		// Submenu 3: Settings (baru ditambahkan)
		add_submenu_page(
			'apps_updates',
			__( 'Settings', TEXT_DOMAIN ),
			__( 'Settings', TEXT_DOMAIN ),
			'manage_options',
			'app-update-settings',
			'app_update_settings_page'             // Fungsi render halaman settings
		);
		

		// Optional: Tambahkan submenu lain nanti, misalnya Settings
		// add_submenu_page( 'apps_updates', 'Settings', 'Settings', 'manage_options', 'app-update-settings', 'app_update_settings_page' );
	}
	add_action( 'admin_menu', 'apk_update_add_admin_menu' );
}

if ( ! function_exists( 'app_update_settings_page' ) ) 
{
	function app_update_settings_page() {
    if (!current_user_can('manage_options')) {
        wp_die(esc_html__('You do not have sufficient permissions to access this page.', TEXT_DOMAIN));
    }

    $success_message = '';

    // Handle form submission
    if (isset($_POST['app_update_save_settings']) && check_admin_referer('app_update_settings_nonce')) {
        $new_interval = sanitize_text_field($_POST['app_update_cron_interval'] ?? 'every_6_hours');
        $batch_size   = max(1, min(100, (int) ($_POST['app_update_batch_size'] ?? 20)));
        $show_notice  = isset($_POST['app_update_show_notice']) ? '1' : '0';
        $show_notice_on_app_list = isset($_POST['app_update_show_notice_on_app_list']) ? '1' : '0';

        // Simpan semua pengaturan
        update_option('app_update_cron_interval', $new_interval);
        update_option('app_update_batch_size', $batch_size);
        update_option('app_update_show_notice', $show_notice);
        update_option('app_update_show_notice_on_app_list', $show_notice_on_app_list);

        // Reschedule cron
        wp_clear_scheduled_hook('check_all_apps_cron');
        $schedule_success = wp_schedule_event(time(), $new_interval, 'check_all_apps_cron') !== false;

        // Tampilkan notice hanya jika di-enable
       
		$success_message = $schedule_success
			? esc_html__('Settings saved successfully! Cron has been rescheduled.', TEXT_DOMAIN)
			: esc_html__('Settings saved, but failed to reschedule cron job.', TEXT_DOMAIN);
       
    }

    // Ambil nilai saat ini dengan default yang aman
    $current_interval        = get_option('app_update_cron_interval', 'every_6_hours');
    $batch_size              = (int) get_option('app_update_batch_size', 20); 
    $show_notice_on_app_list = get_option('app_update_show_notice_on_app_list', '1'); // default: tampilkan

    ?>
    <div class="wrap">
        <h1><?php esc_html_e('App Update Settings', TEXT_DOMAIN); ?></h1>

        <?php if ($success_message): ?>
            <div class="notice notice-success is-dismissible">
                <p><?php echo esc_html($success_message); ?></p>
            </div>
        <?php endif; ?>

        <form method="post" action="">
            <?php wp_nonce_field('app_update_settings_nonce'); ?>

            <table class="form-table" role="presentation">
                <tr>
                    <th scope="row">
                        <label for="app_update_cron_interval"><?php esc_html_e('Cron Check Interval', TEXT_DOMAIN); ?></label>
                    </th>
                    <td>
                        <select name="app_update_cron_interval" id="app_update_cron_interval">
                            <option value="every_1_hours"  <?php selected($current_interval, 'every_1_hours'); ?>><?php esc_html_e('Every 1 Hour', TEXT_DOMAIN); ?></option>
                            <option value="every_3_hours"  <?php selected($current_interval, 'every_3_hours'); ?>><?php esc_html_e('Every 3 Hours', TEXT_DOMAIN); ?></option>
                            <option value="every_6_hours"  <?php selected($current_interval, 'every_6_hours'); ?>><?php esc_html_e('Every 6 Hours', TEXT_DOMAIN); ?></option>
                            <option value="every_12_hours" <?php selected($current_interval, 'every_12_hours'); ?>><?php esc_html_e('Every 12 Hours', TEXT_DOMAIN); ?></option>
                            <option value="every_24_hours" <?php selected($current_interval, 'every_24_hours'); ?>><?php esc_html_e('Once Daily', TEXT_DOMAIN); ?></option>
                        </select>
                        <p class="description"><?php esc_html_e('How frequently the background update checker should run.', TEXT_DOMAIN); ?></p>
                    </td>
                </tr>

                <tr>
                    <th scope="row">
                        <label for="app_update_batch_size"><?php esc_html_e('Batch Size apps per run', TEXT_DOMAIN); ?></label>
                    </th>
                    <td>
                        <input type="number"
                               name="app_update_batch_size"
                               id="app_update_batch_size"
                               value="<?php echo esc_attr($batch_size); ?>"
                               min="1" max="50" step="1"
                               class="small-text" />
                        <p class="description"><?php esc_html_e('Number of apps to check per batch (recommended: 10–30)', TEXT_DOMAIN); ?></p>
                    </td>
                </tr>
 

                <tr>
                    <th scope="row"><?php esc_html_e('Show Notice on App List', TEXT_DOMAIN); ?></th>
                    <td>
                        <label>
                            <input type="checkbox"
                                   name="app_update_show_notice_on_app_list"
                                   id="app_update_show_notice_on_app_list"
                                   value="1"
                                   <?php checked($show_notice_on_app_list, '1'); ?> />
                            <?php esc_html_e('Show update status/success notice on the app list page', TEXT_DOMAIN); ?>
                        </label>
                        <p class="description"><?php esc_html_e('Controls whether update notifications appear on the main app list/admin screen.', TEXT_DOMAIN); ?></p>
                    </td>
                </tr>
            </table>

            <?php submit_button(
                esc_attr__('Save Settings', TEXT_DOMAIN),
                'primary',
                'app_update_save_settings'
            ); ?>
        </form>
    </div>
    <?php
	}

}


/**
 * Render halaman: App Update Cron Status Dashboard
 * VERSI FINAL – Akurat, Profesional, AJAX Clear Log, Countdown Real
*/

if ( ! function_exists( 'app_update_render_cron_status_page' ) ) 
{
	function app_update_render_cron_status_page() 
	{
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( __( 'Permission denied.', TEXT_DOMAIN ) );
		}

		// Handle manual run background check
		if ( isset( $_GET['app_update_force_check'] ) ) {
			check_admin_referer( 'app_update_force_check_all' );
			if ( function_exists( 'app_update_run_batch_check' ) ) {
				app_update_run_batch_check();
			}
			wp_redirect( add_query_arg( 'app_update_notice', 'ran', remove_query_arg( array( 'app_update_force_check', '_wpnonce' ) ) ) );
			exit;
		}

		$force_check_url = wp_nonce_url( add_query_arg( 'app_update_force_check', '1' ), 'app_update_force_check_all' );

		$next_scheduled = wp_next_scheduled( 'check_all_apps_cron' );
		$lock_active    = get_transient( 'app_update_global_cron_lock' );
		$last_log       = get_option( 'app_update_cron_last_log', array() );

		// Mapping interval dari Settings (fallback utama)
		$setting_interval = get_option( 'app_update_cron_interval', 'every_6_hours' );
		$interval_display_map = [
			'every_1_hours'   => __( 'Every 1 Hour', TEXT_DOMAIN ),
			'every_3_hours'   => __( 'Every 3 Hours', TEXT_DOMAIN ),
			'every_6_hours'   => __( 'Every 6 Hours', TEXT_DOMAIN ),
			'every_12_hours'  => __( 'Every 12 Hours', TEXT_DOMAIN ),
			'every_24_hours'  => __( 'Once Daily', TEXT_DOMAIN ),
		];
		$current_interval = $interval_display_map[ $setting_interval ] ?? __( 'Every 6 Hours', TEXT_DOMAIN );

		// Jika cron aktif, ambil display name langsung dari cron array (paling akurat)
		if ( $next_scheduled ) {
			$crons     = _get_cron_array();
			$schedules = wp_get_schedules();
			foreach ( $crons as $cron ) {
				if ( isset( $cron['check_all_apps_cron'] ) ) {
					foreach ( $cron['check_all_apps_cron'] as $hook_data ) {
						if ( isset( $hook_data['schedule'] ) && isset( $schedules[ $hook_data['schedule'] ] ) ) {
							$current_interval = $schedules[ $hook_data['schedule'] ]['display'];
							break 2;
						}
					}
				}
			}
		} else {
			$current_interval = __( 'Not scheduled', TEXT_DOMAIN );
		}

		$current_time      	= current_time( 'timestamp' );
		$current_formatted 	= date_i18n( 'H:i:s T', $current_time );
		$current_full      	= date_i18n( 'l, F j, Y @ H:i:s T', $current_time );
		$batch_size       	= get_option( 'app_update_batch_size', 20 );
		$show_notice_on_app_list = get_option('app_update_show_notice_on_app_list', '1'); // default: tampilkan
		?>
		<!-- CSS tambahan untuk status PHP -->
<style>
.form-table .status-good,
.form-table .status-good-text      { color: #008a20; }
.form-table .status-warning,
.form-table .status-warning-text   { color: gold; font-weight: 500; }
.form-table .status-good-text,
.form-table .status-warning-text   { font-size: 0.92em; }
</style>
 

		<div class="wrap">
			<h1><?php esc_html_e( 'App Update Cron Status', TEXT_DOMAIN ); ?></h1>

			<?php if ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) : ?>
				<div class="notice notice-warning is-dismissible">
					<p><strong><?php esc_html_e( 'Warning:', TEXT_DOMAIN ); ?></strong>
					<?php esc_html_e( 'WP_CRON is disabled (DISABLE_WP_CRON = true). Background checks will not run automatically unless you set up a real system cron.', TEXT_DOMAIN ); ?>
					</p>
				</div>
			<?php endif; ?>

			<!-- Notice setelah Run Manual -->
			<?php if ( isset( $_GET['app_update_notice'] ) && $_GET['app_update_notice'] === 'ran' ) : ?>
				<div class="notice notice-success is-dismissible" style="margin:20px 0;">
					<p><strong>✓ <?php esc_html_e( 'Background check executed successfully!', TEXT_DOMAIN ); ?></strong></p>
					<p><?php esc_html_e( 'New log added. Page will refresh in 3 seconds...', TEXT_DOMAIN ); ?></p>
				</div>
				<script>
					setTimeout(() => location.href = '<?php echo esc_url( remove_query_arg( 'app_update_notice' ) ); ?>', 3000);
				</script>
			<?php endif; ?>
			 
			 
			<div class="card" style="max-width:100%; margin:30px 0;">
				<h2><?php esc_html_e( 'Apps Checker Status', TEXT_DOMAIN ); ?></h2>
				<table class="form-table" role="presentation">
					<tr>
						<th scope="row"><?php esc_html_e( 'Cron Status', TEXT_DOMAIN ); ?></th>
						<td><?php echo $next_scheduled ? '<strong class="status-good">✓ Active & Scheduled</strong>' : '<strong class="status-warning">✗ Not Scheduled</strong>'; ?></td>
					</tr>
					<tr>
					<th scope="row"><?php esc_html_e('PHP Version', TEXT_DOMAIN); ?></th>
						<td>
							<strong class="<?php echo version_compare(PHP_VERSION, '8.0', '>=') ? 'status-good' : 'status-warning'; ?>">
								<?php echo esc_html(PHP_VERSION); ?>
							</strong>&nbsp;
							<?php if (version_compare(PHP_VERSION, '8.0', '<')) : ?>
								<em class="status-warning-text">
									⚠ <?php esc_html_e('Recommended: PHP 8.4 or higher', TEXT_DOMAIN); ?>
								</em>
							<?php else : ?>
								<em>✓ <?php esc_html_e('Good – modern & secure version', TEXT_DOMAIN); ?></em>
							<?php endif; ?>
						</td>
					</tr>		
					<tr>
						<th scope="row"><?php esc_html_e( 'Current Time', TEXT_DOMAIN ); ?></th>
						<td><strong style="color:#666; font-size:1.05em;">🕐 <?php echo esc_html( $current_formatted ); ?> <em>(<?php echo esc_html( $current_full ); ?>)</em></strong></td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Next Scheduled Run', TEXT_DOMAIN ); ?></th>
						<td>
							<?php if ( $next_scheduled ) :
								$next_formatted = date_i18n( 'H:i:s T', $next_scheduled );
								$countdown_id = 'real-countdown-' . wp_rand(1000, 9999);
							?>
								<div style="margin-bottom:10px;display:none" >
									<strong style="color:#856404; font-size:1.05em;">📅 <?php echo esc_html( $next_formatted ); ?></strong>
								</div>
								<div id="<?php echo esc_attr( $countdown_id ); ?>" style="font-size:1.2em; font-weight:600;">
									<em><?php esc_html_e( 'Calculating...', TEXT_DOMAIN ); ?></em>
								</div>
								<script>
								document.addEventListener('DOMContentLoaded', function() {
									const target = <?php echo $next_scheduled * 1000; ?>;
									const el = document.getElementById('<?php echo esc_js( $countdown_id ); ?>');
									function update() {
										const diff = target - Date.now();
										if (diff <= 0) {
											el.innerHTML = '<strong class="status-good">⏰ <?php echo esc_js( __( 'Running now!', TEXT_DOMAIN ) ); ?></strong>';
											return;
										}
										const d = Math.floor(diff / 86400000);
										const h = Math.floor((diff % 86400000) / 3600000);
										const m = Math.floor((diff % 3600000) / 60000);
										const s = Math.floor((diff % 60000) / 1000);
										let text = '<?php echo esc_js( __( 'in', TEXT_DOMAIN ) ); ?> ';
										if (d > 0) text += d + ' <?php echo esc_js( __( 'days', TEXT_DOMAIN ) ); ?>, ';
										if (h > 0 || d > 0) text += h + ' <?php echo esc_js( __( 'hours', TEXT_DOMAIN ) ); ?>, ';
										text += m + ' <?php echo esc_js( __( 'minutes', TEXT_DOMAIN ) ); ?>, ' + s + ' <?php echo esc_js( __( 'seconds', TEXT_DOMAIN ) ); ?>';
										el.innerHTML = diff < 60000
											? '<strong class="status-warning">⏳ <?php echo esc_js( __( 'Very soon!', TEXT_DOMAIN ) ); ?> (' + s + 's)</strong>'
											: '<strong style="color:#a05d56;">' + text + '</strong>';
									}
									update();
									setInterval(update, 1000);
								});
								</script>
							<?php else : ?>
								<em class="status-warning"><?php esc_html_e( 'Not scheduled', TEXT_DOMAIN ); ?></em>
							<?php endif; ?>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Current Interval', TEXT_DOMAIN ); ?></th>
						<td><strong><?php echo esc_html( $current_interval ); ?></strong></td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Batch Size', TEXT_DOMAIN ); ?></th>
						<td><strong><?php echo esc_html($batch_size); ?> <?php esc_html_e('apps per run', TEXT_DOMAIN); ?></strong></td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Show Notice on App List', TEXT_DOMAIN ); ?></th>
						<td><strong><?php echo $show_notice_on_app_list === '1' ? __('Yes', TEXT_DOMAIN) : __('No', TEXT_DOMAIN); ?></strong></td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Current Process', TEXT_DOMAIN ); ?></th>
						<td><?php echo $lock_active ? '<strong class="status-warning">🔒 Running in background...</strong>' : '<strong class="status-good">✓ Idle – ready for next run</strong>'; ?></td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Last Batch Result', TEXT_DOMAIN ); ?></th>
						<td id="app-update-last-batch">
							<?php if ( ! empty( $last_log ) && is_array( $last_log ) ) : ?>
								<?php echo esc_html( $last_log[0]['message'] ?? '' ); ?><br>
								<em><?php echo esc_html( $last_log[0]['time'] ?? '' ); ?></em>
							<?php else : ?>
								<em><?php esc_html_e( 'No batch has run yet.', TEXT_DOMAIN ); ?></em>
							<?php endif; ?>
						</td>
					</tr>
				</table>

				<p class="submit" style="margin-top: 30px; display: flex; flex-wrap: wrap; gap: 12px; align-items: center;">
				<!-- Primary action - most important -->
				<a href="<?php echo esc_url( $force_check_url ); ?>" 
				   class="button button-primary button-large">
					<?php esc_html_e( 'Run Background Check Now', TEXT_DOMAIN ); ?>
				</a>

				<a href="<?php echo esc_url( admin_url( 'admin.php?page=app-update-settings' ) ); ?>" 
				   class="button button-secondary button-large">
					<?php esc_html_e( 'Settings', TEXT_DOMAIN ); ?>
				</a>

				<!-- Secondary actions -->
				<button type="button" 
						id="app-update-clear-log-btn" 
						class="button button-secondary button-large">
					<?php esc_html_e( 'Clear All Log', TEXT_DOMAIN ); ?>
				</button>

				<!-- Optional: extra helpful link variant (smaller) -->
				<!-- 
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=app-update-settings' ) ); ?>" 
				   class="page-title-action" style="margin-left: 8px;">
					<?php esc_html_e( 'Configure Cron & Batch', TEXT_DOMAIN ); ?>
				</a>
				-->

				<!-- Explanatory text --> 
				<span style="display: inline-block; color: #666; font-size: 13px; margin-left: 8px;">
					<?php esc_html_e( 'Processes apps in safe batches automatically', TEXT_DOMAIN ); ?>
				</span>
			</p>

			</div>

			<!-- Recent Activity Log -->
			<div id="app-update-log-section" class="card" style="max-width:100%;">
				<?php if ( ! empty( $last_log ) && is_array( $last_log ) ) : ?>
					<h2><?php esc_html_e( 'Recent Activity Log', TEXT_DOMAIN ); ?> (<?php echo count( $last_log ); ?> <?php esc_html_e( 'entries', TEXT_DOMAIN ); ?>)</h2>
					<table class="widefat fixed striped">
						<thead>
							<tr>
								<th style="width:180px;"><?php esc_html_e( 'Time', TEXT_DOMAIN ); ?></th>
								<th><?php esc_html_e( 'Message', TEXT_DOMAIN ); ?></th>
							</tr>
						</thead>
						<tbody>
							<?php foreach ( $last_log as $entry ) : ?>
								<tr>
									<td><?php echo esc_html( $entry['time'] ?? '' ); ?></td>
									<td><?php echo esc_html( $entry['message'] ?? '' ); ?></td>
								</tr>
							<?php endforeach; ?>
						</tbody>
					</table>
				<?php else : ?>
					<p><em><?php esc_html_e( 'No activity recorded yet. Run a check to see logs here.', TEXT_DOMAIN ); ?></em></p>
				<?php endif; ?>
			</div>

			<hr style="margin:50px 0;">
			<p>
				<strong><?php esc_html_e( 'Note:', TEXT_DOMAIN ); ?></strong>
				<?php esc_html_e( 'The background checker runs automatically according to your settings. Use the button above to run manually.', TEXT_DOMAIN ); ?>
			</p>
		</div>
		<?php
	}
}
