<?php

////////////////////////////////////////////////////////////////////////////////
/// Add new profile fields
////////////////////////////////////////////////////////////////////////////////

add_filter('user_contactmethods', 'wpestate_modify_contact_methods');     
if( !function_exists('wpestate_modify_contact_methods') ):

function wpestate_modify_contact_methods($profile_fields) {

	// Add new fields
        $profile_fields['facebook']                     = 'Facebook';
        $profile_fields['twitter']                      = 'Twitter';
        $profile_fields['linkedin']                     = 'Linkedin';
        $profile_fields['pinterest']                    = 'Pinterest';
        $profile_fields['instagram']                    = 'Instagram';
        $profile_fields['website']                      = 'Website';
	$profile_fields['phone']                        = 'Phone';
        $profile_fields['mobile']                       = 'Mobile';
	$profile_fields['skype']                        = 'Skype';
	$profile_fields['title']                        = 'Title/Position';
        $profile_fields['custom_picture']               = 'Picture Url';
        $profile_fields['small_custom_picture']         = 'Small Picture Url';
        $profile_fields['package_id']                   = 'Package Id';
        $profile_fields['package_activation']           = 'Package Activation';
        $profile_fields['package_listings']             = 'Listings available';
        $profile_fields['package_featured_listings']    = 'Featured Listings available';
        $profile_fields['profile_id']                   = 'Paypal Recuring Profile';
        $profile_fields['user_agent_id']                = 'User Agent Id';
        $profile_fields['stripe']                       = 'Stripe Consumer Profile';
        $profile_fields['stripe_subscription_id']       = 'Stripe Subscription ID';
        $profile_fields['has_stripe_recurring']         = 'Has Stripe Recurring';
	return $profile_fields;
}

endif; // end   wpestate_modify_contact_methods 







function wpestate_recaptcha_path($secret,$captcha){
    return "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".esc_html($_SERVER['REMOTE_ADDR']);
    
}


if( !function_exists('wpestate_my_order') ):
function wpestate_disable_filtering($filter, $function){
    remove_filter($filter, $function); 
}
endif;


if( !function_exists('wpestate_return_filtered_by_order') ):
function wpestate_return_filtered_by_order($args){
    add_filter( 'posts_orderby', 'wpestate_my_order' );
    $prop_selection = new WP_Query($args);
    remove_filter( 'posts_orderby', 'wpestate_my_order' );
    return $prop_selection;
}
endif;




if (!function_exists('wpestate_send_emails')):
    function wpestate_send_emails($receiver_email, $subject, $message,$headers=''){
        if($headers==''){
            $headers = 'From: noreply  <noreply@'.$_SERVER['HTTP_HOST'].'>' . "\r\n".
                        'Reply-To: noreply@'.$_SERVER['HTTP_HOST']. "\r\n" .
                        'X-Mailer: PHP/' . phpversion();
        }
        wp_mail($receiver_email, $subject, $message, $headers);
    }
endif;


if( !function_exists('wpestate_get_access_token') ):
    function wpestate_get_access_token($url, $postdata) {
	$clientId                       =   esc_html( get_option('wp_estate_paypal_client_id','') );
        $clientSecret                   =   esc_html( get_option('wp_estate_paypal_client_secret','') );
       
        $access_token='';
        $args=array(
                'method' => 'POST',
                'timeout' => 45,
                'redirection' => 5,
                'httpversion' => '1.0',
                'sslverify' => false,
                'blocking' => true,
                'body' =>  'grant_type=client_credentials',
                'headers' => [
                      'Authorization' => 'Basic ' . base64_encode( $clientId . ':' . $clientSecret ),
                      'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'
                ],
        );
        
        
        
        $response = wp_remote_post( $url, $args ); 
        
        
	if ( is_wp_error( $response ) ) {
	    $error_message = $response->get_error_message();
            die($error_message);
	} else {
	   
            $body = wp_remote_retrieve_body( $response );
            $body = json_decode( $body, true );
            $access_token = $body['access_token'];
        
	}

	return $access_token;
    }
endif; // end   wpestate_get_access_token 







if( !function_exists('wpestate_send_emails') ):
    function wpestate_send_emails($user_email, $subject, $message ){
        $headers = 'From: No Reply <noreply@'.$_SERVER['HTTP_HOST'].'>' . "\r\n";
        wp_mail(
            $user_email,
            $subject,
            $message,
            $headers
            );            
    };
endif;



////////////////////////////////////////////////////////////////////////////////
/// print page function 
////////////////////////////////////////////////////////////////////////////////


  add_action( 'wp_ajax_nopriv_wpestate_ajax_create_print', 'wpestate_ajax_create_print' );  
  add_action( 'wp_ajax_wpestate_ajax_create_print', 'wpestate_ajax_create_print' );  
  
  if( !function_exists('wpestate_ajax_create_print') ):
  function wpestate_ajax_create_print(){ 
    check_ajax_referer( 'wpestate_print_page_nonce', 'security' );
    if(!isset($_POST['propid'])|| !is_numeric($_POST['propid'])){
        exit('out pls1');
    }  
      
    $post_id            = intval($_POST['propid']);
    
    $the_post= get_post( $post_id); 
    if($the_post->post_type!='estate_property' || $the_post->post_status!='publish'){
        exit('out pls2');
    }
    
    $unit               = esc_html( get_option('wp_estate_measure_sys', '') );
    $wpestate_currency           = esc_html( get_option('wp_estate_currency_symbol', '') );
    $wpestate_where_currency     = esc_html( get_option('wp_estate_where_currency_symbol', '') );
    $property_address   = esc_html( get_post_meta($post_id, 'property_address', true) );
    $property_city      = strip_tags ( get_the_term_list($post_id, 'property_city', '', ', ', '') );
    $property_area      = strip_tags ( get_the_term_list($post_id, 'property_area', '', ', ', '') );
    $property_county    = esc_html( get_post_meta($post_id, 'property_county', true) );
    $property_zip       = esc_html(get_post_meta($post_id, 'property_zip', true) );
    $property_country   = esc_html(get_post_meta($post_id, 'property_country', true) );
    $ref_code           = get_post_meta($post_id, 'reference_code', true); 
      
    $property_size      = floatval(get_post_meta($post_id, 'property_size', true) );
    if ($property_size  != '') {
        $property_size  = wpestate_sizes_no_format($property_size) . ' '.esc_html__('square','wpestatetheme-core').' ' . $unit;
    }
    $property_bedrooms              = floatval ( get_post_meta($post_id, 'property_bedrooms', true) );
    $property_bathrooms             = floatval ( get_post_meta($post_id, 'property_bathrooms', true) );     
    $property_year                  = floatval ( get_post_meta($post_id, 'property_year', true) );  
                  
             
    $image_id           = get_post_thumbnail_id($post_id);
    $full_img           = wp_get_attachment_image_src($image_id, 'full');
    $full_img           = $full_img [0];
  
  
    $title              = get_the_title($post_id); 
    $page_object        = get_page( $post_id );
    $content            = $page_object->post_content;
    
    remove_filter('the_content', 'wpestate_pretyScan');
    $content            = apply_filters('the_content',$content);
    add_filter('the_content', 'wpestate_pretyScan');
    
    $price              = floatval   ( get_post_meta($post_id, 'property_price', true) );
  
   
    $price = wpestate_show_price($post_id,$wpestate_currency,$wpestate_where_currency,1);    
   
    
    $feature_list_array =   array();
    $feature_list       =   esc_html( get_option('wp_estate_feature_list') );
    $feature_list_array =   explode( ',',$feature_list);
    $all_features   ='';
    if ( !count( $feature_list_array )==0 ){
        foreach($feature_list_array as $checker => $value){
            $post_var_name=  str_replace(' ','_', trim($value) );
            if (esc_html( get_post_meta($post_id, $post_var_name, true) ) == 1) {
                 $all_features   .='<div class="print-right-row">'. trim($value).'</div>';
            }
        }
    }                    
                        
    /////////////////////////////////////////////////////////////////////////////////////////////////////
    // get thumbs
    /////////////////////////////////////////////////////////////////////////////////////////////////////
    $arguments = array( 
        'numberposts'   => -1,
        'post_type'     => 'attachment', 
        'post_parent'   => $post_id,
        'post_status'   => null,
        'exclude'       => $image_id,
        'orderby'       => 'menu_order',
        'order'         => 'ASC'
    );
    $post_attachments = get_posts($arguments);

    
    $agent_email='';
    $agent_skype='';
    $agent_mobile='';
    $agent_phone='';
    $name='';
    $preview_img='';
    
    /////////////////////////////////////////////////////////////////////////////////////////////////////
    // get agent details
    /////////////////////////////////////////////////////////////////////////////////////////////////////
    
    $agent_id   = intval( get_post_meta($post_id, 'property_agent', true) );
    if ($agent_id!=0){  
        $args = array(
            'post_type' => 'estate_agent',
            'p' => apply_filters( 'translate_object_id', $agent_id, 'post_estate_agent', true )
        );
        $agent_selection = new WP_Query($args);

        while ($agent_selection->have_posts()): $agent_selection->the_post();
            $thumb_id       = get_post_thumbnail_id($agent_id);
            $preview        = wp_get_attachment_image_src(get_post_thumbnail_id(), 'property_listings');
            $preview_img    = $preview[0];
            $agent_skype    = esc_html( get_post_meta($agent_id, 'agent_skype', true) );
            $agent_phone    = esc_html( get_post_meta($agent_id, 'agent_phone', true) );
            $agent_mobile   = esc_html( get_post_meta($agent_id, 'agent_mobile', true) );
            $agent_email    = esc_html( get_post_meta($agent_id, 'agent_email', true) );
            $agent_pitch    = esc_html( get_post_meta($agent_id, 'agent_pitch', true) );
            $agent_posit    = esc_html( get_post_meta($agent_id, 'agent_position', true) );
            $link           = esc_url( get_permalink($agent_id) );
            $name           = get_the_title($agent_id);

        endwhile;
        wp_reset_query();
    
    }else{
        $user_id=wpsestate_get_author($post_id);
        if ( get_the_author_meta('user_level',$user_id) !=10){
        
            $preview_img    =   get_the_author_meta( 'custom_picture',$user_id  );
            if($preview_img==''){
                $preview_img=get_template_directory_uri().'/img/default-user.png';
            }
       
            $agent_skype         = get_the_author_meta( 'skype' ,$user_id );
            $agent_phone         = get_the_author_meta( 'phone' ,$user_id );
            $agent_mobile        = get_the_author_meta( 'mobile' ,$user_id );
            $agent_email         = get_the_author_meta( 'user_email',$user_id );
            $agent_pitch         = '';
            $agent_posit         = get_the_author_meta( 'title',$user_id  );
            $agent_facebook      = get_the_author_meta( 'facebook',$user_id  );
            $agent_twitter       = get_the_author_meta( 'twitter',$user_id  );
            $agent_linkedin      = get_the_author_meta( 'linkedin' ,$user_id );
            $agent_pinterest     = get_the_author_meta( 'pinterest',$user_id  );
            $agent_urlc          = get_the_author_meta( 'website' ,$user_id );
            $link                = esc_url ( get_permalink());
            $name                = get_the_author_meta( 'first_name',$user_id ).' '.get_the_author_meta( 'last_name',$user_id);
            
       
       }
    }
    
    
    
    
    
    
     
    /////////////////////////////////////////////////////////////////////////////////////////////////////
    // end get agent details
    /////////////////////////////////////////////////////////////////////////////////////////////////////
        
    print  '<html><head><title>'.$title.'</title><link href="'.get_stylesheet_uri().'" rel="stylesheet" type="text/css" />';
    
    if(is_child_theme()){
        print '<link href="'.get_template_directory_uri().'/style.css" rel="stylesheet" type="text/css" />';   
    }
    
    if(is_rtl()){
        print '<link href="'.get_template_directory_uri().'/rtl.css" rel="stylesheet" type="text/css" />';
    }
    print '</head>';
    $protocol = is_ssl() ? 'https' : 'http';
    print  '<script src="'.$protocol.'://code.jquery.com/jquery-1.10.1.min.js"></script><script>$(window).load(function(){ print(); });</script>';
    print  '<body class="print_body" >';

    $logo=get_option('wp_estate_logo_image','');
    if ( $logo!='' ){
       print '<img src="'.$logo.'" class="img-responsive printlogo" alt="logo"/>';	
    } else {
       print '<img class="img-responsive printlogo" src="'. get_template_directory_uri().'/img/logo.png" alt="logo"/>';
    }
    print '<img class="print_qrcode" src="https://chart.googleapis.com/chart?cht=qr&chs=110x110&chl='. urlencode( esc_url( get_permalink($post_id)) ) .'&choe=UTF-8" title="'.urlencode($title).'" />';
    print'</div>';
    
    print '<h1 class="print_title">'.$title.'</h1>';
    print '<div class="print-price">'.esc_html__('Price','wpestatetheme-core').': '.$price.'</div>';
    print '<div class="print-addr">'. $property_address. ', ' . $property_city.', '.$property_area.'</div>';
    print '<div class="print-col-img"><img src="'.$full_img.'">';
   
    
        
    $property_description_text  =   esc_html( get_option('wp_estate_property_description_text') );
    $property_details_text      =   esc_html( get_option('wp_estate_property_details_text') );
    $property_features_text     =   esc_html( get_option('wp_estate_property_features_text') );
    $property_adr_text          =   stripslashes ( esc_html( get_option('wp_estate_property_adr_text') ) );
    $print_show_images          =   get_option('wp_estate_print_show_images','');
    $print_show_floor_plans     =   get_option('wp_estate_print_show_floor_plans','');
    $print_show_features        =   get_option('wp_estate_print_show_features','');
    $print_show_details         =   get_option('wp_estate_print_show_details','');
    $print_show_adress          =   get_option('wp_estate_print_show_adress','');
    $print_show_description     =   get_option('wp_estate_print_show_description','');
    $print_show_agent          =    get_option('wp_estate_print_show_agent','');
    $print_show_subunits        =   get_option('wp_estate_print_show_subunits','');
     
     
    if($print_show_subunits == 'yes'){ 
        global $property_subunits_master;
        $has_multi_units=intval(get_post_meta($post_id, 'property_has_subunits', true));
        $property_subunits_master=intval(get_post_meta($post_id, 'property_subunits_master', true));

        print '<div class="print_property_subunits_wrapper">';
            if($has_multi_units==1){
                print '<h2 class="print_header">'.esc_html__('Available Units','wpestatetheme-core').'</h2>';
                wpestate_shortcode_multi_units($post_id,$property_subunits_master,1);
            }else{
                if($property_subunits_master!=0){
                    wpestate_shortcode_multi_units($post_id,$property_subunits_master,1);
                }
            }
        print '</div>';
    }
   
 
    if( $print_show_agent == 'yes'){    
  

        print '<div class="print_header"><h2>'.esc_html__('Agent','wpestatetheme-core').'</h2></div>';
         print '<div class="print-content">';
        if ( $preview_img!='' ){
            print '<div class="print-col-img agent_print_image"><img src="'.$preview_img.'"></div>';
        }
        print '<div class="print_agent_wrapper">';
            if ($name!='')
                print '<div class="listing_detail_agent col-md-4 agent_name"><strong>'.esc_html__('Name','wpestatetheme-core').':</strong> '.$name.'</div>';
            if($agent_phone!='')
                print '<div class="listing_detail_agent col-md-4"><strong>'.esc_html__('Telephone','wpestatetheme-core').':</strong> '.$agent_phone.'</div>';
            if($agent_mobile!='')
                print '<div class="listing_detail_agent col-md-4"><strong>'.esc_html__('Mobile','wpestatetheme-core').':</strong> '.$agent_mobile.'</div>';
            if($agent_skype!='')
                print '<div class="listing_detail_agent col-md-4"><strong>'.esc_html__('Skype','wpestatetheme-core').':</strong> '.$agent_skype.'</div>';
            if($agent_email!='')
                print '<div class="listing_detail_agent col-md-4"><strong>'.esc_html__('Email','wpestatetheme-core').':</strong> '.$agent_email.'</div>';
        print '</div>';
        print '</div>';
        print '</div>';
        print '<div class="printbreak"></div>';
    }
  
    if( $print_show_description == 'yes' ){ 
        print '<div class="print_header"><h2>'.esc_html__('Property Description','wpestatetheme-core').'</h2></div><div class="print-content">'.$content.'</div></div>';
    }
      
    if($print_show_adress  == 'yes' ){ 
        print '<div class="print_header"><h2>';
            if($property_adr_text!=''){
                echo esc_html($property_adr_text);
            } else{
                esc_html_e('Property Address','wpestatetheme-core');
            }        
        print '</h2></div>';

        print '<div class="print-content">';
            print wpestate_listing_address_show($post_id); 
        print ' </div>';
    }   
    
    if($print_show_details == 'yes' ){ 
        print '<div class="print_header"><h2>';
            if($property_adr_text!=''){
                echo esc_html($property_details_text);
            } else{
                esc_html_e('Property Details','wpestatetheme-core');
            }   
        print '</h2></div>';
        print '<div class="print-content">';
            print estate_listing_details($post_id);
        print ' </div>';
    }
    
    if($print_show_features == 'yes'){ 
        print '<div class="print_header"><h2>';
            if($property_adr_text!=''){
                echo esc_html($property_features_text);
            } else{
                esc_html_e('Features and Amenities','wpestatetheme-core');
            }
        print '</h2></div>';
        print '<div class="print-content">';
            print estate_listing_features($post_id);
        print ' </div>';
        
    }
    
    if($print_show_floor_plans  == 'yes' ){ 
        print '<div class="print_header"><h2>'.esc_html__('Floor Plans','wpestatetheme-core').'</h2></div>';   
        print '<div class="print-content">';
            wpestate_floor_plan_print_show($post_id,1);
        print ' </div>';
        print '<div class="printbreak"></div>';
    }
    
    if($print_show_images  == 'yes' ){ 
        print '<div class="print_header"><h2>'.esc_html__('Images','wpestatetheme-core').'</h2></div>';                   
        foreach ($post_attachments as $attachment) {
            $original       =   wp_get_attachment_image_src($attachment->ID, 'full');
             print '<div class="print-col-img printimg"><img src="'. $original[0].'"></div>';
        }
    }
  
    print '<div class="print_spacer"></div>';
    print '</body></html>';die();
  } 

endif;

         



if( !function_exists('wpestate_new_import_options_tab') ):
function wpestate_new_import_options_tab(){
    
    if(isset($_POST['import_theme_options']) && $_POST['import_theme_options']!=''){
        
        $data =@unserialize(base64_decode( trim($_POST['import_theme_options']) ) );
        if ($data !== false && !empty($data) && is_array($data)) {
            foreach($data as $key=>$value){
                update_option($key, $value);          
            }
        
            print'<div class="estate_option_row">
            <div class="label_option_row">'.esc_html__('Import Completed','wpestatetheme-core') .'</div>
            </div>';
            update_option('wp_estate_import_theme_options','') ;
   
        }else{
            print'<div class="estate_option_row">
            <div class="label_option_row">'.esc_html__('The inserted code is not a valid one','wpestatetheme-core') .'</div>
            </div>';
            update_option('wp_estate_import_theme_options','') ;
        }

    }else{
        print'<div class="estate_option_row">
        <div class="label_option_row">'.esc_html__('Import Theme Options','wpestatetheme-core').'</div>
        <div class="option_row_explain">'.esc_html__('Import Theme Options ','wpestatetheme-core').'</div>    
            <textarea  rows="15" style="width:100%;" id="import_theme_options" name="import_theme_options"></textarea>
        </div>';
        print ' <div class="estate_option_row_submit">
        <input type="submit" name="submit"  class="new_admin_submit " value="'.esc_html__('Import','wpestatetheme-core').'" />
        </div>';
    } 
               
}
endif;





function wpestate_export_theme_options(){
    $export_options = array(
        'wp_estate_adv_back_color_opacity',
        'wp_estate_use_price_pins',
        'wp_estate_search_on_start',
        'wp_estate_float_form_top_tax',
        'wp_estate_float_form_top',
        'wp_estate_use_float_search_form',
        'wp_estate_mobile_header_background_color',
        'wp_estate_mobile_header_icon_color',
        'wp_estate_mobile_menu_font_color',
        'wp_estate_mobile_menu_hover_font_color',
        'wp_estate_mobile_item_hover_back_color',
        'wp_estate_mobile_menu_backgound_color',
        'wp_estate_mobile_menu_border_color',
        'wp_estate_crop_images_lightbox',
        'wp_estate_show_lightbox_contact',
        'wp_estate_submission_page_fields',
        'wp_estate_mandatory_page_fields',
        'wp_estate_url_rewrites',
        'wp_estate_print_show_subunits',
        'wp_estate_print_show_agent',
        'wp_estate_print_show_description',
        'wp_estate_print_show_adress',
        'wp_estate_print_show_details',
        'wp_estate_print_show_features',
        'wp_estate_print_show_floor_plans',
        'wp_estate_print_show_images',
        'wp_estate_show_header_dashboard',
        'wp_estate_user_dashboard_menu_color',
        'wp_estate_user_dashboard_menu_hover_color',
        'wp_estate_user_dashboard_menu_color_hover',
        'wp_estate_user_dashboard_menu_back',
        'wp_estate_user_dashboard_package_back',
        'wp_estate_user_dashboard_package_color',
        'wp_estate_user_dashboard_buy_package',
        'wp_estate_user_dashboard_package_select',
        'wp_estate_user_dashboard_content_back',
        'wp_estate_user_dashboard_content_button_back',
        'wp_estate_user_dashboard_content_color',
        'wp_estate_property_multi_text',                
        'wp_estate_property_multi_child_text', 
        'wp_estate_theme_slider_type',
        'wp_estate_adv6_taxonomy',
        'wp_estate_adv6_taxonomy_terms',   
        'wp_estate_adv6_max_price',     
        'wp_estate_adv6_min_price',
        'wp_estate_adv_search_fields_no',
        'wp_estate_search_fields_no_per_row',
        'wp_estate_property_sidebar',
        'wp_estate_property_sidebar_name',
        'wp_estate_show_breadcrumbs',
        'wp_estate_global_property_page_template',
        'wp_estate_p_fontfamily',
        'wp_estate_p_fontsize',
        'wp_estate_p_fontsubset',
        'wp_estate_p_lineheight',
        'wp_estate_p_fontweight',
        'wp_estate_h1_fontfamily',
        'wp_estate_h1_fontsize',
        'wp_estate_h1_fontsubset',
        'wp_estate_h1_lineheight',
        'wp_estate_h1_fontweight',
        'wp_estate_h2_fontfamily',
        'wp_estate_h2_fontsize',
        'wp_estate_h2_fontsubset',
        'wp_estate_h2_lineheight',
        'wp_estate_h2_fontweight',
        'wp_estate_h3_fontfamily',
        'wp_estate_h3_fontsize',
        'wp_estate_h3_fontsubset',
        'wp_estate_h3_lineheight',
        'wp_estate_h3_fontweight',
        'wp_estate_h4_fontfamily',
        'wp_estate_h4_fontsize',
        'wp_estate_h4_fontsubset',
        'wp_estate_h4_lineheight',
        'wp_estate_h4_fontweight',
        'wp_estate_h5_fontfamily',
        'wp_estate_h5_fontsize',
        'wp_estate_h5_fontsubset',
        'wp_estate_h5_lineheight',
        'wp_estate_h5_fontweight',
        'wp_estate_h6_fontfamily',
        'wp_estate_h6_fontsize',
        'wp_estate_h6_fontsubset',
        'wp_estate_h6_lineheight',
        'wp_estate_h6_fontweight',
        'wp_estate_menu_fontfamily',
        'wp_estate_menu_fontsize',
        'wp_estate_menu_fontsubset',
        'wp_estate_menu_lineheight',
        'wp_estate_menu_fontweight',
        'wp_estate_transparent_logo_image',
        'wp_estate_stikcy_logo_image',
        'wp_estate_logo_image',
        'wp_estate_sidebar_boxed_font_color',
        'wp_estate_sidebar_heading_background_color',
        'wp_estate_map_controls_font_color',
        'wp_estate_map_controls_back',
        'wp_estate_transparent_menu_hover_font_color',
        'wp_estate_transparent_menu_font_color',
        'wp_estate_top_menu_hover_back_font_color',
        'wp_estate_top_menu_hover_type',
        'wp_estate_top_menu_hover_font_color',
        'wp_estate_menu_item_back_color',
        'wp_estate_sticky_menu_font_color',
        'wp_estate_top_menu_font_size',
        'wp_estate_menu_item_font_size',
        'wpestate_uset_unit',
        'wp_estate_widget_sidebar_border_size',
        'wp_estate_widget_sidebar_border_color',
        'wp_estate_unit_border_color',
        'wp_estate_unit_border_size',
        'wp_estate_blog_unit_min_height',
        'wp_estate_agent_unit_min_height',
        'wp_estate_agent_listings_per_row',
        'wp_estate_blog_listings_per_row',
        'wp_estate_content_area_back_color',
        'wp_estate_contentarea_internal_padding_top',
        'wp_estate_contentarea_internal_padding_left',
        'wp_estate_contentarea_internal_padding_bottom',
        'wp_estate_contentarea_internal_padding_right',
        'wp_estate_property_unit_color',
        'wp_estate_propertyunit_internal_padding_top',
        'wp_estate_propertyunit_internal_padding_left',
        'wp_estate_propertyunit_internal_padding_bottom',
        'wp_estate_propertyunit_internal_padding_right',       
        'wpestate_property_unit_structure',
        'wpestate_property_page_content',
        'wp_estate_main_grid_content_width',
        'wp_estate_main_content_width',
        'wp_estate_header_height',
        'wp_estate_sticky_header_height',
        'wp_estate_cssbox_shadow',
        'wp_estate_prop_unit_min_height',
        'wp_estate_border_bottom_header',
        'wp_estate_sticky_border_bottom_header',
        'wp_estate_listings_per_row',
        'wp_estate_unit_card_type',
        'wp_estate_prop_unit_min_height',
        'wp_estate_main_grid_content_width',
        'wp_estate_header_height',
        'wp_estate_sticky_header_height',
        'wp_estate_border_bottom_header_sticky_color',
        'wp_estate_border_bottom_header_color',
        'wp_estate_show_top_bar_user_login',
        'wp_estate_show_top_bar_user_menu',
        'wp_estate_show_adv_search_general',
        'wp_estate_currency_symbol',
        'wp_estate_where_currency_symbol',
        'wp_estate_measure_sys',
        'wp_estate_facebook_login',
        'wp_estate_google_login',
        'wp_estate_yahoo_login',
        'wp_estate_wide_status',
        'wp_estate_header_type',
        'wp_estate_prop_no',
        'wp_estate_prop_image_number',
        'wp_estate_show_empty_city',
        'wp_estate_blog_sidebar',
        'wp_estate_blog_sidebar_name',
        'wp_estate_blog_unit',
        'wp_estate_general_latitude',
        'wp_estate_general_longitude',
        'wp_estate_default_map_zoom',
        'wp_estate_cache',
        'wp_estate_show_adv_search_map_close',
        'wp_estate_pin_cluster',
        'wp_estate_zoom_cluster',
        'wp_estate_hq_latitude',
        'wp_estate_hq_longitude',
        'wp_estate_idx_enable',
        'wp_estate_geolocation_radius',
        'wp_estate_min_height',
        'wp_estate_paid_submission',
        'wp_estate_admin_submission',
        'wp_estate_user_agent',
        'wp_estate_price_submission',
        'wp_estate_price_featured_submission',
        'wp_estate_submission_curency',
        'wp_estate_free_mem_list',
        'wp_estate_free_feat_list',
        'wp_estate_free_feat_list_expiration',
        'wp_estate_custom_advanced_search',
        'wp_estate_adv_search_type',
        'wp_estate_show_adv_search',
        'wp_estate_show_adv_search_map_close',
        'wp_estate_cron_run',
        'wp_estate_show_no_features',
        'wp_estate_property_features_text',
        'wp_estate_property_description_text',
        'wp_estate_property_details_text',
        'wp_estate_status_list',
        'wp_estate_slider_cycle',
        'wp_estate_show_save_search',
        'wp_estate_search_alert',
        'wp_estate_adv_search_type',
        'wp_estate_color_scheme',
        'wp_estate_main_color',
        'wp_estate_background_color',
        'wp_estate_content_back_color',
        'wp_estate_header_color',
        'wp_estate_breadcrumbs_font_color',
        'wp_estate_font_color',
        'wp_estate_menu_items_color',
        'wp_estate_link_color',
        'wp_estate_headings_color',
        'wp_estate_sidebar_heading_boxed_color',
        'wp_estate_sidebar_heading_color',
        'wp_estate_sidebar_widget_color',
        'wp_estate_sidebar2_font_color',
        'wp_estate_footer_back_color',
        'wp_estate_footer_font_color',
        'wp_estate_footer_copy_color',
        'wp_estate_footer_copy_back_color',
        'wp_estate_menu_font_color',
        'wp_estate_menu_hover_back_color',
        'wp_estate_menu_hover_font_color',
        'wp_estate_menu_border_color',
        'wp_estate_top_bar_back',
        'wp_estate_top_bar_font',
        'wp_estate_adv_search_back_color',
        'wp_estate_adv_search_font_color',
        'wp_estate_box_content_back_color',
        'wp_estate_box_content_border_color',
        'wp_estate_hover_button_color',
        'wp_estate_show_g_search',
        'wp_estate_show_adv_search_extended',
        'wp_estate_readsys',
        'wp_estate_map_max_pins',
        'wp_estate_ssl_map',
        'wp_estate_enable_stripe',    
        'wp_estate_enable_paypal',    
        'wp_estate_enable_direct_pay',    
        'wp_estate_global_prpg_slider_type',
        'wp_estate_global_prpg_content_type',
        'wp_estate_logo_margin',
        'wp_estate_header_transparent',
        'wp_estate_default_map_type',
        'wp_estate_prices_th_separator',
        'wp_estate_multi_curr',
        'wp_estate_date_lang',
        'wp_estate_blog_unit',
        'wp_estate_enable_autocomplete',
        'wp_estate_enable_user_pass',
        'wp_estate_auto_curency',
        'wp_estate_status_list',
        'wp_estate_custom_fields',
        'wp_estate_subject_password_reset_request',
        'wp_estate_password_reset_request',
        'wp_estate_subject_password_reseted',
        'wp_estate_password_reseted',
        'wp_estate_subject_purchase_activated',
        'wp_estate_purchase_activated',
        'wp_estate_subject_approved_listing',
        'wp_estate_approved_listing',
        'wp_estate_subject_new_wire_transfer',
        'wp_estate_new_wire_transfer',
        'wp_estate_subject_admin_new_wire_transfer',
        'wp_estate_admin_new_wire_transfer',
        'wp_estate_subject_admin_new_user',
        'wp_estate_admin_new_user',
        'wp_estate_subject_new_user',
        'wp_estate_new_user',
        'wp_estate_subject_admin_expired_listing',
        'wp_estate_admin_expired_listing',
        'wp_estate_subject_matching_submissions',
        'wp_estate_subject_paid_submissions',
        'wp_estate_paid_submissions',
        'wp_estate_subject_featured_submission',
        'wp_estate_featured_submission',
        'wp_estate_subject_account_downgraded',
        'wp_estate_account_downgraded',
        'wp_estate_subject_membership_cancelled',
        'wp_estate_membership_cancelled',
        'wp_estate_subject_downgrade_warning',
        'wp_estate_downgrade_warning',
        'wp_estate_subject_membership_activated',
        'wp_estate_membership_activated',
        'wp_estate_subject_free_listing_expired',
        'wp_estate_free_listing_expired',
        'wp_estate_subject_new_listing_submission',
        'wp_estate_new_listing_submission',
        'wp_estate_subject_listing_edit',
        'wp_estate_listing_edit',
        'wp_estate_subject_recurring_payment',
        'wp_estate_subject_recurring_payment',
         'wp_estate_custom_css',
        'wp_estate_company_name',
        'wp_estate_telephone_no',
        'wp_estate_mobile_no',
        'wp_estate_fax_ac',
        'wp_estate_skype_ac',
        'wp_estate_co_address',
        'wp_estate_facebook_link',
        'wp_estate_twitter_link',
        'wp_estate_pinterest_link',
        'wp_estate_instagram_link',
        'wp_estate_linkedin_link',
        'wp_estate_contact_form_7_agent',
        'wp_estate_contact_form_7_contact',
        'wp_estate_global_revolution_slider',
        'wp_estate_repeat_footer_back',
        'wp_estate_prop_list_slider',
        'wp_estate_agent_sidebar',
        'wp_estate_agent_sidebar_name',
        'wp_estate_property_list_type',
        'wp_estate_property_list_type_adv',
        'wp_estate_prop_unit',
        'wp_estate_general_font',
        'wp_estate_headings_font_subset',
        'wp_estate_copyright_message',
        'wp_estate_show_graph_prop_page',
        'wp_estate_map_style',
        'wp_estate_submission_curency_custom',
        'wp_estate_free_mem_list_unl',
        'wp_estate_adv_search_what',
        'wp_estate_adv_search_how',
        'wp_estate_adv_search_label',
        'wp_estate_adv_search_type',
        'wp_estate_show_save_search',
        'wp_estate_show_adv_search_slider',
        'wp_estate_show_adv_search_visible',
        'wp_estate_show_slider_price',
        'wp_estate_show_dropdowns',
        'wp_estate_show_slider_min_price',
        'wp_estate_show_slider_max_price',
        'wp_estate_adv_back_color',
        'wp_estate_adv_font_color',
        'wp_estate_adv_position',
        'wp_estate_feature_list',
        'wp_estate_show_no_features',
        'wp_estate_advanced_exteded',
        'wp_estate_adv_search_what',
        'wp_estate_adv_search_how',
        'wp_estate_adv_search_label',
        'wp_estate_property_adr_text',
        'wp_estate_property_features_text',
        'wp_estate_property_description_text',
        'wp_estate_property_details_text',
        'wp_estate_new_status',
        'wp_estate_status_list',
        'wp_estate_theme_slider',
        'wp_estate_slider_cycle',
        'wp_estate_use_mimify',
        'wp_estate_currency_label_main',
        'wp_estate_footer_background',
        'wp_estate_wide_footer',
        'wp_estate_show_footer',
    '   wp_estate_show_footer_copy',
        'wp_estate_footer_type',
        'wp_estate_logo_header_type',
        'wp_estate_wide_header',
        'wp_estate_logo_header_align',
     
        'wp_estate_general_country'
        );
    
  
    
    $return_exported_data=array();
    // esc_html( get_option('wp_estate_where_currency_symbol') );
    foreach($export_options as $option){
        $real_option=get_option($option);
        
        if(is_array($real_option)){
            $return_exported_data[$option]= get_option($option) ;
        }else{
            $return_exported_data[$option]=esc_html( get_option($option) );
        }
     
    }
    
    return base64_encode( serialize( $return_exported_data) );
    
}




add_action( 'wp_ajax_wpestate_start_demo_import', 'wpestate_start_demo_import' );

if( !function_exists('wpestate_start_demo_import') ):
function wpestate_start_demo_import(){
    check_ajax_referer( 'wpestate_activate_template_nonce', 'security' );
    if(!is_admin()){
        exit('out pls');
    }
       
    /* include importers */
    if (!defined('WP_LOAD_IMPORTERS')) define('WP_LOAD_IMPORTERS', true);
                
    if (!class_exists('WP_Importer')) {
        $wp_importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';
        include $wp_importer;
    }
    
    if (!class_exists('WP_Import')) {
        require_once WPESTATE_PLUGIN_PATH.'resources/wordpress-importer.php';
    }

    $base_template = sanitize_text_field($_POST['base_template']);
    
    $base_template_dir  =    get_template_directory();  
    $theme_content      =    $base_template_dir . '/wpestate_templates/'.$base_template.'/theme_content.xml';
    $theme_options      =    $base_template_dir . '/wpestate_templates/'.$base_template.'/options.txt';   
    $theme_widget       =    $base_template_dir . '/wpestate_templates/'.$base_template.'/widgets.wie';
    $rev_slder_main     =    $base_template_dir . '/wpestate_templates/'.$base_template.'/main.zip';

            
    
    ////////////////////// import the actual demo content
    $importer = new WP_Import();
  
    $importer->fetch_attachments = true;
    ob_start();  ob_end_clean();
    $importer->import($theme_content);
  
    echo '<li>'.esc_html__('Demo content is imported.','wpestatetheme-core').'</li>';

    ////////////////////// import menus
    $menu_locations  = get_theme_mod('nav_menu_locations');
    $menus      = wp_get_nav_menus();
 
    if ($menus) {
        foreach ($menus as $menu) {
            if ($menu->name == 'Main Navigation' || $menu->name == 'Main' || $menu->name == 'Main Menu' || $menu->name == 'main') {
                $menu_locations['primary'] = $menu->term_id;
                $menu_locations['mobile']= $menu->term_id;
            }
            if ($menu->name == 'Footer' || $menu->name == 'footer') {
                $menu_locations['footer_menu'] = $menu->term_id;
            }
        }
    }
    echo '<li>'.esc_html__('Menus are configured','wpestatetheme-core').'</li>';
    set_theme_mod('nav_menu_locations', $menu_locations);
    

    ////////////////////// set up pages
    $homepage = get_page_by_title('Homepage');
    if (!empty($homepage->ID)) {
        update_option('page_on_front', $homepage->ID);
        update_option('show_on_front', 'page');
         
        echo '<li>'.esc_html__('Default homepage is configured','wpestatetheme-core').'</li>';
    }else{
        echo '<li>'.esc_html__('Default homepage is NOT configured','wpestatetheme-core').'</li>';
    }
         
    
    ///////////////////// theme options imports
                        
    $import_data =file_get_contents($theme_options);
    $data = unserialize(base64_decode($import_data));
    

  
    if (!empty($data)) {
        foreach($data as $key=>$value){
            update_option($key, $value);          
        }
        update_option('wp_estate_readsys','no' );
        echo '<li>'.esc_html__('Theme options are imported.','wpestatetheme-core').'</li>';
    }
     ///////////////////// widgets import
    $wid_import_data    =   file_get_contents($theme_widget);
    $data               =   json_decode($wid_import_data);
    
    global $wp_registered_sidebars;
    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']])) {
            $available_widgets[ $widget['id_base']]['id_base'] = $widget['id_base'];
            $available_widgets[ $widget['id_base']]['name'] = $widget['name'];
        }
    }
    
    $widget_instances = array();
    foreach ($available_widgets as $widget_data) {
        $widget_instances[ $widget_data['id_base']] = get_option('widget_' . $widget_data['id_base']);
    }
         
   
    $imported_sidebars=  array();
    
    foreach ($data as $sidebar_id => $widgets) {
        if (!isset($wp_registered_sidebars[ $sidebar_id ])) {
            $imported_sidebars[] =$sidebar_id;
            //    print 'add '.$sidebar_id.'</br>';
        }
    }
    
    update_option('estate_imported_sidebars',$imported_sidebars);

    foreach ($data as $sidebar_id => $widgets) {
        if ('wp_inactive_widgets' == $sidebar_id) {
            continue;
        }
        
        if (isset($wp_registered_sidebars[ $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';
            $sidebar_message_type   = 'error';
            $sidebar_message        = esc_html__('Sidebar does not exist', 'wpestatetheme-core');
        }
       
   
        
        if ( !empty($wp_registered_sidebars[ $sidebar_id ]['name']) ){
            $results[ $sidebar_id ]['name'] = $wp_registered_sidebars[ $sidebar_id ]['name'];
        }else{
            $results[ $sidebar_id ]['name']  = $sidebar_id;
        }
        $results[ $sidebar_id ]['message_type'] = $sidebar_message_type;
        $results[ $sidebar_id ]['message']      = $sidebar_message;
        $results[ $sidebar_id ]['widgets']      = array();
        
        
        foreach ($widgets as $widget_instance_id => $widget) {
                $fail = false;
                $id_base = preg_replace('/-[0-9]+$/', '', $widget_instance_id);
                $instance_id_number = str_replace($id_base . '-', '', $widget_instance_id);
                if (!$fail && !isset($available_widgets[ $id_base ])) {
                        $fail                   = true;
                        $widget_message_type    = 'error';
                        $widget_message         = esc_html__('Site does not support this widget', 'wpestatetheme-core');
                }
                
             
                
                if (!$fail && isset($widget_instances[ $id_base ])) {
                        $sidebars_widgets           = get_option('sidebars_widgets');
                      
                        if(isset($sidebars_widgets[ $use_sidebar_id ])){
                            $sidebar_widgets = $sidebars_widgets[ $use_sidebar_id ];
                        }else{
                            $sidebar_widgets =array();
                        }
                      
                        if( !empty($widget_instances[ $id_base ])  ){
                            $single_widget_instances   =  $widget_instances[ $id_base ]; 
                        }else{
                            $single_widget_instances  = array();
                        }
                        
                        
                        foreach ($single_widget_instances as $check_id => $check_widget) {
                            if (in_array("$id_base-$check_id", $sidebar_widgets) && (array)$widget == $check_widget) {
                                $fail = true;
                                $widget_message_type = 'warning';
                                $widget_message = esc_html__('Widget already exists', 'wpestatetheme-core');
                                break;
                            }
                        }
                }
                
                if (!$fail) {
                        $single_widget_instances = get_option('widget_' . $id_base);
                        $single_widget_instances = !empty($single_widget_instances) ? $single_widget_instances : array(
                                '_multiwidget' => 1
                        );
                        $single_widget_instances[] = (array)$widget;
                        end($single_widget_instances);
                        $new_instance_id_number = key($single_widget_instances);
                        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]);
                        }
                        if (isset($single_widget_instances['_multiwidget'])) {
                                $multiwidget = $single_widget_instances['_multiwidget'];
                                unset($single_widget_instances['_multiwidget']);
                                $single_widget_instances['_multiwidget'] = $multiwidget;
                        }
                        update_option('widget_' . $id_base, $single_widget_instances);
                        $sidebars_widgets = get_option('sidebars_widgets');
                        $new_instance_id = $id_base . '-' . $new_instance_id_number;
                        $sidebars_widgets[ $use_sidebar_id ][] = $new_instance_id;
                        update_option('sidebars_widgets', $sidebars_widgets);
                        if ($sidebar_available) {
                                $widget_message_type = 'success';
                                $widget_message = esc_html__('Imported', 'wpestatetheme-core');
                        } 
                        else {
                                $widget_message_type = 'warning';
                                $widget_message = esc_html__('Imported to Inactive', 'wpestatetheme-core');
                        }
                }

                if( isset( $available_widgets[ $id_base ]['name'] ) ) {
                    $results[ $sidebar_id ]['widgets'][ $widget_instance_id ]['name'] = $available_widgets[ $id_base ]['name'] ;
                }else{
                    $results[ $sidebar_id ]['widgets'][ $widget_instance_id ]['name'] = $id_base;
                }
                
                if($widget->title){
                    $results[ $sidebar_id ]['widgets'][ $widget_instance_id ]['title'] =$widget->title;
                }else{
                    $results[ $sidebar_id ]['widgets'][ $widget_instance_id ]['title'] =esc_html__('No Title', 'wpestatetheme-core');
                }
                
                $results[ $sidebar_id ]['widgets'][ $widget_instance_id ]['message_type'] = $widget_message_type;
                $results[ $sidebar_id ]['widgets'][ $widget_instance_id ]['message'] = $widget_message;
            }
            
          
    }
    

    if( file_exists  ($rev_slder_main) ) {
        if(function_exists('RevSlider')){
            $slider = new RevSlider();
            $slider->importSliderFromPost(true,true,$rev_slder_main);  
        }
    }


    die();

}
endif;





?>