<?php
/**
 * Kkart Admin
 *
 * @class    KKART_Admin
 * @package  Kkart\Admin
 * @version  2.6.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * KKART_Admin class.
 */
class KKART_Admin {

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'init', array( $this, 'includes' ) );
		add_action( 'current_screen', array( $this, 'conditional_includes' ) );
		add_action( 'admin_init', array( $this, 'buffer' ), 1 );
		add_action( 'admin_init', array( $this, 'preview_emails' ) );
		add_action( 'admin_init', array( $this, 'prevent_admin_access' ) );
		add_action( 'admin_init', array( $this, 'admin_redirects' ) );
		add_action( 'admin_footer', 'kkart_print_js', 25 );
		add_filter( 'admin_footer_text', array( $this, 'admin_footer_text' ), 1 );
		add_action( 'init', array( 'KKART_Site_Tracking', 'init' ) );

		// Disable WXR export of schedule action posts.
		add_filter( 'action_scheduler_post_type_args', array( $this, 'disable_webhook_post_export' ) );

		// Add body class for WP 5.3+ compatibility.
		add_filter( 'admin_body_class', array( $this, 'include_admin_body_class' ), 9999 );
	}

	/**
	 * Output buffering allows admin screens to make redirects later on.
	 */
	public function buffer() {
		ob_start();
	}

	/**
	 * Include any classes we need within admin.
	 */
	public function includes() {
		include_once __DIR__ . '/kkart-admin-functions.php';
		include_once __DIR__ . '/kkart-meta-box-functions.php';
		include_once __DIR__ . '/class-kkart-admin-post-types.php';
		include_once __DIR__ . '/class-kkart-admin-taxonomies.php';
		include_once __DIR__ . '/class-kkart-admin-menus.php';
		include_once __DIR__ . '/class-kkart-admin-customize.php';
		include_once __DIR__ . '/class-kkart-admin-notices.php';
		include_once __DIR__ . '/class-kkart-admin-assets.php';
		include_once __DIR__ . '/class-kkart-admin-api-keys.php';
		include_once __DIR__ . '/class-kkart-admin-webhooks.php';
		include_once __DIR__ . '/class-kkart-admin-pointers.php';
		include_once __DIR__ . '/class-kkart-admin-importers.php';
		include_once __DIR__ . '/class-kkart-admin-exporters.php';

		include_once KKART_ABSPATH . 'includes/tracks/class-kkart-tracks.php';
		include_once KKART_ABSPATH . 'includes/tracks/class-kkart-tracks-event.php';
		include_once KKART_ABSPATH . 'includes/tracks/class-kkart-tracks-client.php';
		include_once KKART_ABSPATH . 'includes/tracks/class-kkart-tracks-footer-pixel.php';
		include_once KKART_ABSPATH . 'includes/tracks/class-kkart-site-tracking.php';

		// Help Tabs.
		if ( apply_filters( 'kkart_enable_admin_help_tab', true ) ) {
			include_once __DIR__ . '/class-kkart-admin-help.php';
		}

		// Helper.
		include_once __DIR__ . '/helper/class-kkart-helper.php';

		// Marketplace suggestions & related REST API.
		include_once __DIR__ . '/marketplace-suggestions/class-kkart-marketplace-suggestions.php';
		include_once __DIR__ . '/marketplace-suggestions/class-kkart-marketplace-updater.php';
	}

	/**
	 * Include admin files conditionally.
	 */
	public function conditional_includes() {
		$screen = get_current_screen();

		if ( ! $screen ) {
			return;
		}

		switch ( $screen->id ) {
			case 'dashboard':
			case 'dashboard-network':
				include __DIR__ . '/class-kkart-admin-dashboard.php';
				break;
			case 'options-permalink':
				include __DIR__ . '/class-kkart-admin-permalink-settings.php';
				break;
			case 'plugins':
				include __DIR__ . '/plugin-updates/class-kkart-plugins-screen-updates.php';
				break;
			case 'update-core':
				include __DIR__ . '/plugin-updates/class-kkart-updates-screen-updates.php';
				break;
			case 'users':
			case 'user':
			case 'profile':
			case 'user-edit':
				include __DIR__ . '/class-kkart-admin-profile.php';
				break;
		}
	}

	/**
	 * Handle redirects to setup/welcome page after install and updates.
	 *
	 * The user must have access rights, and we must ignore the network/bulk plugin updaters.
	 */
	public function admin_redirects() {
		// Don't run this fn from Action Scheduler requests, as it would clear _kkart_activation_redirect transient.
		// That means OBW would never be shown.
		if ( kkart_is_running_from_async_action_scheduler() ) {
			return;
		}

		// phpcs:disable WordPress.Security.NonceVerification.Recommended
		// Nonced plugin install redirects.
		if ( ! empty( $_GET['kkart-install-plugin-redirect'] ) ) {
			$plugin_slug = kkart_clean( wp_unslash( $_GET['kkart-install-plugin-redirect'] ) );

			if ( current_user_can( 'install_plugins' ) && in_array( $plugin_slug, array( 'kkart-gateway-stripe' ), true ) ) {
				$nonce = wp_create_nonce( 'install-plugin_' . $plugin_slug );
				$url   = self_admin_url( 'update.php?action=install-plugin&plugin=' . $plugin_slug . '&_wpnonce=' . $nonce );
			} else {
				$url = admin_url( 'plugin-install.php?tab=search&type=term&s=' . $plugin_slug );
			}

			wp_safe_redirect( $url );
			exit;
		}

		// phpcs:enable WordPress.Security.NonceVerification.Recommended
	}

	/**
	 * Prevent any user who cannot 'edit_posts' (subscribers, customers etc) from accessing admin.
	 */
	public function prevent_admin_access() {
		$prevent_access = false;

		if ( apply_filters( 'kkart_disable_admin_bar', true ) && ! is_ajax() && isset( $_SERVER['SCRIPT_FILENAME'] ) && basename( sanitize_text_field( wp_unslash( $_SERVER['SCRIPT_FILENAME'] ) ) ) !== 'admin-post.php' ) {
			$has_cap     = false;
			$access_caps = array( 'edit_posts', 'manage_kkart', 'view_admin_dashboard' );

			foreach ( $access_caps as $access_cap ) {
				if ( current_user_can( $access_cap ) ) {
					$has_cap = true;
					break;
				}
			}

			if ( ! $has_cap ) {
				$prevent_access = true;
			}
		}

		if ( apply_filters( 'kkart_prevent_admin_access', $prevent_access ) ) {
			wp_safe_redirect( kkart_get_page_permalink( 'myaccount' ) );
			exit;
		}
	}

	/**
	 * Preview email template.
	 */
	public function preview_emails() {

		if ( isset( $_GET['preview_kkart_mail'] ) ) {
			if ( ! ( isset( $_REQUEST['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_REQUEST['_wpnonce'] ) ), 'preview-mail' ) ) ) {
				die( 'Security check' );
			}

			// load the mailer class.
			$mailer = KKART()->mailer();

			// get the preview email subject.
			$email_heading = __( 'HTML email template', 'kkart' );

			// get the preview email content.
			ob_start();
			include __DIR__ . '/views/html-email-template-preview.php';
			$message = ob_get_clean();

			// create a new email.
			$email = new KKART_Email();

			// wrap the content with the email template and then add styles.
			$message = apply_filters( 'kkart_mail_content', $email->style_inline( $mailer->wrap_message( $email_heading, $message ) ) );

			// print the preview email.
			// phpcs:ignore WordPress.Security.EscapeOutput
			echo $message;
			// phpcs:enable
			exit;
		}
	}

	/**
	 * Change the admin footer text on Kkart admin pages.
	 *
	 * @since  2.3
	 * @param  string $footer_text text to be rendered in the footer.
	 * @return string
	 */
	public function admin_footer_text( $footer_text ) {
		if ( ! current_user_can( 'manage_kkart' ) || ! function_exists( 'kkart_get_screen_ids' ) ) {
			return $footer_text;
		}
		$current_screen = get_current_screen();
		$kkart_pages       = kkart_get_screen_ids();

		// Set only KKART pages.
		$kkart_pages = array_diff( $kkart_pages, array( 'profile', 'user-edit' ) );

		// Check to make sure we're on a Kkart admin page.
		if ( isset( $current_screen->id ) && apply_filters( 'kkart_display_admin_footer_text', in_array( $current_screen->id, $kkart_pages, true ) ) ) {
			// Change the footer text.
			if ( ! get_option( 'kkart_admin_footer_text_rated' ) ) {
				$footer_text = sprintf(
					/* translators: 1: Kkart 2:: five stars */
					__( 'If you like %1$s please leave us a %2$s rating. A huge thanks in advance!', 'kkart' ),
					sprintf( '<strong>%s</strong>', esc_html__( 'Kkart', 'kkart' ) ),
					'<a href="https://wordpress.org/support/plugin/kkart/reviews?rate=5#new-post" target="_blank" class="kkart-rating-link" aria-label="' . esc_attr__( 'five star', 'kkart' ) . '" data-rated="' . esc_attr__( 'Thanks :)', 'kkart' ) . '">&#9733;&#9733;&#9733;&#9733;&#9733;</a>'
				);
				kkart_enqueue_js(
					"jQuery( 'a.kkart-rating-link' ).click( function() {
						jQuery.post( '" . KKART()->ajax_url() . "', { action: 'kkart_rated' } );
						jQuery( this ).parent().text( jQuery( this ).data( 'rated' ) );
					});"
				);
			} else {
				$footer_text = __( 'Thank you for selling with Kkart.', 'kkart' );
			}
		}

		return $footer_text;
	}

	/**
	 * Check on a Jetpack install queued by the Setup Wizard.
	 *
	 * See: KKART_Admin_Setup_Wizard::install_jetpack()
	 */
	public function setup_wizard_check_jetpack() {
		$jetpack_active = class_exists( 'Jetpack' );

		wp_send_json_success(
			array(
				'is_active' => $jetpack_active ? 'yes' : 'no',
			)
		);
	}

	/**
	 * Disable WXR export of scheduled action posts.
	 *
	 * @since 3.6.2
	 *
	 * @param array $args Scehduled action post type registration args.
	 *
	 * @return array
	 */
	public function disable_webhook_post_export( $args ) {
		$args['can_export'] = false;
		return $args;
	}

	/**
	 * Include admin classes.
	 *
	 * @since 4.2.0
	 * @param string $classes Body classes string.
	 * @return string
	 */
	public function include_admin_body_class( $classes ) {
		if ( in_array( array( 'kkart-wp-version-gte-53', 'kkart-wp-version-gte-55' ), explode( ' ', $classes ), true ) ) {
			return $classes;
		}

		$raw_version   = get_bloginfo( 'version' );
		$version_parts = explode( '-', $raw_version );
		$version       = count( $version_parts ) > 1 ? $version_parts[0] : $raw_version;

		// Add WP 5.3+ compatibility class.
		if ( $raw_version && version_compare( $version, '5.3', '>=' ) ) {
			$classes .= ' kkart-wp-version-gte-53';
		}

		// Add WP 5.5+ compatibility class.
		if ( $raw_version && version_compare( $version, '5.5', '>=' ) ) {
			$classes .= ' kkart-wp-version-gte-55';
		}

		return $classes;
	}
}

return new KKART_Admin();
