<?php
if (!class_exists('constructionarc_Welcome')) :
    class constructionarc_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 constructionarc_Demo_Importer
		 *
		 * @since 1.0.0
		 */
		private $plugin = null;

		/**
		 * Redirect.
		 *
		 * @param $url
		 *
		 * @since 1.0.0
		 *
		 */
		private static function constructionarc_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_constructionarc_activate_plugin', array($this, 'activate_plugin'));

			add_action( 'wp_ajax_thim_core_installer', array( $this, 'constructionarc_ajax_install' ) );
			
			add_action( 'constructionarc_installer_step_start', array( $this, 'constructionarc_prepare_installation' ) );
			add_action( 'constructionarc_installer_step_install', array( $this, 'constructionarc_step_install' ) );
			add_action( 'constructionarc_installer_step_activate', array( $this, 'constructionarc_step_activate' ) );
        }

        /** Trigger Welcome Message Notification */
        public function admin_notice($hook) {
            $hide_notice = get_option('constructionarc_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_constructionarc-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 constructionarc-welcome-notice">
                    <div class="constructionarc-welcome-notice-wrap">
                        <h2><?php esc_html_e('Congratulations!', 'construction-arc'); ?></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.', 'construction-arc'), $this->theme_name); ?></p>
                        <div class="constructionarc-welcome-info">
                            <div class="constructionarc-welcome-thumb">
                                <img src="<?php echo esc_url(get_stylesheet_directory_uri() . '/screenshot.png'); ?>" alt="<?php echo esc_attr__('Construction Arc Demo', 'construction-arc'); ?>">
                            </div>
                            <div class="constructionarc-welcome-import">
                                <h2><?php esc_html_e('Import Demo', 'construction-arc'); ?></h2>
                                <p><?php esc_html_e('Click below to install and activate the Ikreate Demo Importer Plugin.', 'construction-arc'); ?></p>
                                <p><?php echo $this->constructionarc_setup_content(); ?></p>
                            </div>
                            <div class="constructionarc-welcome-getting-started">
                                <h2><?php esc_html_e('Get Started', 'construction-arc'); ?></h2>
                                <p><?php printf(esc_html__('Here you will find all the necessary features, and information about %s theme.', 'construction-arc'), $this->theme_name); ?></p>
                                <p><a href="<?php echo esc_url(admin_url('admin.php?page=constructionarc-welcome')); ?>" class="button button-primary"><span class="dashicons dashicons-admin-settings"></span> <?php esc_html_e('Go to Setting Page', 'construction-arc'); ?></a></p>
                            </div>
                        </div>
                        <a href="<?php echo wp_nonce_url(add_query_arg('constructionarc_hide_notice', 1), 'constructionarc_hide_notice_nonce', '_constructionarc_notice_nonce'); ?>" class="notice-close"></a>
                    </div>
                </div>
            <?php 
        }

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

        /** Register Menu for Welcome Page */
        public function welcome_register_menu() {
            add_menu_page( esc_html__('Welcome', 'construction-arc'), sprintf(esc_html__('%s', 'construction-arc'),  'Construction Arc' ), 'manage_options', 'constructionarc-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', 'construction-arc'),
                    'activating_text' => esc_html__('Activating Demo Importer Plugin', 'construction-arc'),
                    'importer_page' => esc_html__('Go to Demo Importer Page', 'construction-arc'),
                    'importer_url' => admin_url('themes.php?page=elementor'),
                    'error' => esc_html__('Error! Reload the page and try again.', 'construction-arc'),
                );
                wp_enqueue_style('constructionarc-welcome', get_template_directory_uri() . '/inc/welcome/css/welcome.css', array());
                wp_enqueue_script('constructionarc-welcome', get_template_directory_uri() . '/inc/welcome/js/welcome.js', array('plugin-install', 'updates'), '', true);
                wp_localize_script('constructionarc-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'] ), 'constructionarc_plugin_activation_nonce' ) ) {
                wp_send_json_error( array( 'message' => esc_html__( 'Security check failed', 'construction-arc' ) ) );
            }

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

            $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('constructionarc_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_constructionarc-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!', 'construction-arc'), '<a href="https://wordpress.org/support/theme/construction-arc/reviews/?filter=5#new-post" target="_blank">&#9733;&#9733;&#9733;&#9733;&#9733;</a>');
            }
            return $text;
        }

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

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

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

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

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

			$result = $plugin->install();

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

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

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

			do_action( "constructionarc_installer_step_$step" );
		}

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

			$thim_core = $this->constructionarc_get_thim_core();

			$status    = $thim_core->get_status();

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

			$link = $this->constructionarc_get_link_step( $step );
			
			if ( $status == 'inactive' ) {
				$import_class = 'button button-primary';
				$import_button_text = esc_html__('Activate Demo Importer Plugin', 'construction-arc');
			} elseif ( $status == 'active' ) {
				$import_class = 'button button-primary';
				$import_button_text = esc_html__('Go to Demo Importer Page', 'construction-arc');
				$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', 'construction-arc');	
			}

			?>
				<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 constructionarc_step_install() {

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

			$plugin = $this->constructionarc_get_thim_core();

			$status = $plugin->get_status();

			if ( $status != 'not_installed' ) {
				self::constructionarc_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', 'construction-arc') ?>
				</a>
            <?php
			if ( $result ) {
				self::constructionarc_redirect( $link );
			}
		}

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

			$plugin = $this->constructionarc_get_thim_core();

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

				$this->constructionarc_redirect_dashboard();

				return;
			}

		}

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

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

			self::constructionarc_redirect( $url );
		}

    }
    new constructionarc_Welcome();
endif;
