<?php

function st_update_admin_menu()
{
    add_submenu_page( apply_filters('ot_theme_options_menu_slug','st_traveler_options'), "Update taxonomy", 'Update taxonomy', 'manage_options', 'update_taxonomy', 'st_control_update');
}
add_action('admin_menu','st_update_admin_menu',50);

function st_control_update(){
    echo '<div class="wrap"><div id="icon-tools" class="icon32"></div>';
    echo '<h2>Update Taxonomy and Icons</h2><br><br>';


    echo '<div><a href="admin.php?page=update_taxonomy&add_before=true" class="button button-primary" >1 . Add Taxonomy before import XML </a></div><br>';
    echo '<div><a href="admin.php?page=update_taxonomy&add_after=true" class="button button-primary" >2 . Add Icons after import XML </a></div><br>';
    echo '<div><a href="admin.php?page=update_taxonomy&add_widget=true" class="button button-primary" >3 . Update Widget</a></div><br>';
    echo '<div><a href="admin.php?page=update_taxonomy&add_option_tree=true" class="button button-primary" >4 . Update OptionTree</a></div><br>';

    if(!empty($_REQUEST['add_before']) and $_REQUEST['add_before'] == 'true'){
        st_update_taxonomy();
    }
    if(!empty($_REQUEST['add_after']) and $_REQUEST['add_after'] == 'true'){
        st_update_icon_import();
    }

    if(!empty($_REQUEST['add_widget']) and $_REQUEST['add_widget'] == 'true'){
        st_update_widget();
    }

    if(!empty($_REQUEST['add_option_tree']) and $_REQUEST['add_option_tree'] == 'true'){
        st_update_option_tree();
    }


}
function st_update_option_tree(){
    $data = '
 ';
    $options=unserialize(ot_decode($data));
    update_option( ot_options_id(), $options );
    _e('Update OptionTree -> OK',STP_TEXTDOMAIN);
}
function st_update_taxonomy(){
    $attr = 'a:8:{s:16:"hotel_facilities";a:3:{s:4:"name";s:16:"Hotel Facilities";s:9:"post_type";a:1:{i:0;s:8:"st_hotel";}s:12:"hierarchical";i:1;}s:15:"room_facilities";a:3:{s:4:"name";s:15:"Room facilities";s:9:"post_type";a:1:{i:0;s:10:"hotel_room";}s:12:"hierarchical";i:1;}s:12:"car_features";a:3:{s:4:"name";s:12:"Car Features";s:9:"post_type";a:1:{i:0;s:7:"st_cars";}s:12:"hierarchical";i:1;}s:17:"default_equipment";a:3:{s:4:"name";s:17:"Default Equipment";s:9:"post_type";a:1:{i:0;s:7:"st_cars";}s:12:"hierarchical";i:1;}s:11:"hotel_theme";a:3:{s:4:"name";s:11:"Hotel Theme";s:9:"post_type";a:1:{i:0;s:8:"st_hotel";}s:12:"hierarchical";i:1;}s:9:"amenities";a:3:{s:4:"name";s:9:"Amenities";s:9:"post_type";a:1:{i:0;s:9:"st_rental";}s:12:"hierarchical";i:1;}s:11:"suitability";a:3:{s:4:"name";s:11:"Suitability";s:9:"post_type";a:1:{i:0;s:9:"st_rental";}s:12:"hierarchical";i:1;}s:11:"attractions";a:3:{s:4:"name";s:11:"Attractions";s:9:"post_type";a:1:{i:0;s:11:"st_activity";}s:12:"hierarchical";i:1;}}';
    $attr = unserialize($attr);
    update_option( 'st_attribute_taxonomy', $attr );
    _e('Add Taxonomy before import XML -> OK',STP_TEXTDOMAIN);
}
function st_update_widget(){
    $data_widget = '{"blog-sidebar":{"search-2":{"title":""},"categories-2":{"title":"Categories","count":0,"hierarchical":0,"dropdown":0},"st_widget_list_post-2":{"title":"Popular Posts","number":5,"show_date":true,"orderby":"views_count","order":"DESC"},"recent-comments-2":{"title":"Recent Comments","number":5},"sttwitterwidget-2":{"user_id":"evanto","title":"Twitter Feed","number_tweet":"5"},"st_widget_list_gallery-2":{"title":"Gallery","number":9}},"page-sidebar":{"st_nav_menu-2":{"nav_menu":56,"title":false}},"hotel-sidebar":{"st_widget_search_hotel-2":{"title":"Filter By:","show_attribute":"","st_search_fields":"[{\"order\":\"0\",\"title\":\"Price\",\"field\":\"price\",\"taxonomy\":\"hotel_facilities\"},{\"order\":\"1\",\"title\":\"Star Rating\",\"field\":\"hotel_rate\",\"taxonomy\":\"hotel_facilities\"},{\"order\":\"2\",\"title\":\"Review Score\",\"field\":\"rate\",\"taxonomy\":\"hotel_facilities\"},{\"order\":\"3\",\"title\":\"Hotel Theme\",\"field\":\"taxonomy\",\"taxonomy\":\"hotel_facilities\"}]","style":"dark"}},"hotel-sidebar-2":{"st_widget_search_hotel-3":{"title":"Filter By:","show_attribute":"","st_search_fields":"[{\"order\":\"0\",\"title\":\"Price\",\"field\":\"price\",\"taxonomy\":\"hotel_facilities\"},{\"order\":\"0\",\"title\":\"Star Review\",\"field\":\"rate\",\"taxonomy\":\"hotel_facilities\"},{\"order\":\"0\",\"title\":\"Facility\",\"field\":\"taxonomy\",\"taxonomy\":\"hotel_facilities\"},{\"order\":\"0\",\"title\":\"Hotel Theme\",\"field\":\"taxonomy\",\"taxonomy\":\"hotel_theme\"}]","style":"light"}},"cars-sidebar":{"st_widget_search_cars-2":{"title":"Filter By:","show_attribute":"","st_search_fields":"[{\"order\":\"0\",\"title\":\"Car Feature\",\"field\":\"taxonomy\",\"taxonomy\":\"car_features\"},{\"order\":\"0\",\"title\":\"Price\",\"field\":\"price\",\"taxonomy\":\"car_features\"},{\"order\":\"0\",\"title\":\"Default Equipment\",\"field\":\"taxonomy\",\"taxonomy\":\"default_equipment\"},{\"order\":\"0\",\"title\":\"Category Car\",\"field\":\"taxonomy\",\"taxonomy\":\"st_category_cars\"},{\"order\":\"0\",\"title\":\"Pickup Features\",\"field\":\"taxonomy\",\"taxonomy\":\"st_cars_pickup_features\"}]","st_style":"dark"}},"cars-sidebar-2":{"st_widget_search_cars-3":{"title":"Filter By:","show_attribute":"","st_search_fields":"[{\"order\":\"0\",\"title\":\"Car Feature\",\"field\":\"taxonomy\",\"taxonomy\":\"car_features\"},{\"order\":\"0\",\"title\":\"Price\",\"field\":\"price\",\"taxonomy\":\"car_features\"},{\"order\":\"0\",\"title\":\"Default Equipment\",\"field\":\"taxonomy\",\"taxonomy\":\"default_equipment\"},{\"order\":\"0\",\"title\":\"Category Car\",\"field\":\"taxonomy\",\"taxonomy\":\"st_category_cars\"},{\"order\":\"0\",\"title\":\"Pickup Features\",\"field\":\"taxonomy\",\"taxonomy\":\"st_cars_pickup_features\"}]","st_style":"light"}},"rental-sidebar":{"st_widget_search_rental-2":{"title":"Filter By:","show_attribute":"","st_search_fields":"[{\"order\":\"0\",\"title\":\"\",\"field\":\"price\",\"taxonomy\":\"amenities\"},{\"order\":\"1\",\"title\":\"Score Rating\",\"field\":\"rate\",\"taxonomy\":\"amenities\"},{\"order\":\"2\",\"title\":\"Suitability\",\"field\":\"taxonomy\",\"taxonomy\":\"suitability\"},{\"order\":\"3\",\"title\":\"Amenities\",\"field\":\"taxonomy\",\"taxonomy\":\"amenities\"}]","style":"dark"}},"rental-sidebar-2":{"st_widget_search_rental-3":{"title":"Filter By:","show_attribute":"","st_search_fields":"[{\"order\":\"0\",\"title\":\"Price:\",\"field\":\"price\",\"taxonomy\":\"amenities\"},{\"order\":\"1\",\"title\":\"Score Rating\",\"field\":\"rate\",\"taxonomy\":\"amenities\"},{\"order\":\"2\",\"title\":\"Amenities\",\"field\":\"taxonomy\",\"taxonomy\":\"amenities\"},{\"order\":\"3\",\"title\":\"Suitability\",\"field\":\"taxonomy\",\"taxonomy\":\"suitability\"}]","style":"light"}},"activity-sidebar":{"st_widget_search_activity-2":{"title":"Filter By:","show_attribute":"","st_search_fields":"[{\"order\":\"0\",\"title\":\"Price\",\"field\":\"price\",\"taxonomy\":\"attractions\"},{\"order\":\"1\",\"title\":\"Review Score\",\"field\":\"rate\",\"taxonomy\":\"attractions\"},{\"order\":\"2\",\"title\":\"Attractions\",\"field\":\"taxonomy\",\"taxonomy\":\"attractions\"}]","st_style":"dark"}},"activity-sidebar-2":{"st_widget_search_activity-3":{"title":"Filter By:","show_attribute":"","st_search_fields":"[{\"order\":\"0\",\"title\":\"Price\",\"field\":\"price\",\"taxonomy\":\"attractions\"},{\"order\":\"1\",\"title\":\"Category\",\"field\":\"taxonomy\",\"taxonomy\":\"attractions\"}]","st_style":"light"}},"tours-sidebar":{"st_widget_search_tour-2":{"title":"Filter By:","show_attribute":"","st_search_fields":"[{\"order\":\"0\",\"title\":\"Price\",\"field\":\"price\",\"taxonomy\":\"st_tour_type\"},{\"order\":\"1\",\"title\":\"Review Score\",\"field\":\"rate\",\"taxonomy\":\"st_tour_type\"},{\"order\":\"2\",\"title\":\"Category\",\"field\":\"taxonomy\",\"taxonomy\":\"st_tour_type\"}]"}},"tour-single-sidebar":{"calendar-2":{"title":""}}}';
    $data_object=json_decode($data_widget);
    wie_import_data( $data_object );
    _e('Update widget -> OK',STP_TEXTDOMAIN);
}
function st_update_icon_import(){
    $list_icon = 'a:68:{s:19:"2-pieces-of-laggage";s:12:"fa-briefcase";s:7:"3-doors";s:12:"im-car-doors";s:16:"air-conditioning";s:6:"im-air";s:17:"airport-transport";s:8:"im-plane";s:8:"amusemen";s:0:"";s:22:"automatic-transmission";s:13:"im-shift-auto";s:7:"bathtub";s:13:"im im-bathtub";s:10:"city-trips";s:0:"";s:15:"climate-control";s:18:"im-climate-control";s:3:"suv";s:0:"";s:8:"cultural";s:0:"";s:6:"deluxe";s:0:"";s:10:"ecotourism";s:0:"";s:12:"elder-access";s:8:"im-elder";s:13:"escorted-tour";s:0:"";s:12:"family-suite";s:0:"";s:14:"fitness-center";s:10:"im-fitness";s:14:"flat-screen-tv";s:8:"im im-tv";s:8:"fm-radio";s:5:"im-fm";s:12:"for-children";s:11:"im-children";s:11:"gas-vehicle";s:9:"im-diesel";s:10:"group-tour";s:0:"";s:12:"hosted-tours";s:0:"";s:13:"im-im-terrace";s:13:"im im-terrace";s:7:"kitchen";s:10:"im-kitchen";s:9:"landmarks";s:0:"";s:6:"ligula";s:0:"";s:6:"luxury";s:0:"";s:9:"main-menu";s:0:"";s:11:"main-menu-2";s:0:"";s:14:"meet-and-greet";s:9:"im-driver";s:24:"menu-sidebar-custom-page";s:0:"";s:8:"mini-bar";s:9:"im im-bar";s:7:"museums";s:0:"";s:6:"normal";s:0:"";s:8:"outdoors";s:0:"";s:7:"parking";s:10:"im-parking";s:5:"party";s:0:"";s:5:"patio";s:11:"im im-patio";s:4:"attr";s:0:"";s:11:"pet-allowed";s:6:"im-dog";s:4:"pool";s:7:"im-pool";s:17:"post-format-audio";s:0:"";s:19:"post-format-gallery";s:0:"";s:17:"post-format-image";s:0:"";s:16:"post-format-link";s:0:"";s:17:"post-format-quote";s:0:"";s:17:"post-format-video";s:0:"";s:16:"power-door-locks";s:7:"im-lock";s:13:"power-windows";s:13:"im-car-window";s:7:"economy";s:0:"";s:10:"queen-room";s:0:"";s:10:"restaurant";s:13:"im-restaurant";s:19:"shuttle-bus-service";s:6:"im-bus";s:15:"smoking-allowed";s:10:"im-smoking";s:10:"soundproof";s:16:"im im-soundproof";s:3:"spa";s:6:"im-spa";s:6:"sports";s:0:"";s:8:"standard";s:0:"";s:27:"standard-double-double-room";s:0:"";s:13:"standard-room";s:0:"";s:12:"stereo-cdmp3";s:9:"im-stereo";s:15:"terminal-pickup";s:8:"fa-plane";s:13:"uncategorized";s:0:"";s:18:"up-to-4-passengers";s:7:"fa-male";s:17:"wheelchair-access";s:14:"im-wheel-chair";s:14:"wi-fi-internet";s:8:"im-wi-fi";s:14:"zoos-aquariums";s:0:"";}';
    $list_icon = unserialize($list_icon);
    $taxonomies = get_taxonomies();
    $list_term = get_terms($taxonomies);
    foreach($list_term as $k=>$v){
        foreach($list_icon as $key => $value){
            if($v->slug == $key){
                if(!empty($value)){
                    update_option('tax_meta_'.$v->term_id,array('st_icon'=>$value));
                }
            }
        }
    }
    _e('Add Taxonomy after import XML -> OK',STP_TEXTDOMAIN);
}


/**
 * Import widget JSON data
 *
 * @since 0.4
 * @global array $wp_registered_sidebars
 * @param object $data JSON widget data from .wie file
 * @return array Results array
 */
if(!function_exists('remove_all_widgets_from_sidebar'))
{
    function remove_all_widgets_from_sidebar($sidebar_id)
    {
        $old_sidebar=get_option('sidebars_widgets',array());
        if(isset($old_sidebar[$sidebar_id]))
        {
            $old_sidebar[$sidebar_id]=array();
        }

        update_option('sidebars_widgets',$old_sidebar);
    }
}
if(!function_exists('wie_import_data'))
{
    function wie_import_data( $data ) {
        global $wp_registered_sidebars;
        // Have valid data?
        // If no data or could not decode
        if ( empty( $data ) || ! is_object( $data ) ) {
            wp_die(
                __( 'Import data could not be read. Please try a different file.', 'widget-importer-exporter' ),
                '',
                array( 'back_link' => true )
            );
        }
        // Hook before import
        do_action( 'wie_before_import' );
        $data = apply_filters( 'wie_import_data', $data );
        // Get all available widgets site supports
        $available_widgets = wie_available_widgets();
        // Get all existing widget instances
        $widget_instances = array();
        foreach ( $available_widgets as $widget_data ) {
            $widget_instances[$widget_data['id_base']] = get_option( 'widget_' . $widget_data['id_base'] );
        }
        // Begin results
        $results = array();
        // Loop import data's sidebars
        foreach ( $data as $sidebar_id => $widgets ) {
            // Skip inactive widgets
            // (should not be in export file)
            if ( 'wp_inactive_widgets' == $sidebar_id ) {
                continue;
            }
            // Check if sidebar is available on this site
            // Otherwise add widgets to inactive, and say so
            if ( isset( $wp_registered_sidebars[$sidebar_id] ) ) {
                remove_all_widgets_from_sidebar($sidebar_id);
                $sidebar_available = true;
                $use_sidebar_id = $sidebar_id;
                $sidebar_message_type = 'success';
                $sidebar_message = '';
            } else {
                $sidebar_available = false;
                $use_sidebar_id = 'wp_inactive_widgets'; // add to inactive if sidebar does not exist in theme
                $sidebar_message_type = 'error';
                $sidebar_message = __( 'Sidebar does not exist in theme (using Inactive)', 'widget-importer-exporter' );
            }
            // Result for sidebar
            $results[$sidebar_id]['name'] = ! empty( $wp_registered_sidebars[$sidebar_id]['name'] ) ? $wp_registered_sidebars[$sidebar_id]['name'] : $sidebar_id; // sidebar name if theme supports it; otherwise ID
            $results[$sidebar_id]['message_type'] = $sidebar_message_type;
            $results[$sidebar_id]['message'] = $sidebar_message;
            $results[$sidebar_id]['widgets'] = array();
            // Loop widgets
            foreach ( $widgets as $widget_instance_id => $widget ) {
                $fail = false;
                // Get id_base (remove -# from end) and instance ID number
                $id_base = preg_replace( '/-[0-9]+$/', '', $widget_instance_id );
                $instance_id_number = str_replace( $id_base . '-', '', $widget_instance_id );
                // Does site support this widget?
                if ( ! $fail && ! isset( $available_widgets[$id_base] ) ) {
                    $fail = true;
                    $widget_message_type = 'error';
                    $widget_message = __( 'Site does not support widget', 'widget-importer-exporter' ); // explain why widget not imported
                }
                // Filter to modify settings before import
                // Do before identical check because changes may make it identical to end result (such as URL replacements)
                $widget = apply_filters( 'wie_widget_settings', $widget );
                // Does widget with identical settings already exist in same sidebar?
                if ( ! $fail && isset( $widget_instances[$id_base] ) ) {
                    // Get existing widgets in this sidebar
                    $sidebars_widgets = get_option( 'sidebars_widgets' );
                    $sidebar_widgets = isset( $sidebars_widgets[$use_sidebar_id] ) ? $sidebars_widgets[$use_sidebar_id] : array(); // check Inactive if that's where will go
                    // Loop widgets with ID base
                    $single_widget_instances = ! empty( $widget_instances[$id_base] ) ? $widget_instances[$id_base] : array();
                    foreach ( $single_widget_instances as $check_id => $check_widget ) {
                        // Is widget in same sidebar and has identical settings?
                        if ( in_array( "$id_base-$check_id", $sidebar_widgets ) && (array) $widget == $check_widget ) {
                            $fail = true;
                            $widget_message_type = 'warning';
                            $widget_message = __( 'Widget already exists', 'widget-importer-exporter' ); // explain why widget not imported
                            break;
                        }

                    }
                }
                // No failure
                if ( ! $fail ) {
                    // Add widget instance
                    $single_widget_instances = get_option( 'widget_' . $id_base ); // all instances for that widget ID base, get fresh every time
                    $single_widget_instances = ! empty( $single_widget_instances ) ? $single_widget_instances : array( '_multiwidget' => 1 ); // start fresh if have to
                    $single_widget_instances[] = (array) $widget; // add it
                    // Get the key it was given
                    end( $single_widget_instances );
                    $new_instance_id_number = key( $single_widget_instances );
                    // If key is 0, make it 1
                    // When 0, an issue can occur where adding a widget causes data from other widget to load, and the widget doesn't stick (reload wipes it)
                    if ( '0' === strval( $new_instance_id_number ) ) {
                        $new_instance_id_number = 1;
                        $single_widget_instances[$new_instance_id_number] = $single_widget_instances[0];
                        unset( $single_widget_instances[0] );
                    }
                    // Move _multiwidget to end of array for uniformity
                    if ( isset( $single_widget_instances['_multiwidget'] ) ) {
                        $multiwidget = $single_widget_instances['_multiwidget'];
                        unset( $single_widget_instances['_multiwidget'] );
                        $single_widget_instances['_multiwidget'] = $multiwidget;
                    }
                    // Update option with new widget
                    update_option( 'widget_' . $id_base, $single_widget_instances );
                    // Assign widget instance to sidebar
                    $sidebars_widgets = get_option( 'sidebars_widgets' ); // which sidebars have which widgets, get fresh every time
                    $new_instance_id = $id_base . '-' . $new_instance_id_number; // use ID number from new widget instance
                    $sidebars_widgets[$use_sidebar_id][] = $new_instance_id; // add new instance to sidebar
                    update_option( 'sidebars_widgets', $sidebars_widgets ); // save the amended data
                    // Success message
                    if ( $sidebar_available ) {
                        $widget_message_type = 'success';
                        $widget_message = __( 'Imported', 'widget-importer-exporter' );
                    } else {
                        $widget_message_type = 'warning';
                        $widget_message = __( 'Imported to Inactive', 'widget-importer-exporter' );
                    }
                }
                // Result for widget instance
                $results[$sidebar_id]['widgets'][$widget_instance_id]['name'] = isset( $available_widgets[$id_base]['name'] ) ? $available_widgets[$id_base]['name'] : $id_base; // widget name or ID if name not available (not supported by site)
                $results[$sidebar_id]['widgets'][$widget_instance_id]['title'] =(isset($widget->title) and  $widget->title) ? $widget->title : __( 'No Title', 'widget-importer-exporter' ); // show "No Title" if widget instance is untitled
                $results[$sidebar_id]['widgets'][$widget_instance_id]['message_type'] = $widget_message_type;
                $results[$sidebar_id]['widgets'][$widget_instance_id]['message'] = $widget_message;
            }
        }
        // Hook after import
        do_action( 'wie_after_import' );
        // Return results
        return apply_filters( 'wie_import_results', $results );
    }
}
if(!function_exists('wie_available_widgets')){
    function wie_available_widgets() {
        global $wp_registered_widget_controls;
        $widget_controls = $wp_registered_widget_controls;
        $available_widgets = array();
        foreach ( $widget_controls as $widget ) {
            if ( ! empty( $widget['id_base'] ) && ! isset( $available_widgets[$widget['id_base']] ) ) { // no dupes
                $available_widgets[$widget['id_base']]['id_base'] = $widget['id_base'];
                $available_widgets[$widget['id_base']]['name'] = $widget['name'];
            }

        }
        return apply_filters( 'wie_available_widgets', $available_widgets );
    }
}