<?php

/*-----------------------------------------------*/
if ( ! defined( 'ABSPATH' ) ) exit; 
// Silence is golden.


/* --------------------------------------------------------------------
 * WP-CRON SCHEDULER FOR APK UPDATES
 * ------------------------------------------------------------------ */
if ( ! function_exists( 'app_update_add_cron_intervals' ) ) 
{
	// 1. Tambahkan interval cron custom
	add_filter( 'cron_schedules', 'app_update_add_cron_intervals' );
	function app_update_add_cron_intervals( $schedules ) 
	{
		$schedules['every_1_hours'] = [
			'interval' => 1 * HOUR_IN_SECONDS,
			'display'  => __( 'Every 1 Hours', TEXT_DOMAIN ),
		];
		$schedules['every_3_hours'] = [
			'interval' => 3 * HOUR_IN_SECONDS,
			'display'  => __( 'Every 3 Hours', TEXT_DOMAIN ),
		];
		$schedules['every_6_hours'] = [
			'interval' => 6 * HOUR_IN_SECONDS,
			'display'  => __( 'Every 6 Hours', TEXT_DOMAIN ),
		];
		$schedules['every_12_hours'] = [
			'interval' => 12 * HOUR_IN_SECONDS,
			'display'  => __( 'Every 12 Hours', TEXT_DOMAIN ),
		];
		$schedules['every_24_hours'] = [
			'interval' => DAY_IN_SECONDS,
			'display'  => __( 'Once Daily', TEXT_DOMAIN ),
		];

		return $schedules;
	}
}

if ( ! function_exists( 'app_update_schedule_cron' ) ) 
{
	// 2. Jadwalkan event saat plugin diaktifkan atau saat pertama kali load (jika belum ada)
	register_activation_hook( __FILE__, 'app_update_schedule_cron' );
	function app_update_schedule_cron() 
	{
		$setting_interval = get_option( 'app_update_cron_interval', 'every_6_hours' );
		if ( ! wp_next_scheduled( 'check_all_apps_cron' ) ) {
			wp_schedule_event( time(), $setting_interval, 'check_all_apps_cron' );
		}
	}
}

if ( ! function_exists( 'app_update_unschedule_cron' ) ) 
{
	// Optional: Bersihkan cron saat plugin dinonaktifkan
	register_deactivation_hook( __FILE__, 'app_update_unschedule_cron' );
	function app_update_unschedule_cron() 
	{
		$timestamp = wp_next_scheduled( 'check_all_apps_cron' );
		if ( $timestamp ) {
			wp_unschedule_event( $timestamp, 'check_all_apps_cron' );
		}
		delete_transient( 'app_update_global_cron_lock' );
	}
}

/* --------------------------------------------------------------------
 * CRON SCHEDULING & CLEANUP – PLUGIN / THEME COMPATIBLE
 * ------------------------------------------------------------------ */

if ( ! function_exists( 'app_update_activate_cron' ) ) 
{
	// 1. Jadwalkan cron saat plugin/theme diaktifkan
	register_activation_hook( __FILE__, 'app_update_activate_cron' );
	function app_update_activate_cron() 
	{
		$setting_interval = get_option( 'app_update_cron_interval', 'every_6_hours' );
		if ( ! wp_next_scheduled( 'check_all_apps_cron' ) ) {
			wp_schedule_event( time(), $setting_interval, 'check_all_apps_cron' );
		}
	}
}

if ( ! function_exists( 'app_update_deactivate_cron' ) ) 
{
	// 2. Hapus cron & lock saat plugin/theme dinonaktifkan
	register_deactivation_hook( __FILE__, 'app_update_deactivate_cron' );
	function app_update_deactivate_cron() 
	{
		// Hapus semua jadwal cron untuk event ini
		wp_clear_scheduled_hook( 'check_all_apps_cron' );

		// Hapus lock global jika ada
		delete_transient( 'app_update_global_cron_lock' );

		// Optional: Bersihkan lock per-app yang mungkin tertinggal
		global $wpdb;
		$wpdb->query(
			"DELETE FROM {$wpdb->options}
			 WHERE option_name LIKE '_transient_apk_update_lock_%'
				OR option_name LIKE '_transient_timeout_apk_update_lock_%'"
		);
	}
}

/* --------------------------------------------------------------------
 * BACA DULU
 * --------------------------------------------------------------------
 * 
 * Jika Anda menggunakan sebagai PLUGIN:
 * Hapus bagian 3 dan 4 (yang pakai switch_theme dan after_switch_theme).
 * 
 * Jika Anda menggunakan sebagai THEME:
 * 
 * Ubah TEXT_DOMAIN menjadi nama folder theme Anda, contoh:
 * 
*/

if ( ! function_exists( 'app_update_cleanup_on_theme_switch' ) ) 
{
	// 3. Jika ini adalah THEME: Bersihkan cron saat theme diganti (switch away)
	add_action( 'switch_theme', 'app_update_cleanup_on_theme_switch', 10, 3 );
	function app_update_cleanup_on_theme_switch( $new_name, $new_theme, $old_theme ) 
	{
		// Hanya jalankan cleanup jika theme lama adalah theme Anda
		// Ganti 'your-theme-slug' dengan folder name theme Anda (misalnya 'appstore-theme')
		$your_theme_slug = TEXT_DOMAIN; // ← UBAH INI!

		if ( $old_theme->get_template() === $your_theme_slug ) {
			wp_clear_scheduled_hook( 'check_all_apps_cron' );
			delete_transient( 'app_update_global_cron_lock' );

			// Bersihkan lock per-app
			global $wpdb;
			$wpdb->query(
				"DELETE FROM {$wpdb->options}
				 WHERE option_name LIKE '_transient_apk_update_lock_%'
					OR option_name LIKE '_transient_timeout_apk_update_lock_%'"
			);
		}
	}
}

if ( ! function_exists( 'app_update_reschedule_on_theme_activation' ) ) 
{
	// 4. Jika ini adalah THEME: Jadwalkan ulang cron saat theme Anda diaktifkan kembali
	add_action( 'after_switch_theme', 'app_update_reschedule_on_theme_activation' );
	function app_update_reschedule_on_theme_activation( $new_name, $new_theme ) 
	{
		// Ganti 'your-theme-slug' dengan slug theme Anda
		$your_theme_slug = TEXT_DOMAIN; // ← UBAH INI!
		$setting_interval = get_option( 'app_update_cron_interval', 'every_6_hours' );

		if ( $new_theme->get_template() === $your_theme_slug ) {
			if ( ! wp_next_scheduled( 'check_all_apps_cron' ) ) {
				wp_schedule_event( time(), $setting_interval, 'check_all_apps_cron' );
			}
		}
	}
}

if ( ! function_exists( 'force_schedule_app_update_cron_once' ) ) 
{
	// === SEMENTARA: Paksa jadwalkan ulang cron secara otomatis ===
	add_action( 'admin_init', 'force_schedule_app_update_cron_once' );
	function force_schedule_app_update_cron_once() 
	{
		// Hanya untuk admin
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		$setting_interval = get_option( 'app_update_cron_interval', 'every_6_hours' );
		// Gunakan transient agar hanya berjalan SEKALI
		//if ( get_transient( 'force_run_cron_done' ) ) {
		// return; // Sudah pernah dijalankan
		//}
		// Cek apakah cron sudah terjadwal
		if ( ! wp_next_scheduled( 'check_all_apps_cron' ) ) {
			// Jadwalkan dengan interval every_6_hours
			wp_schedule_event( time(), $setting_interval, 'check_all_apps_cron' );
			if ( isset( $_GET['page'] ) && $_GET['page'] === 'apps_updates' ) {
					// Tampilkan notice sekali saja
					add_action( 'admin_notices', function() {
						echo '<div class="notice notice-success is-dismissible">
								<p><strong>✅ Background cron successfully rescheduled!</strong><br>
								Now the cron status will show "Active".</p>
							  </div>';
					} );
			}
		}
	}
}
/**
 * =====================================================================
 *  TEMPORARY CODE - FORCE FIRST BATCH RUN (RUNS ONLY ONCE)
 *  
 *  Tujuan: Memastikan proses pengecekan pertama langsung berjalan setelah 
 *  aktivasi plugin, sehingga log & hasil langsung terlihat di Cron Status.
 *  
 *  HAPUS SELURUH BLOK INI SETELAH:
 *  - Halaman Cron Status sudah menunjukkan log terbaru
 *  - Ada entri aktivitas di tabel log
 *  - Notice sukses sudah pernah muncul minimal sekali
 * =====================================================================
 */
if (!function_exists('app_update_force_first_batch_once')) 
{
    //add_action('admin_init', 'app_update_force_first_batch_once', 20); // priority rendah agar jalan setelah inisialisasi lain

    function app_update_force_first_batch_once() 
	{
        // Hanya jalankan di area admin + hanya untuk user yang berhak
        if (!is_admin() || !current_user_can('manage_options')) {
            return;
        }

        // Cek apakah sudah pernah dijalankan (menggunakan transient)
        if (get_transient('app_update_first_batch_forced')) {
            return;
        }

        // Jalankan proses batch check (jika fungsi tersedia)
        if (function_exists('app_update_run_batch_check')) {
            app_update_run_batch_check();

            // Tandai bahwa proses pertama sudah dipaksa
            set_transient('app_update_first_batch_forced', 'done', WEEK_IN_SECONDS * 4); // 4 minggu cukup aman

            // Tambahkan notice sekali saja di halaman yang relevan
            add_action('admin_notices', function () {
                // Hanya tampilkan di halaman Cron Status (atau halaman lain yang kamu inginkan)
                $current_page = isset($_GET['page']) ? $_GET['page'] : '';
                if (in_array($current_page, ['apps_updates', 'app-update-cron-status', 'app_update_cron_status'])) {
                    ?>
                    <div class="notice notice-success is-dismissible">
                        <p><strong>✅ First automatic background check has been forced!</strong></p>
                        <p>Initial batch processing has been triggered successfully.<br>
                        Refresh this page to see the latest activity log.</p>
                        <p style="margin-top:12px; opacity:0.85;">
                            <em>(You can now safely delete the temporary "force first batch" code block from your plugin.)</em>
                        </p>
                    </div>
                    <?php
                }
            });
        }
    }
}

/**
 * TEMPORARY: Force run first batch only once per site (permanently)
 * Kode ini akan otomatis berhenti setelah pertama kali berhasil
 * Tidak perlu dihapus manual dari file
 */
add_action('admin_init', function() {
    // Hanya di admin + user berhak
    if (!is_admin() || !current_user_can('manage_options')) {
        return;
    }

    // Flag permanen (option) – kalau sudah ada, langsung keluar
    if (get_option('app_update_first_batch_forced_done')) {
        return;
    }

    // Jalankan batch pertama
    if (function_exists('app_update_run_batch_check')) {
        app_update_run_batch_check();

        // Tandai bahwa sudah pernah jalan (selamanya)
        update_option('app_update_first_batch_forced_done', '1', 'no'); // autoload false biar ringan

        // Tampilkan notice sekali saja
        add_action('admin_notices', function() {
            $page = isset($_GET['page']) ? $_GET['page'] : '';
            if (in_array($page, ['apps_updates', 'app-update-cron-status', 'app_update_cron_status'])) {
                ?>
                <div class="notice notice-success is-dismissible">
                    <p><strong>✅ First background batch check has been automatically triggered!</strong></p>
                    <p>Proses awal selesai. Log aktivitas sekarang sudah tersedia.</p>
                    <p><em>Kode "force first batch" ini sekarang sudah non-aktif permanen.</em></p>
                </div>
                <?php
            }
        });
    }
}, 20);

/* ===================================================================
   Enqueue Script & AJAX Clear Log
   =================================================================== 
*/
if ( ! function_exists( 'app_update_enqueue_cron_status_scripts' ) ) 
{
	add_action( 'admin_enqueue_scripts', 'app_update_enqueue_cron_status_scripts' );
	function app_update_enqueue_cron_status_scripts( $hook ) 
	{
		// Load hanya di halaman yang relevan
		if ( ! isset( $_GET['page'] ) || ! in_array( $_GET['page'], ['app-update-list', 'apps_updates', 'app-update-list', 'app-update-settings'] ) ) {
			return;
		}

		wp_enqueue_script( 'jquery' );

		$script = '
		jQuery(function($) {
			$("#app-update-clear-log-btn").on("click", function() {
				if (!confirm("' . esc_js( __( 'Are you sure you want to clear all activity logs? This action cannot be undone.', TEXT_DOMAIN ) ) . '")) {
					return;
				}
				var btn = $(this);
				btn.prop("disabled", true).text("' . esc_js( __( 'Clearing...', TEXT_DOMAIN ) ) . '");

				$.post(ajaxurl, {
					action: "app_update_clear_log_ajax",
					_ajax_nonce: "' . wp_create_nonce( 'app_update_clear_log_ajax' ) . '"
				}, function(res) {
					if (res.success) {
						$("#app-update-log-section").fadeOut(400, function() {
							$(this).html("<p><em>' . esc_js( __( 'No activity recorded yet. Run a check to see logs here.', TEXT_DOMAIN ) ) . '</em></p>").fadeIn(400);
						});
						$("#app-update-last-batch").html("<em>' . esc_js( __( 'No batch has run yet.', TEXT_DOMAIN ) ) . '</em>");
						$(".wrap").prepend("<div class=\"notice notice-success is-dismissible\"><p><strong>✅ " + res.data.message + "</strong></p></div>");
					} else {
						alert("Error: " + (res.data ? res.data.message : "Unknown error"));
					}
				}).always(function() {
					btn.prop("disabled", false).text("' . esc_js( __( 'Clear All Log', TEXT_DOMAIN ) ) . '");
				});
			});
		});
		';
		wp_add_inline_script( 'jquery', $script );
	}
}

/* ===================================================================
   AJAX Handler: Clear Log
   =================================================================== 
*/
if ( ! function_exists( 'app_update_ajax_clear_log' ) ) 
{
	add_action( 'wp_ajax_app_update_clear_log_ajax', 'app_update_ajax_clear_log' );
	function app_update_ajax_clear_log() 
	{
		check_ajax_referer( 'app_update_clear_log_ajax' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', TEXT_DOMAIN ) ] );
		}

		delete_option( 'app_update_cron_last_log' );

		wp_send_json_success( [
			'message' => __( 'All activity logs have been cleared successfully!', TEXT_DOMAIN )
		] );
	}
}

/* --------------------------------------------------------------------
 * Tambahkan Widget Status App Update ke Dashboard Utama WordPress
 * ------------------------------------------------------------------ 
 */
if ( ! function_exists( 'app_update_add_dashboard_widget' ) ) 
{
	add_action( 'wp_dashboard_setup', 'app_update_add_dashboard_widget' );
	function app_update_add_dashboard_widget() 
	{
		// Hanya untuk admin yang punya hak manage_options
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		wp_add_dashboard_widget(
			'app_update_cron_status_widget',                  // Widget ID
			__( 'App Update Background Checker', TEXT_DOMAIN ), // Judul widget
			'app_update_render_dashboard_widget'              // Callback render
		);

		// Optional: Pindahkan widget ke posisi atas (prioritas tinggi)
		global $wp_meta_boxes;
		$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
		$widget    = [ 'app_update_cron_status_widget' => $dashboard['app_update_cron_status_widget'] ];
		unset( $dashboard['app_update_cron_status_widget'] );
		$sorted_dashboard = array_merge( $widget, $dashboard );
		$wp_meta_boxes['dashboard']['normal']['core'] = $sorted_dashboard;
	}
}

/**
 * Render isi widget di dashboard
 */
if ( ! function_exists( 'app_update_render_dashboard_widget' ) ) 
{
	function app_update_render_dashboard_widget()
	{
		$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', [] );
		$count_updates  = apk_update_count_posts(); // jumlah app butuh update

		// Deteksi interval
		$current_interval = __( 'Not scheduled', TEXT_DOMAIN );
		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['interval'] ) ) {
							$interval = $hook_data['interval'];
							foreach ( $schedules as $name => $sched ) {
								if ( $sched['interval'] === $interval ) {
									$current_interval = $sched['display'];
									break 2;
								}
							}
						}
					}
				}
			}
		}

		// URL manual check & link ke halaman detail
		$force_url   = wp_nonce_url( add_query_arg( 'app_update_force_check', '1' ), 'app_update_force_check_all' );
		$status_page = admin_url( 'admin.php?page=apps_updates' );
		$updates_page = admin_url( 'admin.php?page=app-update-list' );
		?>

		<div style="padding:10px 0; font-size:13px; line-height:1.6;">
			<!-- Status Ringkasan -->
			<p>
                <strong><?php esc_html_e('Status:', TEXT_DOMAIN); ?></strong><br>
                <?php if ($next_scheduled): ?>
                    <span style="color:#46b450; font-weight:600;">✓ <?php esc_html_e('Active & Scheduled', TEXT_DOMAIN); ?></span>
                <?php else: ?>
                    <span style="color:#d63638; font-weight:600;">✗ <?php esc_html_e('Not Scheduled', TEXT_DOMAIN); ?></span>
                <?php endif; ?>
			</p>

			<p>
				<strong><?php esc_html_e('PHP Version', TEXT_DOMAIN); ?></strong><br>
				<strong style="color:#46b450; font-weight:600;"><?php echo esc_html(PHP_VERSION); ?></strong>
			</p>

			<p>
                <strong><?php esc_html_e('Next Run:', TEXT_DOMAIN); ?></strong><br>
                <?php if ($next_scheduled): ?>
                    <?php echo esc_html(date_i18n('j M Y @ H:i', $next_scheduled)); ?>
                    <span style="color:#646970;">(<?php echo esc_html(human_time_diff($next_scheduled)); ?>)</span>
                <?php else: ?>
                    <em><?php esc_html_e('Not scheduled yet', TEXT_DOMAIN); ?></em>
                <?php endif; ?>
			</p>

			<p>
                <strong><?php esc_html_e('Interval:', TEXT_DOMAIN); ?></strong><br>
                <?php echo esc_html($current_interval); ?>
			</p>


			<p>
                <strong><?php esc_html_e('Current Process:', TEXT_DOMAIN); ?></strong><br>
                <?php if ($lock_active): ?>
                    <span style="color:#ffb900; font-weight:600;">🔒 <?php esc_html_e('Running in background...', TEXT_DOMAIN); ?></span>
                <?php else: ?>
                    <span style="color:#46b450; font-weight:600;">✓ <?php esc_html_e('Idle – ready for next run', TEXT_DOMAIN); ?></span>
                <?php endif; ?>
			</p>


			<p>
				<strong><?php esc_html_e( 'App(s) to Need Update:', TEXT_DOMAIN ); ?></strong><br>
				<?php if ( $count_updates > 0 ) : ?>
					<a href="<?php echo esc_url( $updates_page ); ?>"><strong style="color:#4fadf1;font-size: 2rem;"><?php echo number_format_i18n( $count_updates ); ?> </strong></a> <?php esc_html_e( 'Apps ', TEXT_DOMAIN ); ?>
				<?php else : ?>
					<span style="color:green;"><?php esc_html_e( 'All up to date!', TEXT_DOMAIN ); ?></span>
				<?php endif; ?>
			</p>

			<?php if ( ! empty( $last_log ) ) : ?>
			<p>
					<strong><?php esc_html_e( 'Last Batch:', TEXT_DOMAIN ); ?></strong><br>
					<small><?php echo esc_html( $last_log[0]['message'] ); ?><br>
					<em><?php echo esc_html( $last_log[0]['time'] ); ?></em></small>
			</p>
			<?php endif; ?>

			<!-- Tombol Aksi -->
			<p style="margin-top:20px;">
				<a href="<?php echo esc_url( $force_url ); ?>" class="button button-primary">
					<?php esc_html_e( 'Run Check Now', TEXT_DOMAIN ); ?>
				</a>
				<a href="<?php echo esc_url( $status_page ); ?>" class="button" style="margin-left:10px;">
					<?php esc_html_e( 'View Details →', TEXT_DOMAIN ); ?>
				</a>
			</p>

			<?php if ( ! $next_scheduled ) : ?>
				<p style="margin-top:15px; color:#d63638; font-size:0.9em;">
					<strong><?php esc_html_e( 'Cron not scheduled?', TEXT_DOMAIN ); ?></strong><br>
					<?php esc_html_e( 'Click "Run Check Now" above — WordPress will automatically schedule it.', TEXT_DOMAIN ); ?>
				</p>
			<?php endif; ?>
		</div>
		<?php
	}
}
