<?php
/**
 * Manages Kkart plugin updating on the Updates screen.
 *
 * @package     Kkart\Admin
 * @version     3.2.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'KKART_Plugin_Updates' ) ) {
	include_once dirname( __FILE__ ) . '/class-kkart-plugin-updates.php';
}

/**
 * Class KKART_Updates_Screen_Updates
 */
class KKART_Updates_Screen_Updates extends KKART_Plugin_Updates {

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'admin_print_footer_scripts', array( $this, 'update_screen_modal' ) );
	}

	/**
	 * Show a warning message on the upgrades screen if the user tries to upgrade and has untested plugins.
	 */
	public function update_screen_modal() {
		$updateable_plugins = get_plugin_updates();
		if ( empty( $updateable_plugins['kkart/kkart.php'] )
			|| empty( $updateable_plugins['kkart/kkart.php']->update )
			|| empty( $updateable_plugins['kkart/kkart.php']->update->new_version ) ) {
			return;
		}

		$this->new_version            = kkart_clean( $updateable_plugins['kkart/kkart.php']->update->new_version );
		$this->major_untested_plugins = $this->get_untested_plugins( $this->new_version, 'major' );

		if ( ! empty( $this->major_untested_plugins ) ) {
			echo $this->get_extensions_modal_warning(); // phpcs:ignore WordPress.XSS.EscapeOutput.OutputNotEscaped
			$this->update_screen_modal_js();
		}
	}

	/**
	 * JS for the modal window on the updates screen.
	 */
	protected function update_screen_modal_js() {
		?>
		<script>
			( function( $ ) {
				var modal_dismissed = false;

				// Show the modal if the KKART upgrade checkbox is checked.
				var show_modal_if_checked = function() {
					if ( modal_dismissed ) {
						return;
					}
					var $checkbox = $( 'input[value="kkart/kkart.php"]' );
					if ( $checkbox.prop( 'checked' ) ) {
						$( '#kkart-upgrade-warning' ).click();
					}
				}

				$( '#plugins-select-all, input[value="kkart/kkart.php"]' ).on( 'change', function() {
					show_modal_if_checked();
				} );

				// Add a hidden thickbox link to use for bringing up the modal.
				$('body').append( '<a href="#TB_inline?height=600&width=550&inlineId=kkart_untested_extensions_modal" class="kkart-thickbox" id="kkart-upgrade-warning" style="display:none"></a>' );

				// Don't show the modal again once it's been accepted.
				$( '#kkart_untested_extensions_modal .accept' ).on( 'click', function( evt ) {
					evt.preventDefault();
					modal_dismissed = true;
					tb_remove();
				});

				// Uncheck the KKART update checkbox if the modal is canceled.
				$( '#kkart_untested_extensions_modal .cancel' ).on( 'click', function( evt ) {
					evt.preventDefault();
					$( 'input[value="kkart/kkart.php"]' ).prop( 'checked', false );
					tb_remove();
				});
			})( jQuery );
		</script>
		<?php
		$this->generic_modal_js();
	}
}
new KKART_Updates_Screen_Updates();
