<?php
if (!class_exists('sparkconstructionlite_Welcome')) :
    class sparkconstructionlite_Welcome {

        public $tab_sections = array();
        public $theme_name = ''; // For storing Theme Name
        public $theme_version = ''; // For Storing Theme Current Version Information
        public $free_plugins = array(); // For Storing the list of the Recommended Free Plugins
        
        /**
		 * @var array
		 *
		 * @since 1.0.0
		 */
		private $package = array(
			'slug'   => 'ikreate-demo-importer',
			'name'   => 'Ikreate Demo Importer',
			'source' => 'https://ikreatethemes.com/ikreate-demo-importer.zip'
		);

		/**
		 * @var sparkconstructionlite_Demo_Importer
		 *
		 * @since 1.0.0
		 */
		private $plugin = null;

		/**
		 * Redirect.
		 *
		 * @param $url
		 *
		 * @since 1.0.0
		 *
		 */
		private static function sparkconstructionlite_redirect( $url ) {

			if ( headers_sent() ) {
				echo "<meta http-equiv='refresh' content='0;URL=$url' />";
			} else {
				wp_redirect( $url );
			}
			exit();
		}


        /**
         * Constructor for the Welcome Screen
        */
        public function __construct() {

            /** Useful Variables */
            $theme = wp_get_theme();
            $this->theme_name = $theme->Name;
            $this->theme_version = $theme->Version;

            /** Define Tabs Sections */
            $this->tab_sections = array(
                'getting_started' => 'Getting Started',
                'recommended_plugins' => 'Recommended Plugins',
                'support' => 'Support',
                'free_vs_pro' => 'Free Vs Pro'
            );

            /** List of Recommended Free Plugins **/
            $this->free_plugins = array(
                'elementor' => array(
                    'name' => 'Elementor Page Builder',
                    'slug' => 'elementor',
                    'filename' => 'elementor',
                    'thumb_path' => 'https://ps.w.org/elementor/assets/icon-256x256.gif'
                ),
                'contact-form-7' => array(
                    'name' => 'Contact Form 7',
                    'slug' => 'contact-form-7',
                    'filename' => 'contact-form-7',
                    'thumb_path' => 'https://ps.w.org/contact-form-7/assets/icon.svg'
                ),
                'menu-icons' => array(
                    'name' => 'Menu Icons',
                    'slug' => 'menu-icons',
                    'filename' => 'menu-icons',
                    'thumb_path' => 'https://ps.w.org/menu-icons/assets/icon-128x128.png'
                ),
                'loco-translate' => array(
                    'name' => 'Loco Translate',
                    'slug' => 'loco-translate',
                    'filename' => 'loco-translate',
                    'thumb_path' => 'https://ps.w.org/loco-translate/assets/icon-256x256.png'
                ),
                'hash-form' => array(
                    'name' => 'Hash Form(Drag & Drop)',
                    'slug' => 'hash-form',
                    'filename' => 'hash-form',
                    'thumb_path' => 'https://ps.w.org/hash-form/assets/icon-256x256.gif'
                ),
                'cookie-law-info' => array(
                    'name' => 'CookieYes(GDPR/CCPA)',
                    'slug' => 'cookie-law-info',
                    'filename' => 'cookie-law-info',
                    'thumb_path' => 'https://plugins.svn.wordpress.org/cookie-law-info/assets/icon-256x256.png'
                )
            );
            
            /* Create a Welcome Page */
            add_action('admin_menu', array($this, 'welcome_register_menu'));

            /* Enqueue Styles & Scripts for Welcome Page */
            add_action('admin_enqueue_scripts', array($this, 'welcome_styles_and_scripts'));

            /* Adds Footer Rating Text */
            add_filter('admin_footer_text', array($this, 'admin_footer_text'));

            /* Hide Notice */
            add_filter('wp_loaded', array($this, 'hide_admin_notice'), 10);

            /* Create a Welcome Page */
            add_action('wp_loaded', array($this, 'admin_notice'), 20);

            add_action('after_switch_theme', array($this, 'erase_hide_notice'));

            add_action('wp_ajax_sparkconstructionlite_activate_plugin', array($this, 'activate_plugin'));

			add_action( 'wp_ajax_thim_core_installer', array( $this, 'sparkconstructionlite_ajax_install' ) );
			
			add_action( 'sparkconstructionlite_installer_step_start', array( $this, 'sparkconstructionlite_prepare_installation' ) );
			add_action( 'sparkconstructionlite_installer_step_install', array( $this, 'sparkconstructionlite_step_install' ) );
			add_action( 'sparkconstructionlite_installer_step_activate', array( $this, 'sparkconstructionlite_step_activate' ) );
        }

        /** Trigger Welcome Message Notification */
        public function admin_notice($hook) {
            $hide_notice = get_option('sparkconstructionlite_hide_notice');
            if (!$hide_notice) {
                add_action('admin_notices', array($this, 'admin_notice_content'));
            }
        }

        /** Welcome Message Notification */
        public function admin_notice_content() {
                $screen = get_current_screen();
                if ('appearance_page_sparkconstructionlite-welcome' === $screen->id || (isset($screen->parent_file) && 'plugins.php' === $screen->parent_file && 'update' === $screen->id) || 'theme-install' === $screen->id) {
                    return;
                }
                $slug = $filename = 'elementor';
            ?>
                <div class="updated notice sparkconstructionlite-welcome-notice">
                    <div class="sparkconstructionlite-welcome-notice-wrap">
                        <h2><?php esc_html_e('Congratulations!', 'spark-construction-lite'); ?></h2>
                        <p><?php printf(esc_html__('%1$s is now installed and ready to use. You can start either by importing the ready-made demo or get started by customizing it your self.', 'spark-construction-lite'), $this->theme_name); ?></p>
                        <div class="sparkconstructionlite-welcome-info">
                            <div class="sparkconstructionlite-welcome-thumb">
                                <img src="<?php echo esc_url(get_stylesheet_directory_uri() . '/screenshot.png'); ?>" alt="<?php echo esc_attr__('Spark Construction Lite Demo', 'spark-construction-lite'); ?>">
                            </div>
                            <div class="sparkconstructionlite-welcome-import">
                                <h2><?php esc_html_e('Import Demo', 'spark-construction-lite'); ?></h2>
                                <p><?php esc_html_e('Click below to install and activate the Ikreate Demo Importer Plugin.', 'spark-construction-lite'); ?></p>
                                <p><?php echo $this->sparkconstructionlite_setup_content(); ?></p>
                            </div>
                            <div class="sparkconstructionlite-welcome-getting-started">
                                <h2><?php esc_html_e('Get Started', 'spark-construction-lite'); ?></h2>
                                <p><?php printf(esc_html__('Here you will find all the necessary features, and information about %s theme.', 'spark-construction-lite'), $this->theme_name); ?></p>
                                <p><a href="<?php echo esc_url(admin_url('admin.php?page=sparkconstructionlite-welcome')); ?>" class="button button-primary"><span class="dashicons dashicons-admin-settings"></span> <?php esc_html_e('Go to Setting Page', 'spark-construction-lite'); ?></a></p>
                            </div>
                        </div>
                        <a href="<?php echo wp_nonce_url(add_query_arg('sparkconstructionlite_hide_notice', 1), 'sparkconstructionlite_hide_notice_nonce', '_sparkconstructionlite_notice_nonce'); ?>" class="notice-close"></a>
                    </div>
                </div>
            <?php 
        }

        /** Hide Admin Notice */
        public function hide_admin_notice() {
            if (isset($_GET['sparkconstructionlite_hide_notice']) && isset($_GET['_sparkconstructionlite_notice_nonce']) && current_user_can('manage_options')) {
                if (!wp_verify_nonce(wp_unslash($_GET['_sparkconstructionlite_notice_nonce']), 'sparkconstructionlite_hide_notice_nonce')) {
                    wp_die(esc_html__('Action Failed. Something is Wrong.', 'spark-construction-lite'));
                }
                update_option('sparkconstructionlite_hide_notice', true);
            }
        }

        /** Register Menu for Welcome Page */
        public function welcome_register_menu() {
            add_menu_page( esc_html__('Welcome', 'spark-construction-lite'), sprintf(esc_html__('%s', 'spark-construction-lite'),  'Construction Lite' ), 'manage_options', 'sparkconstructionlite-welcome', array($this, 'welcome_screen'), 'data:image/svg+xml;base64, ', 3);
        }

        /** Welcome Page */
        public function welcome_screen() {
            $tabs = $this->tab_sections; ?>
            <div class="welcome-wrap">
                <div class="welcome-main-content">
                    <?php require_once get_template_directory() . '/inc/welcome/sections/header.php'; ?>
                    <div class="welcome-section-wrapper">
                        <?php $section = isset($_GET['section']) && array_key_exists($_GET['section'], $tabs) ? $_GET['section'] : 'getting_started'; ?>

                        <div class="welcome-section <?php echo esc_attr($section); ?> clearfix">
                            <?php require_once get_template_directory() . '/inc/welcome/sections/' . $section . '.php'; ?>
                        </div>
                    </div>
                </div>

                <div class="welcome-footer-content">
                    <?php require_once get_template_directory() . '/inc/welcome/sections/footer.php'; ?>
                </div>
            </div>
            <?php
        }

        /** Enqueue Necessary Styles and Scripts for the Welcome Page */
        public function welcome_styles_and_scripts($hook) {
            if ('theme-install.php' !== $hook) {
                $importer_params = array(
                    'installing_text' => esc_html__('Installing Demo Importer Plugin', 'spark-construction-lite'),
                    'activating_text' => esc_html__('Activating Demo Importer Plugin', 'spark-construction-lite'),
                    'importer_page' => esc_html__('Go to Demo Importer Page', 'spark-construction-lite'),
                    'importer_url' => admin_url('themes.php?page=elementor'),
                    'error' => esc_html__('Error! Reload the page and try again.', 'spark-construction-lite'),
                );
                wp_enqueue_style('sparkconstructionlite-welcome', get_template_directory_uri() . '/inc/welcome/css/welcome.css', array());
                wp_enqueue_script('sparkconstructionlite-welcome', get_template_directory_uri() . '/inc/welcome/js/welcome.js', array('plugin-install', 'updates'), '', true);
                wp_localize_script('sparkconstructionlite-welcome', 'importer_params', $importer_params);
            }
        }

        /* Check if plugin is installed */
        public function check_plugin_installed_state($slug, $filename) {
            return file_exists(ABSPATH . 'wp-content/plugins/' . $slug . '/' . $filename . '.php') ? true : false;
        }

        /* Check if plugin is activated */
        public function check_plugin_active_state($slug, $filename) {
            return is_plugin_active($slug . '/' . $filename . '.php') ? true : false;
        }

        /** Generate Url for the Plugin Button */
        public function plugin_generate_url($status, $slug, $file_name) {
            switch ($status) {
                case 'install':
                    return wp_nonce_url(add_query_arg(array(
                        'action' => 'install-plugin',
                        'plugin' => esc_attr($slug)
                                    ), network_admin_url('update.php')), 'install-plugin_' . esc_attr($slug));
                    break;

                case 'inactive':
                    return add_query_arg(array(
                        'action' => 'deactivate',
                        'plugin' => rawurlencode(esc_attr($slug) . '/' . esc_attr($file_name) . '.php'),
                        'plugin_status' => 'all',
                        'paged' => '1',
                        '_wpnonce' => wp_create_nonce('deactivate-plugin_' . esc_attr($slug) . '/' . esc_attr($file_name) . '.php'),
                            ), network_admin_url('plugins.php'));
                    break;

                case 'active':
                    return add_query_arg(array(
                        'action' => 'activate',
                        'plugin' => rawurlencode(esc_attr($slug) . '/' . esc_attr($file_name) . '.php'),
                        'plugin_status' => 'all',
                        'paged' => '1',
                        '_wpnonce' => wp_create_nonce('activate-plugin_' . esc_attr($slug) . '/' . esc_attr($file_name) . '.php'),
                            ), network_admin_url('plugins.php'));
                    break;
            }
        }

        /** Ajax Plugin Activation */
        public function activate_plugin() {
            // Security: Verify nonce
            if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['nonce'] ), 'sparkconstructionlite_plugin_activation_nonce' ) ) {
                wp_send_json_error( array( 'message' => esc_html__( 'Security check failed', 'spark-construction-lite' ) ) );
            }

            // Security: Check user capabilities
            if ( ! current_user_can( 'manage_options' ) ) {
                wp_send_json_error( array( 'message' => esc_html__( 'Insufficient permissions', 'spark-construction-lite' ) ) );
            }

            $slug = isset($_POST['slug']) ? sanitize_key($_POST['slug']) : '';
            $file = isset($_POST['file']) ? sanitize_key($_POST['file']) : '';
            $success = false;
            if (!empty($slug) && !empty($file)) {
                //patterns-plugin-activate
                //activate_plugin('patterns-kit/plugins.php');
                $result = activate_plugin($slug . '/' . $file . '.php');
                update_option('sparkconstructionlite_hide_notice', true);
                if (!is_wp_error($result)) {
                    $success = true;
                }
            }
            echo wp_json_encode(array('success' => $success));
            die();
        }

        /** Adds Footer Notes */
        public function admin_footer_text($text) {
            $screen = get_current_screen();
            if ('toplevel_page_sparkconstructionlite-welcome' == $screen->id) {
                $text = sprintf(esc_html__('Please leave us a %s rating if you like our theme . A huge thank you from ikreate themes in advance!', 'spark-construction-lite'), '<a href="https://wordpress.org/support/theme/spark-construction-lite/reviews/?filter=5#new-post" target="_blank">&#9733;&#9733;&#9733;&#9733;&#9733;</a>');
            }
            return $text;
        }

        public function erase_hide_notice() {
            delete_option('sparkconstructionlite_hide_notice');
        }

		private function sparkconstructionlite_get_thim_core() {
			if ( $this->plugin === null ) {
				$plugin = new sparkconstructionlite_Plugin();
				$plugin->set_args( $this->package );
				$this->plugin = $plugin;
			}
			return $this->plugin;
		}

		private function sparkconstructionlite_get_link_step( $step = '' ) {
			return add_query_arg( array( 'step' => $step ) );
		}

		public function sparkconstructionlite_ajax_install() {
            // Verify nonce for security
            if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['nonce'] ), 'sparkconstructionlite_plugin_installation_nonce' ) ) {
                wp_send_json_error( array( 'message' => esc_html__( 'Security check failed', 'spark-construction-lite' ) ) );
            }

            // Check user capabilities
            if ( ! current_user_can( 'manage_options' ) ) {
                wp_send_json_error( array( 'message' => esc_html__( 'Insufficient permissions', 'spark-construction-lite' ) ) );
            }
            
			$plugin = $this->sparkconstructionlite_get_thim_core();

			$result = $plugin->install();

			if ( ! $result ) {
				wp_send_json_error( $plugin->get_messages() );
			}

			wp_send_json_success( $plugin->get_messages() );
		}

		private function sparkconstructionlite_setup_content() {
			
			$thim_core   = $this->sparkconstructionlite_get_thim_core();
			$status      = $thim_core->get_status();
			$step        = isset( $_REQUEST['step'] ) ? $_REQUEST['step'] : 'start';

			do_action( "sparkconstructionlite_installer_step_$step" );
		}

		/**
		 * Prepare installation Thim Core.
		 *
		 * @since 1.0.0
		 */
		public function sparkconstructionlite_prepare_installation() {

			$thim_core = $this->sparkconstructionlite_get_thim_core();

			$status    = $thim_core->get_status();

			$step = ( $status == 'inactive' ) ? 'activate' : 'install';

			$link = $this->sparkconstructionlite_get_link_step( $step );
			
			if ( $status == 'inactive' ) {
				$import_class = 'button button-primary';
				$import_button_text = esc_html__('Activate Demo Importer Plugin', 'spark-construction-lite');
			} elseif ( $status == 'active' ) {
				$import_class = 'button button-primary';
				$import_button_text = esc_html__('Go to Demo Importer Page', 'spark-construction-lite');
				$link =  admin_url( '/themes.php?page=ikreate-demo-importer' );
			} else {
				$import_class = 'thim-button-link button button-primary';
				$import_button_text = esc_html__('Install Demo Importer Plugin', 'spark-construction-lite');	
			}

			?>
				<a class="<?php echo esc_attr( $import_class ); ?>" data-href="<?php echo esc_url( $link ) ?>" href=<?php echo esc_url( $link ) ?>>
					<?php echo esc_attr( $import_button_text ); ?>
				</a>
			<?php

		}

		/**
		 * Step install.
		 *
		 * @since 1.0.0
		 */
		public function sparkconstructionlite_step_install() {

			$link = $this->sparkconstructionlite_get_link_step( 'activate' );

			$plugin = $this->sparkconstructionlite_get_thim_core();

			$status = $plugin->get_status();

			if ( $status != 'not_installed' ) {
				self::sparkconstructionlite_redirect( $link );
			}

			$result = $plugin->install();
			$messages = $plugin->get_messages();
			$notice   = $result ? 'success' : 'error';
			
            ?>
                <a class="button button-primary" data-href="<?php echo esc_url( $link ) ?>" href=<?php echo esc_url( $link ) ?>>
					<?php esc_html_e('Activate Demo Importer Plugin', 'spark-construction-lite') ?>
				</a>
            <?php
			if ( $result ) {
				self::sparkconstructionlite_redirect( $link );
			}
		}

		/**
		 * Step active.
		 *
		 * @since 1.0.0
		 */
		public function sparkconstructionlite_step_activate() {

			$plugin = $this->sparkconstructionlite_get_thim_core();

			if ( $plugin->activate( true ) || $plugin->is_active() ) {

				$this->sparkconstructionlite_redirect_dashboard();

				return;
			}

		}

		/**
		 * Reload to redirect to theme dashboard.
		 *
		 * @since 1.0.0
		 */
		private function sparkconstructionlite_redirect_dashboard() {

			$url = admin_url( 'themes.php?page=ikreate-demo-importer' );

			self::sparkconstructionlite_redirect( $url );
		}

    }
    new sparkconstructionlite_Welcome();
endif;
