<?php

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

if ( ! class_exists( 'Iconvert_Shoply_Admin' ) ) :


	class Iconvert_Shoply_Admin {

		public function __construct() {
			add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );

            add_action( 'admin_notices', array( $this, 'admin_notices' ), 99 );
			add_action( 'wp_ajax_iconvert_shoply_dismiss_notice', array( $this, 'dismiss_notice' ) );

		}



		public function enqueue_scripts() {

			if ( true === (bool) get_option( 'iconvert_shoply_dismissed' ) ) {
				return;
			}





			wp_enqueue_script( 'iconvert-shoply-admin', get_template_directory_uri() . '/assets/js/admin.js', array( 'jquery' ), ICONVERT_SHOPLY_VERSION, 'all' );

			$shoply = array(
				'nonce' => wp_create_nonce( 'iconvert_shoply_notice_dismiss' ),
			);

			wp_localize_script( 'iconvert-shoply-admin', 'iconvertShoply', $shoply );
		}


		public function admin_notices() {
			global $pagenow;

			if ( true === (bool) get_option( 'iconvert_shoply_dismissed' ) ) {
				return;
			}

            if(iconvert_shoply_is_woocommerce_activated()) {
                return;
            }

			if ( wp_get_referer() && 0 === strpos( basename( wp_get_referer() ), 'index.php?page=wc-setup' ) && 'post-new.php' === $pagenow ) {
				return;
			}
			?>

			<div class="notice notice-info iconvert-shoply-notice is-dismissible">
				<?php
					self::admin_notices_content();
				?>
			</div>
			<?php
		}


		public static function admin_notices_content() {
			?>
				<div class="notice-content">
					<?php if ( ! iconvert_shoply_is_woocommerce_activated() && current_user_can( 'install_plugins' ) && current_user_can( 'activate_plugins' ) ) : ?>
						<h2><?php esc_html_e( 'Thanks for installing iConvert Shoply', 'iconvert-shoply' ); ?></h2>
						<p><?php esc_html_e( 'To enable eCommerce features you need to install the WooCommerce plugin.', 'iconvert-shoply' ); ?></p>
						<p><?php Iconvert_Shoply_Plugin_Install::install_plugin_button( 'woocommerce', 'woocommerce.php', 'WooCommerce', array(), __( 'WooCommerce activated', 'iconvert-shoply' ), __( 'Activate WooCommerce', 'iconvert-shoply' ), __( 'Install WooCommerce', 'iconvert-shoply' ) ); ?></p>
					<?php endif; ?>

				</div>
			<?php
		}


		public function dismiss_notice() {
			if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'iconvert_shoply_notice_dismiss' ) || ! current_user_can( 'manage_options' ) ) { // WPCS: input var ok.
				die();
			}

			update_option( 'iconvert_shoply_dismissed', true );
		}

	}

endif;

return new Iconvert_Shoply_Admin();
