<?php
// Exit if accessed directly
if ( ! defined('ABSPATH') ) {
    exit;
}
if ( ! class_exists( 'Wlpr_Import_Export' ) ) {

    class Wlpr_Import_Export {
        /**
         * @var null
         */
        private static $instance = null;
        private static $woo_core_options = array(
            'wlpr_launcher_guest_header_content',
            'wlpr_launcher_guest_signup_heading',
            'wlpr_launcher_guest_signup_content',
            'wlpr_launcher_guest_signup_button_text',
            'wlpr_launcher_guest_signup_button_url',
            'wlpr_launcher_guest_signup_button_color',
            'wlpr_launcher_guest_signup_button_text_color',
            'wlpr_launcher_guest_signup_text_color',
            'wlpr_launcher_guest_signup_signin_prefix_text',
            'wlpr_launcher_guest_signup_signin_link_text',
            'wlpr_launcher_guest_signup_signin_url',
            'wlpr_launcher_guest_signup_background_color',
            'wlpr_launcher_guest_review_heading',
            'wlpr_launcher_guest_review_content',
            'wlpr_launcher_guest_review_img',
            'wlpr_launcher_guest_review_background_color',
            'wlpr_launcher_guest_review_text_color',

            'wlpr_launcher_login_header_content',
            'wlpr_launcher_login_review_heading',
            'wlpr_launcher_login_review_content',
            'wlpr_launcher_login_review_img',
            'wlpr_launcher_login_review_background_color',
            'wlpr_launcher_login_review_text_color',

            'wlpr_launcher_login_referral_heading',
            'wlpr_launcher_login_referral_content',
            'wlpr_launcher_login_referral_img',
            'wlpr_launcher_login_referral_background_color',
            'wlpr_launcher_login_referral_text_color',

            'wlpr_launcher_login_referee_heading',
            'wlpr_launcher_login_referee_content',
            'wlpr_launcher_body_login_referee_content',
            'wlpr_launcher_login_referee_img',
            'wlpr_launcher_login_referee_background_color',
            'wlpr_launcher_login_referee_text_color',

            'wlpr_launcher_header_image',
            'wlpr_launcher_header_background_color',
            'wlpr_launcher_header_text_color',
            'wlpr_launcher_body_background_color'
        ,
            'wlpr_launcher_login_review_ordering',
            'wlpr_launcher_login_referral_ordering',
            'wlpr_launcher_login_referee_ordering',
            'wlpr_launcher_font_family'
        );
        private static $prebuilt_options = array(
            'wlpr_full' => 'a:2:{s:8:"template";s:22:"wlpr-launcher-designer";s:7:"options";a:59:{s:13:"wlpr_launcher";a:3:{s:22:"launcher_load_template";s:9:"wlpr_full";s:10:"custom_css";s:0:"";s:13:"import_export";s:0:"";}s:34:"wlpr_launcher_guest_header_content";s:54:"Welcome to <br> <span class="agent"> My Rewards</span>";s:34:"wlpr_launcher_guest_signup_heading";s:15:"Become a Member";s:34:"wlpr_launcher_guest_signup_content";s:63:"Join our loyalty program to unlock exclusive perks and rewards.";s:38:"wlpr_launcher_guest_signup_button_text";s:8:"Join Now";s:37:"wlpr_launcher_guest_signup_button_url";s:17:"{wlpr_signup_url}";s:39:"wlpr_launcher_guest_signup_button_color";s:7:"#353d9f";s:44:"wlpr_launcher_guest_signup_button_text_color";s:7:"#f9f9f9";s:37:"wlpr_launcher_guest_signup_text_color";s:4:"#444";s:45:"wlpr_launcher_guest_signup_signin_prefix_text";s:24:"Already have an account?";s:43:"wlpr_launcher_guest_signup_signin_link_text";s:7:"Sign in";s:37:"wlpr_launcher_guest_signup_signin_url";s:17:"{wlpr_signin_url}";s:43:"wlpr_launcher_guest_signup_background_color";s:7:"#f9f9f9";s:34:"wlpr_launcher_guest_review_heading";s:14:"Review Product";s:34:"wlpr_launcher_guest_review_content";s:74:"Review and earn <strong>{wlpr_review_points}</strong> {wlpr_points_label}!";s:30:"wlpr_launcher_guest_review_img";s:0:"";s:43:"wlpr_launcher_guest_review_background_color";s:7:"#f9f9f9";s:37:"wlpr_launcher_guest_review_text_color";s:4:"#444";s:34:"wlpr_launcher_login_header_content";s:85:"<span>Your Points</span> <br> <span class="agent">{wlpr_customer_total_points}</span>";s:34:"wlpr_launcher_login_review_heading";s:14:"Review Product";s:34:"wlpr_launcher_login_review_content";s:74:"Review and earn <strong>{wlpr_review_points}</strong> {wlpr_points_label}!";s:30:"wlpr_launcher_login_review_img";s:0:"";s:43:"wlpr_launcher_login_review_background_color";s:7:"#f9f9f9";s:37:"wlpr_launcher_login_review_text_color";s:4:"#444";s:36:"wlpr_launcher_login_review_link_text";s:6:"Review";s:42:"wlpr_launcher_login_review_link_text_color";s:7:"#353d9f";s:36:"wlpr_launcher_login_referral_heading";s:21:"Your Referral Rewards";s:36:"wlpr_launcher_login_referral_content";s:41:"{wlpr_total_referral_point} points earned";s:32:"wlpr_launcher_login_referral_img";s:0:"";s:45:"wlpr_launcher_login_referral_background_color";s:7:"#f9f9f9";s:39:"wlpr_launcher_login_referral_text_color";s:4:"#444";s:35:"wlpr_launcher_login_referee_heading";s:18:"Refer your friends";s:35:"wlpr_launcher_login_referee_content";s:48:"You can earn {wlpr_referral_earn_points} points.";s:40:"wlpr_launcher_body_login_referee_content";s:164:"Share this URL to your friends. Your friends get {wlpr_friend_earn_points} bonus points on their first purchase and you will get {wlpr_referral_earn_points} points.";s:31:"wlpr_launcher_login_referee_img";s:0:"";s:44:"wlpr_launcher_login_referee_background_color";s:7:"#f9f9f9";s:38:"wlpr_launcher_login_referee_text_color";s:4:"#444";s:26:"wlpr_launcher_header_image";s:0:"";s:37:"wlpr_launcher_header_background_color";s:7:"#353d9f";s:31:"wlpr_launcher_header_text_color";s:7:"#f9f9f9";s:35:"wlpr_launcher_body_background_color";s:7:"#f9f9f9";s:35:"wlpr_launcher_login_review_ordering";i:1;s:37:"wlpr_launcher_login_referral_ordering";i:2;s:36:"wlpr_launcher_login_referee_ordering";i:3;s:25:"wlpr_launcher_font_family";s:9:"helvetica";s:13:"launcher_text";s:7:"Rewards";s:17:"launcher_position";s:5:"right";s:38:"wlpr_launcher_guest_signup_card_enable";s:3:"yes";s:38:"wlpr_launcher_guest_review_card_enable";s:3:"yes";s:38:"wlpr_launcher_login_review_card_enable";s:3:"yes";s:40:"wlpr_launcher_login_referral_card_enable";s:3:"yes";s:39:"wlpr_launcher_login_referee_card_enable";s:3:"yes";s:33:"wlpr_launcher_birth_date_ordering";i:2;s:32:"wlpr_launcher_birth_date_heading";s:16:"Birthday Rewards";s:30:"wlpr_launcher_birth_date_label";s:19:"Enter Birthday Date";s:23:"wlpr_launcher_birth_img";s:95:"http://point.test/wp-content/plugins/loyalty-points-rewards/Assets/Images/wlpr_full/sign-up.png";s:36:"wlpr_launcher_birth_date_button_text";s:4:"Save";s:35:"wlpr_launcher_birthday_button_color";s:7:"#353d9f";s:40:"wlpr_launcher_birthday_button_text_color";s:7:"#f9f9f9";}}',

        );
        /**
         * Instance Control
         */
        public static function get_instance() {
            if ( is_null( self::$instance ) ) {
                self::$instance = new self();
            }
            return self::$instance;
        }
        /**
         * Class constructor
         *
         * @access public
         * @return void
         */
        public function __construct() {
            // Only proceed if this is own request
            if ( ! Wlpr_Designer::is_own_customizer_request() && ! Wlpr_Designer::is_own_preview_request() ) {
                return;
            }

            add_action( 'customize_register', array( $this, 'import_export_requests' ), 999999 );
            add_action( 'customize_controls_print_scripts', array( $this, 'controls_print_scripts' ) );

        }

        /**
         * Check to see if we need to do an export or import.
         * @param object $wp_customize An instance of WP_Customize_Manager.
         * @return void
         */
        static public function import_export_requests( $wp_customize ) {
            // Check if user is allowed to change values
            if ( ! Wlpr_Designer::is_admin()) {
                exit;
            }

            if ( isset( $_REQUEST['wlpr-launcher-export'] ) ) {
                self::export_launcher( $wp_customize );
            }

            if ( isset( $_REQUEST['wlpr-launcher-import'] ) && isset( $_FILES['wlpr-launcher-import-file'] ) ) {
                self::import_launcher( $wp_customize );
            }

            if ( isset( $_REQUEST['wlpr-launcher-import-template'] ) ) {
                self::import_launcher_template( $wp_customize );
            }


        }

        /**
         * Export woomail settings.
         *
         * @access private
         * @param object $wp_customize An instance of WP_Customize_Manager.
         * @return void
         */
        static private function export_launcher( $wp_customize )  {
            $input_helper = new \Wlpr\App\Helpers\Input();
            $wp_customize_launcher_export_input = (string)$input_helper->post_get('wlpr-launcher-export','');
            if ( ! wp_verify_nonce( $wp_customize_launcher_export_input, 'wlpr-launcher-exporting' ) ) {
                return;
            }

            $template	= 'wlpr-launcher-designer';
            $charset	= get_option( 'blog_charset' );
            $data		= array(
                'template'  => $template,
                'options'	  => array()
            );

            // Get options from the Customizer API.
            $settings = $wp_customize->settings();

            foreach ( $settings as $key => $setting ) {
                if ( stristr( $key, 'wlpr_launcher' ) || in_array( $key, self::$woo_core_options ) ) {
                    // to prevent issues we don't want to export the order id.
                    if( $key != 'wlpr_launcher[preview_customer]' ) {
                        $data['options'][ $key ] = $setting->value();
                    }
                }
            }


            // Set the download headers.
            header( 'Content-disposition: attachment; filename=wlpr-launcher-designer-export.dat' );
            header( 'Content-Type: application/octet-stream; charset=' . $charset );

            // Serialize the export data.
            echo serialize( $data );

            // Start the download.
            die();
        }
        /**
         * Imports uploaded  settings
         *
         * @access private
         * @param object $wp_customize An instance of WP_Customize_Manager.
         * @return void
         */
        static private function import_launcher( $wp_customize ) {
            // Make sure we have a valid nonce.
            $input_helper = new \Wlpr\App\Helpers\Input();
            $wp_customize_launcher_import_input = (string)$input_helper->post_get('wlpr-launcher-import','');
            if ( ! wp_verify_nonce( $wp_customize_launcher_import_input, 'wlpr-launcher-importing' ) ) {
                return;
            }
            // Make sure WordPress upload support is loaded.
            if ( ! function_exists( 'wp_handle_upload' ) ) {
                require_once( ABSPATH . 'wp-admin/includes/file.php' );
            }

            // Load the export/import option class.
            require_once WLPR_PLUGIN_PATH . 'App/Includes/Launcher/ImportOption.php';

            // Setup global vars.
            global $wp_customize;
            global $wlpr_launcher_import_error;

            // Setup internal vars.
            $wlpr_launcher_import_error	 = false;
            $template	 = 'wlpr-launcher-designer';
            $overrides   = array( 'test_form' => false, 'test_type' => false, 'mimes' => array('dat' => 'text/plain') );
            $file        = wp_handle_upload( $_FILES['wlpr-launcher-import-file'], $overrides );

            // Make sure we have an uploaded file.
            if ( isset( $file['error'] ) ) {
                $wlpr_launcher_import_error = $file['error'];
                return;
            }
            if ( ! file_exists( $file['file'] ) ) {
                $wlpr_launcher_import_error = __( 'Error importing settings! Please try again.', WLPR_TEXT_DOMAIN );
                return;
            }

            // Get the upload data.
            $raw  = file_get_contents( $file['file'] );
            $data = @unserialize( $raw );

            // Remove the uploaded file.
            unlink( $file['file'] );

            // Data checks.
            if ( 'array' != gettype( $data ) ) {
                $wlpr_launcher_import_error = __( 'Error importing settings! Please check that you uploaded a customizer export file.', WLPR_TEXT_DOMAIN );
                return;
            }
            if ( ! isset( $data['template'] ) ) {
                $wlpr_launcher_import_error = __( 'Error importing settings! Please check that you uploaded a customizer export file.', WLPR_TEXT_DOMAIN );
                return;
            }
            if ( $data['template'] != $template ) {
                $wlpr_launcher_import_error = __( 'Error importing settings! The settings you uploaded are not for the Loyalty launcher Designer.', WLPR_TEXT_DOMAIN );
                return;
            }

            // Import custom options.
            if ( isset( $data['options'] ) ) {

                foreach ( $data['options'] as $option_key => $option_value ) {

                    $option = new Wlpr_Launcher_Import_Option( $wp_customize, $option_key, array(
                        'default'		=> '',
                        'type'			=> 'option',
                        'capability'	=> Wlpr_Designer::get_admin_capability(),
                    ) );

                    $option->import( $option_value );
                }
            }


            // Call the customize_save action.
            do_action( 'customize_save', $wp_customize );

            // Call the customize_save_after action.
            do_action( 'customize_save_after', $wp_customize );

            wp_redirect( Wlpr_Customizer::get_customizer_url() );

            exit;
        }

        /**
         * Imports prebuilt
         *
         * @access private
         * @param object $wp_customize An instance of WP_Customize_Manager.
         * @return void
         */
        static private function import_launcher_template( $wp_customize ) {

            // Make sure we have a valid nonce.
            $input_helper = new \Wlpr\App\Helpers\Input();
            $wp_customize_launcher_import_template_input = (string)$input_helper->post_get('wlpr-launcher-import-template','');
            if ( ! wp_verify_nonce( $wp_customize_launcher_import_template_input, 'wlpr-launcher-importing-template' ) ) {
                return;
            }
            // Load the export/import option class.
            require_once WLPR_PLUGIN_PATH . 'App/Includes/Launcher/ImportOption.php';

            // Setup global vars.
            global $wp_customize;
            global $wlpr_launcher_import_error;

            // Setup internal vars.
            $wlpr_launcher_import_error	 = false;
            $template	 = 'wlpr-launcher-designer';
            $input_helper = new \Wlpr\App\Helpers\Input();
            $prebuilt = (string)$input_helper->post_get('wlpr-launcher-prebuilt-template','');
            $raw_data 	= self::prebuilt( $prebuilt );

            $data = @unserialize( $raw_data );
            //self::generate_default_values();
            
            // Data checks.
            if ( 'array' != gettype( $data ) ) {
                $wlpr_launcher_import_error = __( 'Error importing settings! The template you selected is not found.', WLPR_TEXT_DOMAIN );
                return;
            }
            if ( ! isset( $data['template'] ) ) {
                $wlpr_launcher_import_error = __( 'Error importing settings! The template you selected is not valid.', WLPR_TEXT_DOMAIN );
                return;
            }
            if ( $data['template'] != $template ) {
                $wlpr_launcher_import_error = __( 'Error importing settings! The template you selected is not valid.', WLPR_TEXT_DOMAIN );
                return;
            }

            if(!empty($prebuilt)){
                update_option('wlpr_active_template',$prebuilt);
            }

            // Import custom options.
            if ( isset( $data['options'] ) ) {

                foreach ( $data['options'] as $option_key => $option_value ) {

                    $option = new Wlpr_Launcher_Import_Option( $wp_customize, $option_key, array(
                        'default'		=> '',
                        'type'			=> 'option',
                        'capability'	=> Wlpr_Designer::get_admin_capability(),
                    ) );
                    if(in_array($option_key,self::$woo_core_options)){
                        update_option($option_key,$option_value);
                    }
                    $option->import( $option_value );
                }
            }

            // Call the customize_save action.
            do_action( 'customize_save', $wp_customize );

            // Call the customize_save_after action.
            //do_action( 'customize_save_after', $wp_customize );

            wp_redirect( Wlpr_Customizer::get_customizer_url() );

            exit;
        }
        /**
         * Prints error scripts for the control.
         *
         * @since 0.1
         * @return void
         */
        static public function controls_print_scripts() {
            global $wlpr_launcher_import_error;

            if ( $wlpr_launcher_import_error ) {
                echo '<script> alert("' . $wlpr_launcher_import_error . '"); </script>';
            }
        }
        /**
         * Get value for prebuilt
         *
         * @access public
         * @param string $key
         * @return string
         */
        public static function prebuilt( $key ) {
            if ( isset( self::$prebuilt_options[$key] ) ) {
                $data = self::$prebuilt_options[$key];
            } else {
                $data = null;
            }
            // Allow developers to override with there templates
            return apply_filters( 'wlpr_launcher_template_data', $data, $key );
        }

        private static function generate_default_values(){
            $sss = array(
                'template' => 'wlpr-launcher-designer',
                'options' => array(
                    'wlpr_launcher' => array(
                        'launcher_load_template' => 'wlpr_full',
                        'custom_css' => '',
                        'import_export' => '',
                    ),
                    'wlpr_launcher_guest_header_content' => 'Welcome to <br> <span class="agent"> My Rewards</span>',
                    'wlpr_launcher_guest_signup_heading' => 'Become a Member',
                    'wlpr_launcher_guest_signup_content' => 'Join our loyalty program to unlock exclusive perks and rewards.',
                    'wlpr_launcher_guest_signup_button_text' => 'Join Now',
                    'wlpr_launcher_guest_signup_button_url' => '{wlpr_signup_url}',
                    'wlpr_launcher_guest_signup_button_color' => '#353d9f',
                    'wlpr_launcher_guest_signup_button_text_color' => '#f9f9f9',
                    'wlpr_launcher_guest_signup_text_color' => '#444',
                    'wlpr_launcher_guest_signup_signin_prefix_text' => 'Already have an account?',
                    'wlpr_launcher_guest_signup_signin_link_text' => 'Sign in',
                    'wlpr_launcher_guest_signup_signin_url' => '{wlpr_signin_url}',
                    'wlpr_launcher_guest_signup_background_color' => '#f9f9f9',
                    'wlpr_launcher_guest_review_heading' => 'Review Product',
                    'wlpr_launcher_guest_review_content' => 'Review and earn <strong>{wlpr_review_points}</strong> {wlpr_points_label}!',
                    'wlpr_launcher_guest_review_img' => '',
                    'wlpr_launcher_guest_review_background_color' => '#f9f9f9',
                    'wlpr_launcher_guest_review_text_color' => '#444',

                    'wlpr_launcher_login_header_content' => '<span>Your Points</span> <br> <span class="agent">{wlpr_customer_total_points}</span>',
                    'wlpr_launcher_login_review_heading' => 'Review Product',
                    'wlpr_launcher_login_review_content' => 'Review and earn <strong>{wlpr_review_points}</strong> {wlpr_points_label}!',
                    'wlpr_launcher_login_review_img' => '',
                    'wlpr_launcher_login_review_background_color' => '#f9f9f9',
                    'wlpr_launcher_login_review_text_color' => '#444',
                    'wlpr_launcher_login_review_link_text' => 'Review',
                    'wlpr_launcher_login_review_link_text_color' => '#353d9f',

                    'wlpr_launcher_login_referral_heading' => 'Your Referral Rewards',
                    'wlpr_launcher_login_referral_content' => '{wlpr_total_referral_point} points earned',
                    'wlpr_launcher_login_referral_img' => '',
                    'wlpr_launcher_login_referral_background_color' => '#f9f9f9',
                    'wlpr_launcher_login_referral_text_color' => '#444',

                    'wlpr_launcher_login_referee_heading' => 'Refer your friends',
                    'wlpr_launcher_login_referee_content' => 'You can earn {wlpr_referral_earn_points} points.',
                    'wlpr_launcher_body_login_referee_content' => 'Share this URL to your friends. Your friends get {wlpr_friend_earn_points} bonus points on their first purchase and you will get {wlpr_referral_earn_points} points.',

                    'wlpr_launcher_login_referee_img' => '',
                    'wlpr_launcher_login_referee_background_color' => '#f9f9f9',
                    'wlpr_launcher_login_referee_text_color' => '#444',

                    'wlpr_launcher_header_image' => '',
                    'wlpr_launcher_header_background_color' => '#353d9f',
                    'wlpr_launcher_header_text_color' => '#f9f9f9',
                    'wlpr_launcher_body_background_color' => '#f9f9f9',
                    'wlpr_launcher_login_review_ordering' => 1,
                    'wlpr_launcher_login_referral_ordering' => 2,
                    'wlpr_launcher_login_referee_ordering' => 3,
                    'wlpr_launcher_font_family' => 'helvetica',

                    'launcher_text' => 'Rewards',
                    'launcher_position' => 'right',
                    'wlpr_launcher_guest_signup_card_enable' => 'yes',
                    'wlpr_launcher_guest_review_card_enable' => 'yes',
                    'wlpr_launcher_login_review_card_enable' => 'yes',
                    'wlpr_launcher_login_referral_card_enable' => 'yes',
                    'wlpr_launcher_login_referee_card_enable' => 'yes',

                    'wlpr_launcher_birth_date_ordering' => 2,
                    'wlpr_launcher_birth_date_heading' => 'Birthday Rewards',
                    'wlpr_launcher_birth_date_label' => 'Enter Birthday Date',
                    'wlpr_launcher_birth_img' => WLPR_PLUGIN_URL.'Assets/Images/wlpr_full/sign-up.png',
                    'wlpr_launcher_birth_date_button_text' => 'Save',
                    'wlpr_launcher_birthday_button_color' => '#353d9f',
                    'wlpr_launcher_birthday_button_text_color' => '#f9f9f9',
                )
            );
            $data = serialize($sss);
            echo "<pre>";
            print_r($data);
            exit;
        }
    }
    Wlpr_Import_Export::get_instance();
}