<?php
/**
 * Shopwell About page class.
 *
 * @package     Shopwell
 * @author      Peregrine Themes
 * @since       1.0.0
 */

use Shopwell\Admin\Utilities\Shopwell_Plugin_Utilities;

/**
 * Do not allow direct script access.
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'Shopwell_Dashboard' ) ) :
	/**
	 * Shopwell Dashboard page class.
	 */
	final class Shopwell_Dashboard {

		/**
		 * Singleton instance of the class.
		 *
		 * @since 1.0.0
		 * @var object
		 */
		private static $instance;

		/**
		 * Main Shopwell Dashboard Instance.
		 *
		 * @since 1.0.0
		 * @return Shopwell_Dashboard
		 */
		public static function instance() {

			if ( ! isset( self::$instance ) && ! ( self::$instance instanceof Shopwell_Dashboard ) ) {
				self::$instance = new self();
			}
			return self::$instance;
		}

		/**
		 * Primary class constructor.
		 *
		 * @since 1.0.0
		 */
		public function __construct() {

			/**
			 * Register admin menu item under Appearance menu item.
			 */
			add_action( 'admin_menu', array( $this, 'add_to_menu' ), 10 );
			add_filter( 'submenu_file', array( $this, 'highlight_submenu' ) );

			/**
			 * Ajax activate & deactivate plugins.
			 */
			add_action( 'wp_ajax_hester-plugin-activate', array( $this, 'activate_plugin' ) );
			add_action( 'wp_ajax_hester-plugin-deactivate', array( $this, 'deactivate_plugin' ) );
			add_action( 'wp_ajax_shopwell-plugins-bulk-activate', array( $this, 'bulk_activate_plugins' ) );

			/**
			 * WP core only raises the execution time limit AFTER a plugin zip has
			 * downloaded (see WP_Upgrader::install_package()), so a slow connection
			 * to WordPress.org can still hit max_execution_time mid-download. Raise
			 * it ourselves before core's own install/update AJAX handlers run.
			 */
			add_action( 'wp_ajax_install-plugin', array( $this, 'raise_install_time_limit' ), 0 );
			add_action( 'wp_ajax_update-plugin', array( $this, 'raise_install_time_limit' ), 0 );
		}

		/**
		 * Raise the PHP execution time limit before a plugin install/update
		 * request starts, so a slow plugin-zip download doesn't get killed
		 * mid-transfer. No-ops on hosts where set_time_limit() is disabled.
		 *
		 * @since 1.0.17
		 */
		public function raise_install_time_limit() {

			if ( function_exists( 'set_time_limit' ) ) {
				set_time_limit( 300 );
			}
		}

		/**
		 * Register our custom admin menu item.
		 *
		 * @since 1.0.0
		 */
		public function add_to_menu() {

			/**
			 * Dashboard page.
			 */
			add_theme_page(
				esc_html__( 'Shopwell Theme', 'shopwell' ),
				'Shopwell Theme',
				apply_filters( 'shopwell_manage_cap', 'edit_theme_options' ),
				'shopwell-dashboard',
				array( $this, 'render_dashboard' )
			);

			/**
			 * Plugins page.
			 */
			add_theme_page(
				esc_html__( 'Plugins', 'shopwell' ),
				'Plugins',
				apply_filters( 'shopwell_manage_cap', 'edit_theme_options' ),
				'shopwell-plugins',
				array( $this, 'render_plugins' )
			);

			// Hide from admin navigation.
			remove_submenu_page( 'themes.php', 'shopwell-plugins' );

			/**
			 * Changelog page.
			 */
			add_theme_page(
				esc_html__( 'Changelog', 'shopwell' ),
				'Changelog',
				apply_filters( 'shopwell_manage_cap', 'edit_theme_options' ),
				'shopwell-changelog',
				array( $this, 'render_changelog' )
			);

			// Hide from admin navigation.
			remove_submenu_page( 'themes.php', 'shopwell-changelog' );
		}

		/**
		 * Render dashboard page.
		 *
		 * @since 1.0.0
		 */
		public function render_dashboard() {

			// Render dashboard navigation.
			$this->render_navigation();

			?>
			<div class="hester-container">

				<div class="hester-section-title">
					<h2 class="hester-section-title"><?php esc_html_e( 'Getting Started', 'shopwell' ); ?></h2>
				</div><!-- END .hester-section-title -->

				<div class="hester-section hester-columns">

					<div class="hester-column">
						<div class="hester-box">
							<h4><i class="dashicons dashicons-admin-plugins"></i><?php esc_html_e( 'Install Plugins', 'shopwell' ); ?></h4>
							<p><?php esc_html_e( 'Explore recommended plugins. These free plugins provide additional features and customization options.', 'shopwell' ); ?></p>

							<div class="hester-buttons">
								<a href="<?php echo esc_url( menu_page_url( 'shopwell-plugins', false ) ); ?>" class="hester-btn secondary" role="button"><?php esc_html_e( 'Install Plugins', 'shopwell' ); ?></a>
							</div><!-- END .hester-buttons -->
						</div>
					</div>

					<div class="hester-column">
						<div class="hester-box">
							<h4><i class="dashicons dashicons-layout"></i><?php esc_html_e( 'Start with a Template', 'shopwell' ); ?></h4>
							<p><?php esc_html_e( 'Don&rsquo;t want to start from scratch? Import a pre-built demo website in 1-click and get a head start.', 'shopwell' ); ?></p>

							<div class="hester-buttons plugins">

								<?php
								if ( file_exists( WP_PLUGIN_DIR . '/hester-core/hester-core.php' ) && is_plugin_inactive( 'hester-core/hester-core.php' ) ) {
									$class       = 'hester-btn secondary';
									$button_text = __( 'Activate Hester Core', 'shopwell' );
									$link        = '#';
									$data        = ' data-plugin="hester-core" data-action="activate" data-redirect="' . esc_url( admin_url( 'admin.php?page=shopwell-demo-library' ) ) . '"';
								} elseif ( ! file_exists( WP_PLUGIN_DIR . '/hester-core/hester-core.php' ) ) {
									$class       = 'hester-btn secondary';
									$button_text = __( 'Install Hester Core', 'shopwell' );
									$link        = '#';
									$data        = ' data-plugin="hester-core" data-action="install" data-redirect="' . esc_url( admin_url( 'admin.php?page=shopwell-demo-library' ) ) . '"';
								} else {
									$class       = 'hester-btn secondary active';
									$button_text = __( 'Browse Demos', 'shopwell' );
									$link        = admin_url( 'admin.php?page=shopwell-demo-library' );
									$data        = '';
								}

								printf(
									'<a class="%1$s" %2$s %3$s role="button"> %4$s </a>',
									esc_attr( $class ),
									isset( $link ) ? 'href="' . esc_url( $link ) . '"' : '',
									$data, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
									esc_html( $button_text )
								);
								?>

							</div><!-- END .hester-buttons -->
						</div>
					</div>

					<div class="hester-column">
						<div class="hester-box">
							<h4><i class="dashicons dashicons-palmtree"></i><?php esc_html_e( 'Upload Your Logo', 'shopwell' ); ?></h4>
							<p><?php esc_html_e( 'Kick off branding your new site by uploading your logo. Simply upload your logo and customize as you need.', 'shopwell' ); ?></p>

							<div class="hester-buttons">
								<a href="<?php echo esc_url( admin_url( 'customize.php?autofocus[control]=custom_logo' ) ); ?>" class="hester-btn secondary" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Upload Logo', 'shopwell' ); ?></a>
							</div><!-- END .hester-buttons -->
						</div>
					</div>

					<div class="hester-column">
						<div class="hester-box">
							<h4><i class="dashicons dashicons-welcome-widgets-menus"></i><?php esc_html_e( 'Change Menus', 'shopwell' ); ?></h4>
							<p><?php esc_html_e( 'Customize menu links and choose what&rsquo;s displayed in available theme menu locations.', 'shopwell' ); ?></p>

							<div class="hester-buttons">
								<a href="<?php echo esc_url( admin_url( 'nav-menus.php' ) ); ?>" class="hester-btn secondary" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Go to Menus', 'shopwell' ); ?></a>
							</div><!-- END .hester-buttons -->
						</div>
					</div>

					<div class="hester-column">
						<div class="hester-box">
							<h4><i class="dashicons dashicons-art"></i><?php esc_html_e( 'Change Colors', 'shopwell' ); ?></h4>
							<p><?php esc_html_e( 'Replace the default theme colors and make your website color scheme match your brand design.', 'shopwell' ); ?></p>

							<div class="hester-buttons">
								<a href="<?php echo esc_url( admin_url( 'customize.php?autofocus[section]=shopwell_section_colors' ) ); ?>" class="hester-btn secondary" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Change Colors', 'shopwell' ); ?></a>
							</div><!-- END .hester-buttons -->
						</div>
					</div>

					<div class="hester-column">
						<div class="hester-box">
							<h4><i class="dashicons dashicons-editor-help"></i><?php esc_html_e( 'Need Help?', 'shopwell' ); ?></h4>
							<p><?php esc_html_e( 'Head over to our site to learn more about the Shopwell theme, read help articles and get support.', 'shopwell' ); ?></p>

							<div class="hester-buttons">
								<a href="http://docs.peregrine-themes.com/" target="_blank" rel="noopener noreferrer" class="hester-btn secondary"><?php esc_html_e( 'Help Articles', 'shopwell' ); ?></a>
							</div><!-- END .hester-buttons -->
						</div>
					</div>
				</div><!-- END .hester-section -->

				<div class="hester-section large-section">
					<div class="hester-hero">
						<img src="<?php echo esc_url( SHOPWELL_THEME_URI . '/assets/images/shopwell-customize.svg' ); ?>" alt="<?php echo esc_html( 'Customize' ); ?>" />
					</div>

					<h2><?php esc_html_e( 'Let‘s customize your website', 'shopwell' ); ?></h2>
					<p><?php esc_html_e( 'There are many changes you can make to customize your website. Explore Shopwell customization options and make it unique.', 'shopwell' ); ?></p>

					<div class="hester-buttons">
						<a href="<?php echo esc_url( admin_url( 'customize.php' ) ); ?>" class="hester-btn primary large-button"><?php esc_html_e( 'Start Customizing', 'shopwell' ); ?></a>
					</div><!-- END .hester-buttons -->

				</div><!-- END .hester-section -->

				<?php do_action( 'shopwell_about_content_after' ); ?>

			</div><!-- END .hester-container -->

			<?php
		}

		/**
		 * Render the recommended plugins page.
		 *
		 * @since 1.0.0
		 */
		public function render_plugins() {

			// Render dashboard navigation.
			$this->render_navigation();

			$plugins       = shopwell_plugin_utilities()->get_recommended_plugins();
			$not_installed = shopwell_plugin_utilities()->get_not_installed_plugins( $plugins );
			$not_active    = shopwell_plugin_utilities()->get_deactivated_plugins( $plugins );
			$all_active    = false;

			// Not everything is installed yet - a single click installs & activates everything needed.
			if ( ! empty( $not_installed ) ) {

				$bulk_text = esc_html__( 'Install & Activate All', 'shopwell' );
				$bulk_data = array(
					'shopwell-bulk-action'   => 'install',
					'shopwell-install-list'  => wp_json_encode( array_keys( $not_installed ) ),
					'shopwell-activate-list' => wp_json_encode( array_keys( array_diff_key( $not_active, $not_installed ) ) ),
					'shopwell-plugin-names'  => wp_json_encode( wp_list_pluck( $not_active, 'name' ) ),
				);
			} elseif ( ! empty( $not_active ) ) {

				// Everything is already installed, only activation is left.
				$bulk_text = esc_html__( 'Activate All', 'shopwell' );
				$bulk_data = array(
					'shopwell-bulk-action'   => 'activate',
					'shopwell-activate-list' => wp_json_encode( array_keys( $not_active ) ),
					'shopwell-plugin-names'  => wp_json_encode( wp_list_pluck( $not_active, 'name' ) ),
				);
			} else {
				$bulk_text  = '';
				$bulk_data  = array();
				$all_active = is_array( $plugins ) && ! empty( $plugins );
			}
			?>
			<div class="hester-container">

				<div class="hester-section-title">
					<h2 class="hester-section-title"><?php esc_html_e( 'Recommended Plugins', 'shopwell' ); ?></h2>

					<?php if ( $bulk_text ) : ?>
						<div class="hester-filters">
							<a href="#" class="hester-btn primary shopwell-bulk-plugins-action"
								<?php
								foreach ( $bulk_data as $data_key => $data_value ) {
									echo ' data-' . esc_attr( $data_key ) . '="' . esc_attr( $data_value ) . '"'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
								}
								?>
								role="button">
								<span class="shopwell-notice-spinner"></span>
								<span class="shopwell-notice-action-text" role="status" aria-live="polite"><?php echo esc_html( $bulk_text ); ?></span>
							</a>
						</div>
					<?php elseif ( $all_active ) : ?>
						<div class="hester-filters">
							<span class="hester-btn secondary hester-active-plugin">
								<span class="dashicons dashicons-yes-alt"></span>
								<?php esc_html_e( 'All Activated', 'shopwell' ); ?>
							</span>
						</div>
					<?php endif; ?>
				</div><!-- END .hester-section-title -->

				<div class="hester-section hester-columns plugins">

					<?php if ( is_array( $plugins ) && ! empty( $plugins ) ) { ?>
						<?php foreach ( $plugins as $plugin ) { ?>

							<?php
							// Check plugin status.
							if ( shopwell_plugin_utilities()->is_activated( $plugin['slug'] ) ) {
								$btn_class = 'hester-btn secondary';
								$btn_text  = esc_html__( 'Deactivate', 'shopwell' );
								$action    = 'deactivate';
								$notice    = '<span class="hester-active-plugin"><span class="dashicons dashicons-yes"></span>' . esc_html__( 'Plugin activated', 'shopwell' ) . '</span>';
							} elseif ( shopwell_plugin_utilities()->is_installed( $plugin['slug'] ) ) {
								$btn_class = 'hester-btn primary';
								$btn_text  = esc_html__( 'Activate', 'shopwell' );
								$action    = 'activate';
								$notice    = '';
							} else {
								$btn_class = 'hester-btn primary';
								$btn_text  = esc_html__( 'Install & Activate', 'shopwell' );
								$action    = 'install';
								$notice    = '';
							}
							?>

							<div class="hester-column column-6">
								<div class="hester-box">

									<div class="plugin-image">
										<img src="<?php echo esc_url( $plugin['thumb'] ); ?>" alt="<?php echo esc_html( $plugin['name'] ); ?>"/>
									</div>

									<div class="plugin-info">
										<h4><?php echo esc_html( $plugin['name'] ); ?></h4>
										<p><?php echo esc_html( $plugin['desc'] ); ?></p>
										<div class="hester-buttons">
											<?php echo ( wp_kses_post( $notice ) ); ?>
											<a href="#" class="<?php echo esc_attr( $btn_class ); ?>" data-plugin="<?php echo esc_attr( $plugin['slug'] ); ?>" data-action="<?php echo esc_attr( $action ); ?>"><?php echo esc_html( $btn_text ); ?></a>
										</div>
									</div>

								</div>
							</div>
						<?php } ?>
					<?php } ?>

				</div><!-- END .hester-section -->

				<?php do_action( 'shopwell_recommended_plugins_after' ); ?>

			</div><!-- END .hester-container -->

			<?php
		}

		/**
		 * Render the changelog page.
		 *
		 * @since 1.0.0
		 */
		public function render_changelog() {

			// Render dashboard navigation.
			$this->render_navigation();

			$changelog = SHOPWELL_THEME_PATH . '/changelog.txt';

			if ( ! file_exists( $changelog ) ) {
				$changelog = esc_html__( 'Changelog file not found.', 'shopwell' );
			} elseif ( ! is_readable( $changelog ) ) {
				$changelog = esc_html__( 'Changelog file not readable.', 'shopwell' );
			} else {
				global $wp_filesystem;

				// Check if the the global filesystem isn't setup yet.
				if ( is_null( $wp_filesystem ) ) {
					WP_Filesystem();
				}

				$changelog = $wp_filesystem->get_contents( $changelog );
			}

			?>
			<div class="hester-container">

				<div class="hester-section-title">
					<h2 class="hester-section-title">
						<span><?php esc_html_e( 'Shopwell Theme Changelog', 'shopwell' ); ?></span>
						<span class="changelog-version"><?php echo esc_html( sprintf( 'v%1$s', SHOPWELL_THEME_VERSION ) ); ?></span>
					</h2>

				</div><!-- END .hester-section-title -->

				<div class="hester-section hester-columns">

					<div class="hester-column column-12">
						<div class="hester-box hester-changelog">
							<pre><?php echo esc_html( $changelog ); ?></pre>
						</div>
					</div>
				</div><!-- END .hester-columns -->

				<?php do_action( 'shopwell_after_changelog' ); ?>

			</div><!-- END .hester-container -->
			<?php
		}

		/**
		 * Render admin page navigation tabs.
		 *
		 * @since 1.0.0
		 */
		public function render_navigation() {

			// Get navigation items.
			$menu_items = $this->get_navigation_items();

			?>
			<div class="hester-container">

				<div class="hester-tabs">
					<ul>
						<?php
						// Determine current tab.
						$base = $this->get_current_page();

						// Display menu items.
						foreach ( $menu_items as $item ) {

							// Check if we're on a current item.
							$current = false !== strpos( $base, $item['id'] ) ? 'current-item' : '';
							?>

							<li class="<?php echo esc_attr( $current ); ?>">
								<a href="<?php echo esc_url( $item['url'] ); ?>">
									<?php echo esc_html( $item['name'] ); ?>

									<?php
									if ( isset( $item['icon'] ) && $item['icon'] ) {
										shopwell_print_admin_icon( $item['icon'] );
									}
									?>
								</a>
							</li>

						<?php } ?>
					</ul>
				</div><!-- END .hester-tabs -->

			</div><!-- END .hester-container -->
			<?php
		}

		/**
		 * Return the current Shopwell Dashboard page.
		 *
		 * @since 1.0.0
		 * @return string $page Current dashboard page slug.
		 */
		public function get_current_page() {

			$page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : 'dashboard'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$page = str_replace( 'shopwell-', '', $page );
			$page = apply_filters( 'shopwell_dashboard_current_page', $page );

			return esc_html( $page );
		}

		/**
		 * Print admin page navigation items.
		 *
		 * @since 1.0.0
		 * @return array $items Array of navigation items.
		 */
		public function get_navigation_items() {

			$items = array(
				'dashboard' => array(
					'id'   => 'dashboard',
					'name' => esc_html__( 'About', 'shopwell' ),
					'icon' => '',
					'url'  => menu_page_url( 'shopwell-dashboard', false ),
				),
				'plugins'   => array(
					'id'   => 'plugins',
					'name' => esc_html__( 'Recommended Plugins', 'shopwell' ),
					'icon' => '',
					'url'  => menu_page_url( 'shopwell-plugins', false ),
				),
				'changelog' => array(
					'id'   => 'changelog',
					'name' => esc_html__( 'Changelog', 'shopwell' ),
					'icon' => '',
					'url'  => menu_page_url( 'shopwell-changelog', false ),
				),
			);

			return apply_filters( 'shopwell_dashboard_navigation_items', $items );
		}

		/**
		 * Activate plugin.
		 *
		 * @since 1.0.0
		 */
		public function activate_plugin() {

			// Security check.
			check_ajax_referer( 'shopwell_nonce' );

			// Plugin data.
			$plugin = isset( $_POST['plugin'] ) ? sanitize_text_field( wp_unslash( $_POST['plugin'] ) ) : '';

			if ( empty( $plugin ) ) {
				wp_send_json_error( esc_html__( 'Missing plugin data', 'shopwell' ) );
			}

			if ( $plugin ) {

				$response = shopwell_plugin_utilities()->activate_plugin( $plugin );

				if ( is_wp_error( $response ) ) {
					wp_send_json_error( $response->get_error_message(), $response->get_error_code() );
				}

				wp_send_json_success();
			}

			wp_send_json_error( esc_html__( 'Failed to activate plugin. Missing plugin data.', 'shopwell' ) );
		}

		/**
		 * Deactivate plugin.
		 *
		 * @since 1.0.0
		 */
		public function deactivate_plugin() {

			// Security check.
			check_ajax_referer( 'shopwell_nonce' );

			// Plugin data.
			$plugin = isset( $_POST['plugin'] ) ? sanitize_text_field( wp_unslash( $_POST['plugin'] ) ) : '';

			if ( empty( $plugin ) ) {
				wp_send_json_error( esc_html__( 'Missing plugin data', 'shopwell' ) );
			}

			if ( $plugin ) {
				$response = shopwell_plugin_utilities()->deactivate_plugin( $plugin );

				if ( is_wp_error( $response ) ) {
					wp_send_json_error( $response->get_error_message(), $response->get_error_code() );
				}

				wp_send_json_success();
			}

			wp_send_json_error( esc_html__( 'Failed to deactivate plugin. Missing plugin data.', 'shopwell' ) );
		}

		/**
		 * Ajax bulk activate a list of already installed plugins.
		 *
		 * @since 1.0.17
		 */
		public function bulk_activate_plugins() {

			// Security check.
			check_ajax_referer( 'shopwell_nonce' );

			$plugins = isset( $_POST['plugins'] ) ? array_map( 'sanitize_text_field', wp_unslash( (array) $_POST['plugins'] ) ) : array();
			$plugins = array_filter( $plugins );

			if ( empty( $plugins ) ) {
				wp_send_json_error( esc_html__( 'Missing plugin data', 'shopwell' ) );
			}

			$recommended = shopwell_plugin_utilities()->get_recommended_plugins();
			$failed      = array();

			foreach ( $plugins as $plugin ) {

				$response = shopwell_plugin_utilities()->activate_plugin( $plugin );

				if ( is_wp_error( $response ) ) {

					// Log the real reason for later debugging - the end user only ever sees the plugin name.
					if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
						error_log( sprintf( '[Shopwell] Bulk activate failed for "%s": %s', $plugin, $response->get_error_message() ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
					}

					$plugin_data = shopwell_plugin_utilities()->get_plugin_by_slug( $plugin, $recommended );
					$failed[]    = $plugin_data ? $plugin_data['name'] : $plugin;
				}
			}

			if ( ! empty( $failed ) ) {
				wp_send_json_error( array( 'failed' => $failed ) );
			}

			wp_send_json_success();
		}

		/**
		 * Highlight dashboard page for plugins page.
		 *
		 * @since 1.0.0
		 * @param string $submenu_file The submenu file.
		 */
		public function highlight_submenu( $submenu_file ) {

			global $pagenow;

			// Check if we're on shopwell plugins or changelog page.
			if ( 'themes.php' === $pagenow ) {
				if ( isset( $_GET['page'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
					if ( 'shopwell-plugins' === $_GET['page'] || 'shopwell-changelog' === $_GET['page'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
						$submenu_file = 'shopwell-dashboard';
					}
				}
			}

			return $submenu_file;
		}
	}
endif;

/**
 * The function which returns the one Shopwell_Dashboard instance.
 *
 * Use this function like you would a global variable, except without needing
 * to declare the global.
 *
 * Example: <?php $shopwell_dashboard = shopwell_dashboard(); ?>
 *
 * @since 1.0.0
 * @return object
 */
function shopwell_dashboard() {
	return Shopwell_Dashboard::instance();
}

shopwell_dashboard();
