<?php
if ( !defined( 'ABSPATH' ) ) {
    die( 'No direct access allowed' );
}

require get_template_directory() . '/functions/importer/layered-popups-import.php';

if ( !class_exists( 'Leap_Demo_Import' ) ) {

    class Leap_Demo_Import {

        public $error = '';

        /** ---------------------------------------------------------------------------
         * Constructor
         * ---------------------------------------------------------------------------- */
        function __construct() {
            require_once ABSPATH . 'wp-admin/includes/file.php';
            WP_Filesystem();
            add_action( 'admin_menu', array( $this, 'init' ), 20 );
        }

        /** ---------------------------------------------------------------------------
         * Add theme Page
         * ---------------------------------------------------------------------------- */
        function init() {

            add_theme_page(
            'Import Demo Data', 'Import Demo Data', 'edit_theme_options', 'leap_import_demo_data', array( $this, 'import' )
            );
        }

        /** ---------------------------------------------------------------------------
         * Import
         * ---------------------------------------------------------------------------- */
        function import() {
            global $wpdb;

            if ( key_exists( 'leap_import_nonce', $_POST ) ) {
                if ( wp_verify_nonce( $_POST[ 'leap_import_nonce' ], basename( __FILE__ ) ) ) {

// 				print_r($_POST);
// Importer classes
                    if ( !defined( 'WP_LOAD_IMPORTERS' ) )
                        define( 'WP_LOAD_IMPORTERS', true );

                    if ( !class_exists( 'WP_Importer' ) ) {
                        require_once ABSPATH . 'wp-admin/includes/class-wp-importer.php';
                    }

                    if ( !class_exists( 'WP_Import' ) ) {
                        require_once dirname( __FILE__ ) . '/wordpress-importer.php';
                    }

                    if ( class_exists( 'WP_Importer' ) && class_exists( 'WP_Import' ) ) {

                        if ( !empty( $_POST[ 'demo' ] ) ) {
                            $_POST[ 'demo' ] = htmlspecialchars( stripslashes( $_POST[ 'demo' ] ) );

                            if ( key_exists( 'content', $_POST ) && $_POST[ 'content' ] ) {
                                $content_file = $_POST[ 'demo' ] . '/content.xml';
                                $this->import_content( $content_file );

                                $menu_file = $_POST[ 'demo' ] . '/menu.txt';
                                $this->import_menu_location( $menu_file );
                            }

                            if ( key_exists( 'options', $_POST ) && $_POST[ 'options' ] ) {
                                $options_file = $_POST[ 'demo' ] . '/options.txt';
                                $this->import_options( $options_file );
                            }

                            if ( key_exists( 'widgets', $_POST ) && $_POST[ 'widgets' ] ) {
                                $widgets_file = $_POST[ 'demo' ] . '/widgets.json';
                                $this->import_widget( $widgets_file );
                            }

                            if ( key_exists( 'sliders', $_POST ) && $_POST[ 'sliders' ] ) {
                                if ( class_exists( 'RevSlider' ) ) {
                                    $sliders_path  = dirname( __FILE__ ) . '/demo/' . $_POST[ 'demo' ] . '/sliders/';
                                    $sliders_array = glob( $sliders_path . '*.zip' );
                                    if ( !empty( $sliders_array ) ) {
                                        $this->import_rev_sliders( $sliders_array );
                                    }
                                }
                            }

                            if ( key_exists( 'popups', $_POST ) && $_POST[ 'popups' ] ) {
                                if ( class_exists( 'ulp_admin_class' ) ) {
                                    $popups_path  = dirname( __FILE__ ) . '/demo/' . $_POST[ 'demo' ] . '/popups/';
                                    $popups_array = glob( $popups_path . '*.zip' );
                                    if ( !empty( $popups_array ) ) {
                                        $this->import_popups( $popups_array );
                                    }
                                }
                            }

                            if ( key_exists( 'ess_grid', $_POST ) && $_POST[ 'ess_grid' ] ) {
                                if ( class_exists( 'Essential_Grid_Import' ) ) {
                                    $ess_grid_path   = dirname( __FILE__ ) . '/demo/' . $_POST[ 'demo' ] . '/essential-grid/';
                                    $ess_grids_array = glob( $ess_grid_path . '*.json' );
                                    if ( !empty( $ess_grids_array ) ) {
                                        $this->import_ess_grids( $ess_grids_array );
                                    }
                                }
                            }

                            // set home & blog page
                            $home = get_page_by_title( 'Home' );
                            $blog = get_page_by_title( 'Blog' );
                            if ( !empty( $home->ID ) && !empty( $blog->ID ) ) {
                                update_option( 'show_on_front', 'page' );
                                update_option( 'page_on_front', $home->ID ); // Front Page
                                update_option( 'page_for_posts', $blog->ID ); // Blog Page
                            }  
                        } else {
                            // Empty select.import
                            $this->error = __( 'Please select data to import.', 'wiz' );
                        }

                        // message box
                        if ( $this->error ) {
                            echo '<div class="error settings-error">';
                            echo '<p><strong>' . $this->error . '</strong></p>';
                            echo '</div>';
                        } else {
                            echo '<div class="updated settings-error">';
                            echo '<p><strong>' . __( 'All done. Have fun!', 'wiz' ) . '</strong></p>';
                            echo '</div>';
                        }
                    }
                }
            }
            ?>
            <div id="mfn-wrapper" class="mfn-import wrap">

                <h2><?php echo esc_html( get_admin_page_title() ); ?></h2>

                <p><strong>To properly import Wiz demo data please follow the following steps:</strong></p>
                <ul>
                    <li>- Check what plugins are used for the demo you want to import. <a href="<?php echo esc_url( 'http://www.leap13.com/2015/08/26/installing-included-plugins/#required-plugins' ); ?>" target="_blank">click here to check</a>.</li>
                    <li>- Go to Appearance > <u>Install Plugins</u> to Install the plugins required for the demo you will import.</li>
                    <li>- Choose the demo from the dropdown menu below.</li>
                    <li>- All demo data are selected by default, If you don't want to import specific items please uncheck them.</li>
                    <li>- Click on <u>Import Demo Data</u></li>
                </ul>

                <p><strong>Kindly Note:</strong></p>
                <ul>
                    <li>- Some plugins data cannot be imported automatically like Easy Social Share,  So you will need to import manually <a href="<?php echo esc_url( 'http://www.leap13.com/2015/08/25/importing-a-wiz-demo/' ); ?>" target="_blank">click here</a> for more info.</li>
                </ul>

                <form action="" method="post" onsubmit="return confirm( 'Do you really want to submit the form?' );">

                    <input type="hidden" name="leap_import_nonce" value="<?php echo wp_create_nonce( basename( __FILE__ ) ); ?>" />

                    <table class="form-table">

                        <tr>
                            <th scope="row">
                                <label for="demo">Demo</label>
                            </th>
                            <td>
                                <select id="demo" name="demo">
                                    <option value="">Select Demo</option>
                                    <option value="accounting">Accounting</option>
                                    <option value="advertising">Advertising</option>
                                    <option value="bakery">Bakery</option>
                                    <option value="business">Business</option>
                                    <option value="cafe">Cafe</option>
                                    <option value="charity">Charity</option>
                                    <option value="clinic">Clinic</option>
                                    <option value="corporate">Corporate</option>
                                    <option value="firm">Firm</option>
                                    <option value="freelancer">Freelancer</option>
                                    <option value="landing">Landing</option>
                                    <option value="meditation">Meditation</option>
                                    <option value="nutritional">Nutritional</option>
                                    <option value="photographer">Photographer</option>
                                    <option value="restaurant">Restaurant</option>
                                    <option value="sauce">Sauce</option>
                                    <option value="shop">Shop</option>
                                    <option value="spa">Spa</option>
                                    <option value="sports">Sports</option>
                                    <option value="startup">Start Up</option>
                                    <option value="travel">Travel</option>
                                    <option value="waiting">Waiting</option>
                                </select>
                            </td>
                        </tr>

                        <tr>
                            <th scope="row">Content</th>
                            <td>
                                <fieldset>
                                    <label for="content"><input class="demo-import-item" type="checkbox" value="1" id="content" name="content">Import Content</label>
                                    <p class="description">This will contain all of your posts, pages, comments, custom fields, terms, navigation menus and custom posts.</p>
                                </fieldset>
                            </td>
                        </tr>

                        <tr>
                            <th scope="row">Attachments</th>
                            <td>
                                <fieldset>
                                    <label for="attachments"><input class="demo-import-item" type="checkbox" value="1" id="attachments" name="attachments">Import Media</label>
                                    <p class="description">Download all attachments from the demo may take a while. Please be patient.</p>
                                </fieldset>
                            </td>
                        </tr>

                        <tr>
                            <th scope="row">Theme Options</th>
                            <td>
                                <fieldset>
                                    <label for="options"><input class="demo-import-item" type="checkbox" value="1" id="options" name="options">Import Theme Options</label>
                                </fieldset>
                            </td>
                        </tr>

                        <tr>
                            <th scope="row">Widgets</th>
                            <td>
                                <fieldset>
                                    <label for="widgets"><input class="demo-import-item" type="checkbox" value="1" id="widgets" name="widgets">Import Widgets</label>
                                </fieldset>
                            </td>
                        </tr>

                        <tr>
                            <th scope="row">Sliders</th>
                            <td>
                                <fieldset>
                                    <label for="sliders"><input class="demo-import-item" type="checkbox" value="1" id="sliders" name="sliders">Import sliders</label>
                                </fieldset>
                            </td>
                        </tr>

                        <tr>
                            <th scope="row">Essential Grids</th>
                            <td>
                                <fieldset>
                                    <label for="ess_grid"><input class="demo-import-item" type="checkbox" value="1" id="ess_grid" name="ess_grid">Import Essential Grids</label>
                                </fieldset>
                            </td>
                        </tr>

                        <tr>
                            <th scope="row">Layered Popups</th>
                            <td>
                                <fieldset>
                                    <label for="popups"><input class="demo-import-item" type="checkbox" value="1" id="popups" name="popups">Import Layered Popups</label>
                                </fieldset>
                            </td>
                        </tr>

                    </table>

                    <input type="submit" name="submit" class="button button-primary" value="Import demo data" />

                </form>

                <script>
                    jQuery( "#demo" ).change( function () {
                        var demo = this.value;
                        if ( demo !== '' ) {
                            jQuery( '.demo-import-item' ).prop( 'checked', true );
                        } else {
                            jQuery( '.demo-import-item' ).prop( 'checked', false );
                        }
                    } );
                </script>

            </div>	
            <?php
        }

        /** ---------------------------------------------------------------------------
         * Import | Content
         * ---------------------------------------------------------------------------- */
        function import_content( $file = '' ) {
            $import = new WP_Import();
            $xml    = dirname( __FILE__ ) . '/demo/' . $file;
// 		print_r($xml);

            $import->fetch_attachments = ( $_POST && key_exists( 'attachments', $_POST ) && $_POST[ 'attachments' ] ) ? true : false;

            ob_start();
            $import->import( $xml );
            ob_end_clean();
        }

        /** ---------------------------------------------------------------------------
         * Import | Menu - Locations 
         * ---------------------------------------------------------------------------- */
        function import_menu_location( $file = '' ) {
            global $wp_filesystem;

            $file_data = $wp_filesystem->get_contents( get_template_directory() . '/functions/importer/demo/' . $file );
            $data      = @unserialize( call_user_func( 'base'.'64_decode', $file_data ) );
            $menus     = wp_get_nav_menus();

            foreach ( $data as $key => $val ) {
                foreach ( $menus as $menu ) {
                    if ( $val && $menu->name == $val ) {
                        $data[ $key ] = absint( $menu->term_id );
                    }
                }
            }
            //print_r($data);
            set_theme_mod( 'nav_menu_locations', $data );
        }

        /** ---------------------------------------------------------------------------
         * Import | Theme Options
         * ---------------------------------------------------------------------------- */
        function import_options( $file = 'options.txt' ) {
            global $wp_filesystem;

            $file_data = $wp_filesystem->get_contents( get_template_directory() . '/functions/importer/demo/' . $file );
            $data      = @unserialize( call_user_func( 'base'.'64_decode', $file_data ) );

            update_option( ot_options_id(), $data );

            // Fetch Google fonts
            ob_start();
            ot_fetch_google_fonts();
            $google_fonts = ot_get_option( 'google_fonts', array() );
            ot_set_google_fonts( 'google_fonts', $google_fonts );
            ob_end_clean();
        }

        /** ---------------------------------------------------------------------------
         * Import | Widgets
         * ---------------------------------------------------------------------------- */
        function import_widget( $file = 'widget_data.json' ) {
            global $wp_filesystem;

            $data = $wp_filesystem->get_contents( get_template_directory() . '/functions/importer/demo/' . $file );

            ob_start();
            $this->import_widget_data( $data );
            ob_end_clean();
        }

        /** ---------------------------------------------------------------------------
         * Parse JSON import file
         * http://wordpress.org/plugins/widget-settings-importexport/
         * ---------------------------------------------------------------------------- */
        function import_widget_data( $json_data ) {

            $json_data    = json_decode( $json_data, true );
            $sidebar_data = (array) $json_data[ 0 ];
            $widget_data  = (array) $json_data[ 1 ];
// 		print_r($json_data);
// prepare widgets table
            $widgets      = array();
            foreach ( $widget_data as $k_w => $widget_type ) {
                if ( $k_w ) {
                    $widgets[ $k_w ] = array();
                    foreach ( $widget_type as $k_wt => $widget ) {
                        if ( is_int( $k_wt ) )
                            $widgets[ $k_w ][ $k_wt ] = 1;
                    }
                }
            }
// 		print_r($widgets);
// sidebars
            foreach ( $sidebar_data as $title => $sidebar ) {
                $count = count( $sidebar );
                for ( $i = 0; $i < $count; $i++ ) {
                    $widget                 = array();
                    $widget[ 'type' ]       = trim( substr( $sidebar[ $i ], 0, strrpos( $sidebar[ $i ], '-' ) ) );
                    $widget[ 'type-index' ] = trim( substr( $sidebar[ $i ], strrpos( $sidebar[ $i ], '-' ) + 1 ) );
                    if ( !isset( $widgets[ $widget[ 'type' ] ][ $widget[ 'type-index' ] ] ) ) {
                        unset( $sidebar_data[ $title ][ $i ] );
                    }
                }
                $sidebar_data[ $title ] = array_values( $sidebar_data[ $title ] );
            }

// widgets
            foreach ( $widgets as $widget_title => $widget_value ) {
                foreach ( $widget_value as $widget_key => $widget_value ) {
                    $widgets[ $widget_title ][ $widget_key ] = $widget_data[ $widget_title ][ $widget_key ];
                }
            }
// 		print_r($sidebar_data);

            $sidebar_data = array( array_filter( $sidebar_data ), $widgets );
            $this->parse_import_data( $sidebar_data );
        }

        /** ---------------------------------------------------------------------------
         * Import widgets
         * http://wordpress.org/plugins/widget-settings-importexport/
         * ---------------------------------------------------------------------------- */
        function parse_import_data( $import_array ) {
            $sidebars_data = (array) $import_array[ 0 ];
            $widget_data   = (array) $import_array[ 1 ];

//mfn_register_sidebars(); // fix for sidebars added in Theme Options
            $current_sidebars = get_option( 'sidebars_widgets' );
            $new_widgets      = array();

// 		print_r($sidebars_data);
// 		print_r($current_sidebars);

            foreach ( $sidebars_data as $import_sidebar => $import_widgets ) :

                foreach ( $import_widgets as $import_widget ) :

// if NOT the sidebar exists
                    if ( !isset( $current_sidebars[ $import_sidebar ] ) ) {
                        $current_sidebars[ $import_sidebar ] = array();
                    }

                    $title               = trim( substr( $import_widget, 0, strrpos( $import_widget, '-' ) ) );
                    $index               = trim( substr( $import_widget, strrpos( $import_widget, '-' ) + 1 ) );
                    $current_widget_data = get_option( 'widget_' . $title );
                    $new_widget_name     = $this->get_new_widget_name( $title, $index );
                    $new_index           = trim( substr( $new_widget_name, strrpos( $new_widget_name, '-' ) + 1 ) );

                    if ( !empty( $new_widgets[ $title ] ) && is_array( $new_widgets[ $title ] ) ) {
                        while ( array_key_exists( $new_index, $new_widgets[ $title ] ) ) {
                            $new_index++;
                        }
                    }
                    $current_sidebars[ $import_sidebar ][] = $title . '-' . $new_index;
                    if ( array_key_exists( $title, $new_widgets ) ) {
                        $new_widgets[ $title ][ $new_index ] = $widget_data[ $title ][ $index ];

// notice fix
                        if ( !key_exists( '_multiwidget', $new_widgets[ $title ] ) )
                            $new_widgets[ $title ][ '_multiwidget' ] = '';

                        $multiwidget                             = $new_widgets[ $title ][ '_multiwidget' ];
                        unset( $new_widgets[ $title ][ '_multiwidget' ] );
                        $new_widgets[ $title ][ '_multiwidget' ] = $multiwidget;
                    } else {
                        $current_widget_data[ $new_index ] = $widget_data[ $title ][ $index ];

// notice fix
                        if ( !key_exists( '_multiwidget', $current_widget_data ) )
                            $current_widget_data[ '_multiwidget' ] = '';

                        $current_multiwidget                   = $current_widget_data[ '_multiwidget' ];
                        $new_multiwidget                       = isset( $widget_data[ $title ][ '_multiwidget' ] ) ? $widget_data[ $title ][ '_multiwidget' ] : false;
                        $multiwidget                           = ($current_multiwidget != $new_multiwidget) ? $current_multiwidget : 1;
                        unset( $current_widget_data[ '_multiwidget' ] );
                        $current_widget_data[ '_multiwidget' ] = $multiwidget;
                        $new_widgets[ $title ]                 = $current_widget_data;
                    }

                endforeach;
            endforeach;

            if ( isset( $new_widgets ) && isset( $current_sidebars ) ) {
                update_option( 'sidebars_widgets', $current_sidebars );

                foreach ( $new_widgets as $title => $content )
                    update_option( 'widget_' . $title, $content );

                return true;
            }

            return false;
        }

        /** ---------------------------------------------------------------------------
         * Get new widget name
         * http://wordpress.org/plugins/widget-settings-importexport/
         * ---------------------------------------------------------------------------- */
        function get_new_widget_name( $widget_name, $widget_index ) {
            $current_sidebars = get_option( 'sidebars_widgets' );
            $all_widget_array = array();
            foreach ( $current_sidebars as $sidebar => $widgets ) {
                if ( !empty( $widgets ) && is_array( $widgets ) && $sidebar != 'wp_inactive_widgets' ) {
                    foreach ( $widgets as $widget ) {
                        $all_widget_array[] = $widget;
                    }
                }
            }
            while ( in_array( $widget_name . '-' . $widget_index, $all_widget_array ) ) {
                $widget_index++;
            }
            $new_widget_name = $widget_name . '-' . $widget_index;
            return $new_widget_name;
        }

        function import_rev_sliders( $sliders_array = array() ) {
            $slider = new RevSlider();
            foreach ( $sliders_array as $file_path ) {
                ob_start();
                $slider->importSliderFromPost( true, true, $file_path );
                ob_end_clean();
            }
        }

        function import_popups( $popups_array = array() ) {
            $ulp = new leap_ulp_class();
            foreach ( $popups_array as $file_path ) {
                ob_start();
                $ulp->import_zip( $file_path );
                ob_end_clean();
            }
        }

        function import_ess_grids( $ess_grids_array = array() ) {
            $im = new Essential_Grid_Import();
            foreach ( $ess_grids_array as $ess_grid ) {
                global $wp_filesystem;
                $grids = $wp_filesystem->get_contents( $ess_grid );
                $grids = json_decode( $grids, true );
                ob_start();
                $im->import_grids( $grids[ 'grids' ] );
                ob_end_clean();
            }
        }

    }

}

function leap_import_demo_data() {
    if ( is_admin() ) {
        $leap_demo_import = new Leap_Demo_Import();
    }
}

add_action( 'after_setup_theme', 'leap_import_demo_data', 2 );
