Current File : /home/n742ef5/royalanteam.com/mls_bkp/property_import.php
<?php

    ini_set('memory_limit', '1024M');
    set_time_limit(0);
    ini_set('max_execution_time', 7200);
    ini_set('display_errors', 1);
    ini_set("log_errors", 1);
    ini_set('default_charset', 'UTF-8');
    error_reporting(E_ALL);
    header('Content-Type: text/html; charset=utf-8');
    date_default_timezone_set('America/Toronto');
    $plus_v = urlencode("+");
    $mtime   = microtime();
    $mtime   = explode(" ", $mtime);
    $mtime   = $mtime[1] . $mtime[0];
    $t_start = $mtime;
    require_once("config/mls_config.php");
    require_once("lib/phrets.php");
    require_once("config/properties_config.php");
    require_once("/home/n742ef5/royalanteam.com/wp-load.php");
    //require_once("../wp-load.php");
    global $wpdb;
    echo $website_uri = site_url();
    $main_directory = '/home/n742ef5/royalanteam.com/';
    $message  = "";
    $message = '<html><head><title>Property Wordpress Import</title></head><body>';
	$timestamp_field = 'Timestamp_sql'; 
    $file_name       = "mls_import.php";
    $curr_resource   = "Property";
    $mls_key_field   = "Ml_num";
    echo "<pre>";
    $curr_mls_id     = 1;
    date_default_timezone_set('America/Toronto');
    $curr_date       = date('Y-m-d H:i:s');

    foreach($all_classes as $classkey=> $classdata ) {
        $className = $classdata['ClassName'];
        $pro_table = $classdata['TableName'];
        $classNameText = $classdata['classNameText'];
        echo "<br>".$last_success_query = "SELECT * FROM $pro_table where processed=0 and Status='A' and  Municipality IN ('Markham', 'Toronto', 'Ajax', 'Pickering', 'Oshawa', 'Mississauga', 'Brampton','King') ORDER BY Timestamp_sql DESC LIMIT 300";
        //Scarborough
        //continue;    
        $last_prp_data = $wpdb->get_results($last_success_query,ARRAY_A);
        $all_arr = array();
        $message .= "<table border=1><thead><tr><th>Sr. No</th><th>MLS#</th><th>Title</th><th>Post Id</th></tr></thead> ";
        foreach ($last_prp_data as $record) {
            $listing_key = $record[ $mls_key_field ];
            $ci_p        = date('Y-m-d H:i:s');
            $style = strtolower($record['Style']);
            $default_photo = 272361 ;
            $properties_inserted_in_db++;
            $message  .= "<tr><td>".$properties_inserted_in_db."</td><td >".$listing_key."</td>";            
            $custom_address = '';
            $custom_address .= isset($record['St_num']) ? $record['St_num'] . ' ' : '';
            $custom_address .= isset($record['St_dir']) ? $record['St_dir'] . ' ' : '';
            $custom_address .= isset($record['St']) ? $record['St'] . ' ' : '';
            $custom_address .= isset($record['St_sfx']) ? $record['St_sfx'] . ' ' : '';
            $custom_address .= isset($record['Unit']) ? $record['Unit'] . ' ' : '';
               
            $property_address = isset($record['Addr']) ? $record['Addr'] : $custom_address;
            $unitno = isset($record['Apt_num'])?$record['Apt_num']:'';
			if(trim($unitno)!=''){
                $property_address = $property_address.' #'.$unitno ;
            }
            //$property_address = $property_address.' #'.$unitno ;
            $property_address = preg_replace('/\s /', '-', $property_address);
            $property_address = preg_replace('/\s+/', '-', $property_address);
            $property_address = preg_replace('/\#+/', '#', $property_address);
            
            $property_address = trim($property_address);
            $property_address = str_ireplace("-", " ", $property_address) ;
            $property_address = preg_replace('/\s+/', ' ', $property_address);
            $property_address = preg_replace('/\#+/', '#', $property_address);
            $property_address = preg_replace('/\-+/', ' ', $property_address);          
            
            $post_title                     = trim($property_address) . ', ' . $record['Municipality'] . ', '.$record['County'].', ' . $record['Zip'] . ' ' . $record['Ml_num'];
            $post_title                     = preg_replace('/\s+/', ' ', $post_title);
            $post_title                     = trim($post_title);
            $post_title                     = str_ireplace("-", " ", $post_title) ;
            $post_title                     = preg_replace('/\#+/', '#', $post_title);
            $post_title                     = preg_replace('/\s+/', ' ', $post_title); 
            $string_without_tags            = strip_tags($property_address . '-'.$record['Municipality'].'-'. $record['County'] . '-' . $record['Zip'] . '-' . $record['Ml_num']);
            $string_without_tags            = preg_replace('/\s+/', '-', $string_without_tags);
            $string_without_tags            = preg_replace('/\-+/', '-', $string_without_tags);
            $vowels                         = array(" ", ",", ".","#");
            $filtered                       = str_replace($vowels, "-", $string_without_tags);
            $filtered                       = preg_replace('/\-+/', '-', $filtered);
            $filtered = strtolower($filtered);
            $message  .= "<td>".$post_title."</td>";
            $post_data = array(
                'post_content'  => $record['Ad_text'],
                'post_title'    => $post_title,
                'post_name'     => $filtered,
                'post_status'   => 'publish',
                'post_author' => 4,
                'post_type'     => 'estate'
            );
            $post_meta_data = array();
            $qn_query = "select post_id from $wpdb->postmeta where meta_key='fave_mls_field_key_value' and meta_value = '".$listing_key."' ";
            $pre_post = $wpdb->get_results( $qn_query );
            //print_r($pre_post);
            if ($pre_post && !empty($pre_post) ) {
                $post_id  = $pre_post[0]->post_id;
                $lasttime = get_post_meta($post_id, 'property_image_downloaded_time');
                if (is_array($lasttime) && isset($lasttime[0])) {
                    $lasttime_property_image_downloaded_time = $lasttime[0];
                }
                $image_downloaded_current = $record['Pix_updt'];
                if (!isset($lasttime_property_image_downloaded_time) || $lasttime_property_image_downloaded_time == '' || $lasttime_property_image_downloaded_time == '0000-00-00 00:00:00' || (strtotime($lasttime_property_image_downloaded_time) < strtotime($image_downloaded_current))) {
                    $post_meta_data['image_update_needed'] = 1;
                    //$post_data['post_status']              = 'draft';
                }
                $post_data['ID'] = $post_id;
                wp_update_post( $post_data );
                // Remove previous term and default metadata
                $remove_query_meta = "DELETE FROM $wpdb->postmeta  where post_id = $post_id and meta_key NOT IN('fave_mls_field_key_value','_thumbnail_id','fave_property_images','property_image_downloaded_time','image_update_needed','fave_prop_slider_image')";
                $result_remove     = $wpdb->query($remove_query_meta);                      
                $del_term = "DELETE FROM $wpdb->term_relationships where object_id = $post_id ";
                $wpdb->query($del_term);
                $updated_prop++;
            } else {
                $inserted_prop++;
                $post_meta_data['_thumbnail_id']          = $default_photo;
                //$post_meta_data['fave_prop_slider_image'] = $default_photo;
                $post_meta_data['image_update_needed']    = 1;                
                $post_id = wp_insert_post( $post_data );
            }
            echo "<br>Post Id :".$post_id;
            $message  .= " <td> ".$post_id." </td></tr>";
            //continue;
            //*************** META DATA **************************//

            $addition_features_keys = array( 
                'Gar_spaces'=>'Garage spaces',
                'Gar_type'=>'Garage type',
                'Tot_park_spcs'=>'Parking',
                'Heating'=>'Heating',
                'A_c'=>'AirConditioning',
                'Heat_inc'=>'HeatIncluded',
                'Fpl_num'=>'Fireplace',
                'Fuel'=>'Heat Source',
                'Furnished'=>'Furnished',
                'Gas'=>'Utilities-Gas',
                'Num_kit'=>'Kitchens',
                'Dom'=>'DaysOnMarket',
                'Den_fr'=>'Family Room',
                'Extras'=>'Extras',                 
                'Bsmt1_out'=>'Basement Feature1',
                'Bsmt1_out'=>'Basement Feature2',
                'Util_cable'=>'Cable',
                'Util_tel'=>'Telephone',
                'Br_plus'=>'Bedroom Plus',
                'Cable'=>'CableTv',
                'Cac_inc'=>'Cac Include',
                'Comel_inc'=>'Common Elements Included',
                'Comp_pts'=>'Fronting On NSEW',                
                'Constr2_out'=>'Exterior2',     
                'Prop_feat1_out'=>'Prop Feature1',
                'Prop_feat2_out'=>'Prop Feature2',
                'Prop_feat3_out'=>'Prop Feature3',
                'Prop_feat4_out'=>'Prop Feature4',
                'Prop_feat5_out'=>'Prop Feature5',
                'Prop_feat6_out'=>'Prop Feature6',           
                'Area'=>'Area',
                //'County'=>'County',
                //'Municipality'=>'Municipality',
                'Water'=>'Water',
                'Water_body'=>'Water Body Name',
                'Water_type'=>'Water Body Type',
                'Water_front'=>'Water Frontage',
                'Front_ft'=>'Lot Front',
                'Depth'=>'Lot Depth',                
                'Elec'=>'Utilities-Hydro',
                'Shoreline_exp'=>'ShorelineExposure',                
                'Farm_agri'=>'Farm_agri',
                'Park_chgs'=>'Park Cost',
                'Prkg_inc'=>'Parking Included',
                'Park_spcs'=>'Parking Spaces',                
                'Pool'=>'Pool',
                'Access_prop1'=>'AccessToProperty1',
                'Access_prop2'=>'AccessToProperty2',                
                'Pvt_ent'=>'PrivateEntrance',
                'Retirement'=>'Retirement',
                'Irreg'=>'Lot Irregularities',
                'Legal_desc'=>'Legal Description',
                'Rltr'=>'ListBrokerage',
                'Rms'=>'Rooms',
                'S_r'=>'SaleLease',
                'Sewer'=>'Sewers',
                'Sewage1'=>'Sewage1',
                'Sewage2'=>'Sewage2',
                'Potl'=>'Parcel Of TiedLand',
                'Spec_des1_out'=>'Special Designation1',
                'Spec_des2_out'=>'Special Designation2',
                'Spec_des3_out'=>'Special Designation3',
                'Spec_des4_out'=>'Special Designation4',
                'Spec_des5_out'=>'Special Designation5',
                'Style'=>'Style',
                'Tv'=>'Assessment',                    
                'Vend_pis'=>'Seller Property Info Statement',                    
                'Zoning'=>'Zoning',
                'Yr_built'=>'ApproxAge',
                'Wcloset_p1'=>'WashroomsType1Pcs',
                'Wcloset_p2'=>'WashroomsType2Pcs',
                'Wcloset_p3'=>'WashroomsType3Pcs',
                'Wcloset_p4'=>'WashroomsType4Pcs',
                'Wcloset_p5'=>'WashroomsType5Pcs',
                'Wcloset_t1lvl'=>'Washrooms Type1Level',
                'Wcloset_t2lvl'=>'Washrooms Type2Level',
                'Wcloset_t3lvl'=>'Washrooms Type3Level',
                'Wcloset_t4lvl'=>'Washrooms Type4Level',
                'Wcloset_t5lvl'=>'Washrooms Type5Level',
                'Wcloset_t1'=>'WashroomsType1',
                'Wcloset_t2'=>'WashroomsType2',
                'Wcloset_t3'=>'WashroomsType3',
                'Wcloset_t4'=>'WashroomsType4',
                'Wcloset_t5'=>'WashroomsType5', 
                ////////////////
                'Bus_type'=>'Use',
                'Chattels'=>'Chattels',
                'Crane'=>'Crane',
                'Shpdrsdlhtft'=>'Drive-In Level Shipping Doors Height Feet',
                'Shpdrsdlnu'=>'Drive-In Level Shipping Doors',
                'Shpdrsdlwdft'=>'Drive-In Level Shipping Doors Width Feet',
                'Shpdrsdmhtft'=>'Double Man Shipping Doors Height Feet',
                'Shpdrsdmnu'=>'Double Man Shipping Doors #',
                'Shpdrsdmwdft'=>'Double Man Shipping Doors Width Feet',
                'Shpdrsglhtft'=>'Grade Level Shipping Doors Height Feet',
                'Shpdrsglnu'=>'Grade Level Shipping Doors #',
                'Shpdrsglwdft'=>'Grade Level Shipping Doors Width Feet',
                'Shpdrstlhtft'=>'Truck Level Shipping Doors Height Feet',
                'Shpdrstlnu'=>'Truck Level Shipping Doors #',
                'Shpdrstlwdft'=>'Truck Level Shipping Doors Width Feet',
                'Sprinklers'=>'Sprinklers',
                'Trlr_pk_spt'=> 'Trailer Parking Spots',
                'Utilities'=>'Utilities',
                'Wtr_suptyp'=>'WaterSupplyTypes',
                'Bay_size1'=>'Bay Size Width Feet',
                'Bay_size2' =>'Bay Size Length Feet',
                 /////////////Condo////                    
                'Rural_svc1'=>'Rural Services1',
                'Rural_svc2'=>'Rural Services2',
                'Rural_svc3'=>'Rural Services3',
                'Rural_svc4'=>'Rural Services4',
                'Rural_svc5'=>'Rural Services5',
                'Water_acc_bldg1'=>'Waterfront Accessory Bldgs1',
                'Water_acc_bldg2'=>'Waterfront Accessory Bldgs2',
                'Water_del_feat1'=>'Water Delivery Features1',
                'Water_del_feat2'=>'Water Delivery Features2',
                'Sewage1'=>'Sewage1',
                'Sewage2'=>'Sewage2',                
                'Bldg_amen1_out'=>'BuildingAmenities1',
                'Bldg_amen2_out'=>'BuildingAmenities2',
                'Bldg_amen3_out'=>'BuildingAmenties3',
                'Bldg_amen4_out'=>'BuildingAmenties4',
                'Bldg_amen5_out'=>'BuildingAmenities5',
                'Bldg_amen6_out'=>'BuildingAmenities6',
                'Park_lgl_desc1'=>'Parking Legal Description',
                'Park_lgl_desc2'=>'Parking Legal Description2',
                'Locker_num'=>'Locker #',
            );
            
            $allrooms = array();
            $all_roomsname = array('Living', 'Utility', 'Dining','Family');
            for($i=0;$i<12;$i++) {
                if( isset($record['Level'.$i]) && $record['Level'.$i]!=''){
                    $desc[] = $record['Rm'.$i.'_dc1_out'];
                    $desc[] = $record['Rm'.$i.'_dc2_out'];
                    $desc[] = $record['Rm'.$i.'_dc3_out'];
                    $all_desc = implode(',', $desc);
                    $all_desc = preg_replace('/\,+/',',',$all_desc);
                    $name = $record['Rm'.$i.'_out'];
                    if($name=='Rec'){
                        $name = 'Recreational, Games room';
                    } else if( in_array($name, $all_roomsname) ){
                        $name = $name.' Room';
                    } else if( $name=='Master' ){
                        $name = $name." Bedroom";
                    }
                    $name  = str_ireplace(' Br', 'Bedroom', $name);
                    $level = $record['Level'.$i];
                    if( in_array($level,array('Upper','Lower','Main','Ground')) ){
                        $level = $level.' Level';
                    } else if( $level =='Bsmt'){
                        $level = 'Basement';
                    }
                    $allrooms[] = array(
                            'level' => $level,
                            'description' => $all_desc,
                            'length' => $record['Rm'.$i.'_len'],
                            'width' => $record['Rm'.$i.'_wth'],
                            'name' => $name,
                        );
                }
            }

            $feature_tax = array();
            if( isset($record['A_c']) && $record['A_c']!='' && strtolower($record['A_c'])!='none'){
                $feature_tax['Air conditioning'] = 1;
            }
            if( isset($record['Heat_inc']) && $record['Heat_inc']!='' && strtolower($record['Heat_inc'])!='n'){
                $feature_tax['Heat Included'] = 1;
            }
            //$post_meta_data['fave_property_daysonmarket'] = $record['Dom'];            
            if( isset($record['Heating']) && $record['Heating']!='' && strtolower($record['Heating'])!='none'){
                $feature_tax['Heating'] = 1;
            }
            if( isset($record['Hydro_inc']) && $record['Hydro_inc']!='' && strtolower($record['Hydro_inc'])!='n'){
                $feature_tax['Hydro Included'] = 1;
            }
            if( isset($record['Laundry']) && $record['Laundry']!='' && strtolower($record['Laundry'])!='none'){
                $feature_tax['Laundry'] = 1;
            }
            if( isset($record['Cable']) && $record['Cable']!='' && strtolower($record['Cable'])!='n'){
                $feature_tax['Cable TV Included'] = 1;
            }
            if( isset($record['Central_vac']) && $record['Central_vac']!='' && strtolower($record['Central_vac'])!='n'){
                $feature_tax['Central_vac'] = 1;
            }
            if( isset($record['Elevator']) && $record['Elevator']!='' && strtolower($record['Elevator'])!='n'){
                $feature_tax['Elevator'] = 1;
            }
            if( isset($record['Furnished']) && $record['Furnished']!='' && strtolower($record['Furnished'])!='n'){
                $feature_tax['Furnished'] = 1;
            }
            if( isset($record['Pool']) && $record['Pool']!='' && strtolower($record['Pool'])!='none'){
                $feature_tax['Pool'] = 1;
            }
            if( isset($record['Waterfront']) && $record['Waterfront']!='' && strtolower($record['Waterfront'])!='none'){
                $feature_tax['Waterfront'] = 1;
            }
            if( isset($record['Sewer']) && $record['Sewer']!='' && strtolower($record['Sewer'])!='none'){
                $feature_tax['Sewer'] = 1;
            }
            if( isset($record['Chattels']) && $record['Chattels']!='' && strtolower($record['Chattels'])!='none'){
                $feature_tax['Chattels'] = 1;
            }
            if( isset($record['Crane']) && $record['Crane']!='' && strtolower($record['Crane'])!='n'){
                $feature_tax['Crane'] = 1;
            }

            //$post_meta_data['fave_property_typeasset'] = ($record['Addl_mo_fee']>0)?'AddlMonthlyFees ('.$record['Addl_mo_fee'].')':'Freehold'; 
            //$post_meta_data['fave_property_lotsizecode']  =  $record['Lotsz_code'];
            //$post_meta_data['fave_property_featurefireplace'] = ($record['Fpl_num']=='Y')?'Yes':'No';
            //$post_meta_data['fave_property_familyroom'] = ($record['Den_fr']=='Y')?'Yes':'No';
            //$post_meta_data['fave_property_laundylev']  =  $record['Laundry_lev'];
            //$post_meta_data['fave_property_taxes']  = $record['Taxes'];            
            //$post_meta_data['fave_property_construction']  =  $record['Constr1_out'];
            /*$post_meta_data['fave_property_drive']  =  $record['Drive'];
            $post_meta_data['fave_property_realtor']  =  $record['Rltr'];
            $post_meta_data['fave_property_community'] = $record['Community'];
            $post_meta_data['fave_property_land']           = $record['Acres'] ;
            $post_meta_data['fave_property_taxyear'] = $record['Yr'];
            $post_meta_data['fave_property_maintenancefee'] = round($record['Maint']);
            */
            //$post_meta_data['fave_property_unit_number'] = $record['Unit_num'];
            /*$post_meta_data['fave_property_condocorp'] = $record['Corp_num'];
            $post_meta_data['fave_property_condocorpname'] = $record['Condo_corp'];
            $post_meta_data['fave_property_balcony'] = $record['Patio_ter'];
            $post_meta_data['fave_property_petpolicy'] = $record['Pets'];
            $post_meta_data['fave_property_park_type'] = $record['Park_desig'];
            */
            //$post_meta_data['fave_property_heatinc'] = $record['Heat_inc'];
            //$post_meta_data['fave_property_cableinc'] = $record['Cable'];
            //$post_meta_data['fave_property_waterinc'] = $record['Water_inc'];
            
            
            //$post_meta_data['property_status']           = $record['Status'];
            $post_meta_data['fave_property_id']             = $listing_key;
            $post_meta_data['fave_mls_field_key_value']     = $listing_key;
            //$post_meta_data['fave_property_rooms']          = $allrooms;
            $add_count = 0 ;
            foreach($addition_features_keys as $feature_key => $feature_title){
                if(isset($record[ $feature_key ]) && !empty($record[ $feature_key ])){
                    if($record[ $feature_key ]=='Y' ){
                        $record[ $feature_key ] = 'Yes';
                    } else if($record[ $feature_key ]=='N'){
                        $record[ $feature_key ] = 'No';
                    }
                    $post_meta_data['_estate_additional_features_'.$add_count.'_estate_additional_feature_name'  ] = 'myhome_estate_additional_feature_name';
                    $post_meta_data['_estate_additional_features_'.$add_count.'_estate_additional_feature_value'  ] = 'myhome_estate_additional_feature_value';                    
                    $post_meta_data['estate_additional_features_'.$add_count.'_estate_additional_feature_name'  ] = $feature_title;
                    $post_meta_data['estate_additional_features_'.$add_count.'_estate_additional_feature_value'  ] = $record[ $feature_key ];
                    //estate_additional_features_2_estate_additional_feature_name
                    //_estate_additional_features_2_estate_additional_feature_name
                    $add_count++;
                }
            }
            

            $main_values = array(
                'estate_featured'=>1,
                'estate_attr_price'=>(int)$record['Lp_dol'],
                'estate_attr_bedrooms'=> $record['Br'],
                'estate_attr_bathrooms'=>$record['Bath_tot'],
                'estate_attr_property-size'=>$record['Sqft'],
                'estate_attr_year-built'=> $record['Yr_built'],
                //'estate_attr_lot-size'=>'',
                'estate_additional_features'=>$add_count,
                'estate_location'=>'',
                'estate_video'=>$record['Tour_url'],
            );

            foreach($main_values as $fkey=>$fvalue){
                if( isset($fvalue) && $fvalue!='' ){
                    $post_meta_data[$fkey] = $fvalue;
                    $post_meta_data['_'.$fkey] = 'myhome_'.$fkey;
                }
            }

            if(  !isset($record['Latitude']) || $record['Latitude']==0 ){
                $prop_address = $property_address . ', ' . $record['Municipality'] . ', ' . $record['County'] . ' ' . $record['Zip'];
                $prop_address = preg_replace('/\s+/',' ',$prop_address);
                $prop_address = preg_replace('/\,/','',$prop_address);
                $address = urlencode($prop_address . " CA");
                $string = str_replace (" ", "+", urlencode($address));
                //$mapbox_key = 'pk.eyJ1IjoibXVrZXNoMzMxMzU2IiwiYSI6ImNrZHFhaThvNDBhMHAycnFzanFqZnZzeXgifQ.zKf9afqgVM_dF45RVjbb1w';
                $mapbox_key = 'pk.eyJ1Ijoic2VhcmNocmVhbHR5IiwiYSI6ImNrZzlqaGNuZDAzNG8ycm1uMTkzbXlwYnkifQ.-jVwvmMKpQS4hZ3hksPc-w';
                $geourl = "https://api.mapbox.com/geocoding/v5/mapbox.places/" . $string . ".json?access_token=$mapbox_key";
                $geocode = file_get_contents($geourl);
                $output  = json_decode($geocode);
                if (!empty($output->features[0]->center)) {
                    $lat = $output->features[0]->center[1];
                    $lng = $output->features[0]->center[0];
                    $lat = round($lat,17);
                    $lng = round($lng,17);
                    echo "<br> Lat ".$lat . "    Lng ".$lng ;
                    $post_meta_data['houzez_geolocation_lat']  = $lat ;
                    $post_meta_data['houzez_geolocation_long'] = $lng;
                    $post_meta_data['fave_property_location']  = $lat.','.$lng;
                }
            }
            foreach ($post_meta_data as $meta_key => $metavalue) {
                if (!add_post_meta($post_id, $meta_key, $metavalue, true)) {
                    update_post_meta($post_id, $meta_key, $metavalue);
                }
            }
            //$classNameText = $record['classNameText'];
            
            $all_tax = array(
                array('name'=>'property-type' , 'value'=> $record['Type_own1_out']),
                array('name'=>'offer-type','value'=> $record['S_r'] ),
                //array('name'=>'property_label' ,'value'=> $record['S_r'] ),
                array('name'=>'city' ,'value'=> $record['Municipality']),
                array('name'=>'zip-code' ,'value'=> $record['Zip'] ),
                array('name'=>'neighborhood' ,'value'=> $record['Area'] ),
                array('name'=>'street' ,'value'=> $record['Community'] )
            );
            foreach ($feature_tax as $key => $value) {
                $all_tax[] = array('name'=>'features' ,'value'=>$key);
            }
            //print_r($all_tax);
            /*foreach ($all_tax as $term_tax) {
                $taxonomy   = $term_tax['name'];
                $term_value = $term_tax['value'];
                if( !isset($term_value) || trim($term_value)=='' ) continue;
                $term_info = term_exists( $term_value, $taxonomy );
                if(!empty($term_info)){
                    $term_id = $term_info['term_id'];
                } else {
                    $term_info = wp_insert_term(
                        $term_value, 
                        $taxonomy,
                        array(
                            'parent' => $parent_term_id,
                        )
                    );
                    $term_id = $term_info['term_id'];
                }
                wp_set_post_terms( $post_id, $term_id, $taxonomy , true );
            }*/
            //echo "<br>";
            foreach ($all_tax as $term_tax) {
                //print_r($term_tax);
                $taxonomy   = $term_tax['name'];
                $term_value = $term_tax['value'];
                if( !isset($term_value) || trim($term_value)=='' ) 
                    continue;
                $term_info = term_exists( $term_value, $taxonomy );
                if(!empty($term_info)){
                    //echo "FFFFFFFFFF";
                    //print_r($term_info);
                    $term_id = $term_info['term_id'];
                } else {
                    //echo "AAAAAA";
                    $term_info = wp_insert_term(
                        $term_value, 
                        $taxonomy,
                        array(
                            'description' => $term_value,
                        )
                    );
                    //print_r($term_info);                                        
                    if( isset($term_info->errors) ){
                        print_r($term_info);
                        print_r($term_tax);
                        continue;
                    }
                    $term_id = $term_info['term_id'];
                }
                //echo "  ------   ".$term_id;
                //wp_set_post_terms( $post_id, $term_value.'', $taxonomy , true );
                wp_set_object_terms( $post_id, $term_value.'', $taxonomy , true );                
                //exit;
            }
            $update_query = "UPDATE $pro_table SET processed=1 WHERE $mls_key_field='$listing_key'";    
            $last_prp_data = $wpdb->query($update_query);
            //exit;
        }
        $message .= "</table>";
    }

    $message .= "</body></html>";
    
    // exit;
    $sql_query = "SELECT post_id FROM $wpdb->postmeta where meta_key ='fave_mls_field_key_value' order by post_id desc LIMIT 4000,10";
    $all_post = $wpdb->get_results( $sql_query,ARRAY_A );
    $c = 0;
    $website_uri2 = str_replace('http', 'https', $website_uri);
    echo $website_uri2;
    echo "<hr>";
    echo $website_uri;
    //exit;
    if ($all_post && !empty($all_post) ) {
        foreach($all_post as $curr_post){
            $c++;
            $post_id  = $curr_post['post_id'];
            echo "<br>".$c." Post Id :".$post_id;
            //continue;
            $media  = get_attached_media('', $post_id);
            //echo "<pre>";
            //print_r($media);
            //exit;
            if (isset($media) && count($media) > 0) {
                foreach ($media as $photo) {
                    echo "<br>".$main_image_path = $photo->post_content_filtered;
                    error_log("Image " . $main_image_path . "<br>");
                    unlink($main_image_path);
                    $thumbnail_image_src    = wp_get_attachment_image_src($photo->ID, 'thumbnail');
                    echo "##".$thumbnail_image_src['0']."::";
                    if(strpos($thumbnail_image_src['0'], "https") !== false){
                        $thumbnail_relative_url = str_replace($website_uri2.'/', $main_directory, $thumbnail_image_src['0']);
                    } else {
                    $thumbnail_relative_url = str_replace($website_uri.'/', $main_directory, $thumbnail_image_src['0']);
                    }
                    echo "<br>".$thumbnail_relative_url;
                                           
                    unlink($thumbnail_relative_url);
                    //exit;
                    $image_post_id   = $photo->ID;
                    $wp_delete_query = "DELETE FROM $wpdb->postmeta where post_id=$image_post_id";
                    $wpdb->query($wp_delete_query);
                    $wp_delete_query = "DELETE FROM $wpdb->posts where ID =$image_post_id";
                    $wpdb->query($wp_delete_query);
                }
            }
            $wp_delete_query = "DELETE FROM $wpdb->postmeta where post_id=$post_id and meta_key in('_iwp_gallery','fave_property_images')";
            $wpdb->query($wp_delete_query);
                                                
            $remove_query_meta = "DELETE FROM $wpdb->postmeta  where post_id = $post_id ";
            $result_remove     = $wpdb->query($remove_query_meta);
                                  
            $del_term = "DELETE FROM $wpdb->term_relationships where object_id = $post_id ";
            $wpdb->query($del_term);
                      
            $remove_main   = "DELETE FROM $wpdb->posts where ID = $post_id ";
            $result_remove = $wpdb->query($remove_main);
            
        }
    }
    exit;
    
    
    
    
    echo $message;
    exit;
    $end_time = date('Y-m-d H:i:s');
    if($properties_inserted_in_db>2){
        $headers = 'From: Royalanteam <noreply@'.$_SERVER['HTTP_HOST'].'>' . "\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
        mail('mukesh14092019@gmail.com','Wordpress Import '.$end_time,$message,$headers);
    }
    exit;