Current File : /home/n742ef5/royalanteam.com/mls/WpImport.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once(dirname(__FILE__) . '/constant.php');
require_once(ABSPATH . 'wp-load.php');


global $wpdb;
$limit = 100;
$offset = 0;
$table_name = 'properties';
$mls_key_field='ListingKey';
echo "Property import to wordpress Started \n";
$total_records = $wpdb->get_var("SELECT COUNT(*) FROM properties where flag = 0 and MlsStatus IN ('Active','Pending','Active Under Contract') and  City IN ('Markham', 'Toronto', 'Ajax', 'Pickering', 'Oshawa', 'Mississauga', 'Brampton','King');");
$total_records=955;
echo "Import Count $total_records \n";
for ($offset = 0; $offset < $total_records; $offset += $limit) {
    try {
        $query = $wpdb->prepare("SELECT * FROM $table_name WHERE flag = 0 and MlsStatus IN ('Active','Pending','Active Under Contract') and  City IN ('Markham', 'Toronto', 'Ajax', 'Pickering', 'Oshawa', 'Mississauga', 'Brampton','King') order by id desc LIMIT %d", $limit);
        $propertiesData = $wpdb->get_results($query, ARRAY_A);
    
        if (!empty($propertiesData)) {
            foreach ($propertiesData as $record) {
                $json_data = json_decode($record['otherjson'], true);
                $listing_key = $record[$mls_key_field];
                $record = array_merge($record, $json_data);
                $default_photo = 272361;
                $property_post_id = null;
                $custom_address = '';
                $custom_address .= isset($record['UnitNumber']) ? $record['UnitNumber'] . ' ' : '';
                $custom_address .= isset($record['StreetNumber']) ? $record['StreetNumber'] . ' ' : '';
                $custom_address .= isset($record['StreetName']) ? $record['StreetName'] . ' ' : '';
                $custom_address .= isset($record['StreetSuffix']) ? $record['StreetSuffix'] . ' ' : '';
                $custom_address .= isset($record['CountyOrParish']) ? $record['CountyOrParish'] . ' ' : '';
                $custom_address .= isset($record['StateOrProvince']) ? $record['StateOrProvince'] . ' ' : '';
                $custom_address .= isset($record['PostalCode']) ? $record['PostalCode'] . ' ' : '';
                $property_address = isset($record['UnparsedAddress']) ? $record['UnparsedAddress'] : $custom_address;
                // $unitno = isset($record['Apt_num'])?$record['Apt_num']:'';
                // if(trim($unitno)!=''){
                //     $property_address = $property_address.' #'.$unitno ;
                // }
                //$property_address = $property_address.' #'.$unitno ;
                $post_title_post = trim($property_address) . ' ' . $record['ListingKey'];

                $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['City'] . ', ' . $record['CountyOrParish'] . ', ' . $record['PostalCode'] . ' ' . $record['ListingKey'];
                $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['City'] . '-' . $record['CountyOrParish'] . '-' . $record['PostalCode'] . '-' . $record['ListingKey']);
                $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);
                $post_data = array(
                    'post_content' => $record['PublicRemarks'],
                    'post_title' => $post_title_post,
                    'post_name' => $filtered,
                    'post_status' => 'publish',
                    'post_author' => 4,
                    'post_type' => 'estate'
                );
                $property_post_id = $record['post_id'];
                $post_id_db = get_post_id_by_meta_value('fave_property_id', $record['ListingKey']);
                if (!empty($post_id_db)) {
                    $property_post_id = $post_id_db;
                    $is_update_post = true;
                } else {
                    $is_update_post = false;
                }

                if ($is_update_post) {
                    $post_data["ID"] = $property_post_id;
                    $property_post_id = wp_update_post($post_data);
                } else {
                    $property_post_id = wp_insert_post($post_data);
                }

                echo "\n PostId::$property_post_id";
                $post_meta_data = array();
                $post_meta_data['fave_photo_timestamp'] = $record['PhotosChangeTimestamp'];
                $image_download = true;
                $timeStampCheck = get_post_meta($property_post_id, 'fave_photo_timestamp', true);
                $IsImages = get_post_meta($property_post_id, 'fave_property_images', true);

                // Check if we need to download images
                if ($IsImages) {
                    $image_download = false;
                    if ($timeStampCheck) {
                        $prevTimestamp = strtotime($timeStampCheck);
                        $newTimestamp = strtotime($record['PhotosChangeTimestamp']);
                        if ($newTimestamp > $prevTimestamp) {
                            $image_download = true;
                        }
                    }
                }

                $post_id = $property_post_id;
                $image_url = $record['Media'] ?? [];
                update_post_meta($property_post_id, 'estate_gallery', '');
                update_post_meta($property_post_id, '_estate_gallery', 'myhome_estate_gallery');
                if ($image_download && !empty($image_url)) {
                    $image_urls = json_decode($image_url, true);
                    echo "Images Count =>> " . count($image_urls) . "\n";
                    
                    if (is_array($image_urls) && !empty($image_urls)) {
                        // Delete existing images if updating
                        if ($is_update_post) {
                            delete_post_images($property_post_id);
                        }
                        
                        $attachment_ids = upload_images_from_urls($image_urls, $property_post_id);
                        if (!empty($attachment_ids)) {
                            update_post_meta($property_post_id, 'estate_gallery', $attachment_ids);
                            // print_r(serialize($attachment_ids));die;
                            update_post_meta($property_post_id, '_estate_gallery', 'myhome_estate_gallery');
                            
                            // Set the first image as featured image
                            if (!empty($attachment_ids[0])) {
                                set_post_thumbnail($property_post_id, $attachment_ids[0]);
                            }
                        }
                    }
                }


                $addition_features_keys = array(
                    
                    'GarageParkingSpaces' => 'Garage spaces',
                    'GarageType' => 'Garage type',
                    'ParkingTotal' => 'Parking',
                    'HeatType' => 'Heating',
                    'Cooling'=>'Cooling',
                    'FireplacesTotal' => 'Fireplace',
                    'HeatSource' => 'Heat Source',
                    'Furnished' => 'Furnished',
                    'KitchensTotal' => 'Kitchens',
                    'DaysOnMarket' => 'Days On Market',
                    'DenFamilyroomYN' => 'Family Room',
                    'TelephoneYNA' => 'Telephone',
                    'ExteriorFeatures' => 'Exterior Features',
                    'Water' => 'Water',
                    'WaterBodyName' => 'WaterBodyName',
                    'WaterBodyType' => 'WaterBodyType',
                    'WaterFrontageFt' => 'WaterFrontageFt',
                    'LotWidth' => 'Lot Width',
                    'LotDepth' => 'Lot Depth',
                    'ConstructionMaterials'=>'ConstructionMaterials',
                    'ShorelineExposure' => 'Shoreline Exposure',
                    'ParkingMonthlyCost' => 'Parking Monthly Cost',
                    'ParkingSpaces' => 'Parking Spaces',
                    'ParkingFeatures'=>'Parking Features',
                    'AccessToProperty' => 'Access To Property',
                    'PrivateEntranceYN' => 'Private Entrance',
                    'LotIrregularities' => 'Lot Irregularities',
                    'TaxLegalDescription' => 'Tax Legal Description',
                    'Sewer' => 'Sewer',
                    'Sewage' => 'Sewage',
                    'ParcelOfTiedLand' => 'Parcel Of TiedLand',
                    'SpecialDesignation' => 'Special Designation',
                    'Zoning' => 'Zoning',
                    'Roof'=> 'Roof',
                    'WashroomsType1Pcs' => 'Washrooms Type1Pcs',
                    'WclWashroomsType2Pcsoset_p2' => 'Washrooms Type2Pcs',
                    'WashroomsType3Pcs' => 'Washrooms Type3Pcs',
                    'WashroomsType4Pcs' => 'Washrooms Type4Pcs',
                    'WashroomsType5Pcs' => 'Washrooms Type5Pcs',
                    'WashroomsType1Level' => 'Washrooms Type1Level',
                    'WashroomsType2Level' => 'Washrooms Type2Level',
                    'WashroomsType3Level' => 'Washrooms Type3Level',
                    'WashroomsType4Level' => 'Washrooms Type4Level',
                    'WashroomsType5Level' => 'Washrooms Type5Level',
                    'WashroomsType1' => 'WashroomsType1',
                    'WashroomsType2' => 'WashroomsType2',
                    'WashroomsType3' => 'WashroomsType3',
                    'WashroomsType4' => 'WashroomsType4',
                    'WashroomsType5' => 'WashroomsType5',
                    'ChattelsYN' => 'Chattels',
                    'PoolFeatures'=>'Pool Features',
                    'CraneYN' => 'Crane',
                    'FarmFeatures'=>'Farm Features',
                    'SecurityFeatures'=>'Security Features',
                    'FireplaceFeatures'=>'Fireplace Features',
                    'WaterfrontFeatures'=>'Waterfront Features',
                    'LaundryFeatures'=>'Laundry Features',
                    'DriveInLevelShippingDoorsHeightFeet' => 'DriveInLevelShippingDoorsHeightFeet',
                    'DriveInLevelShippingDoors' => 'DriveInLevelShippingDoors',
                    'DriveInLevelShippingDoorsWidthFeet' => 'DriveInLevelShippingDoorsWidthFeet',
                    'DoubleManShippingDoorsHeightFeet' => 'DoubleManShippingDoorsHeightFeet',
                    'DoubleManShippingDoors' => 'DoubleManShippingDoors',
                    'DoubleManShippingDoorsWidthFeet' => 'DoubleManShippingDoorsWidthFeet',
                    'GradeLevelShippingDoorsHeightFeet' => 'GradeLevelShippingDoorsHeightFeet',
                    'GradeLevelShippingDoors' => 'GradeLevelShippingDoors',
                    'GradeLevelShippingDoorsWidthFeet' => 'GradeLevelShippingDoorsWidthFeet',
                    'TruckLevelShippingDoorsHeightFeet' => 'TruckLevelShippingDoorsHeightFeet',
                    'TruckLevelShippingDoors' => 'TruckLevelShippingDoors',
                    'TruckLevelShippingDoorsWidthFeet' => 'TTruckLevelShippingDoorsWidthFeet',
                    'TrailerParkingSpots' => 'TrailerParkingSpots',
                    'Utilities' => 'Utilities',
                    'WaterSource' => 'WaterSupplyTypes',
                    'BaySizeWidthFeet' => 'BaySizeWidthFeet',
                    'BaySizeLengthFeet' => 'BaySizeLengthFeet',
                    'WaterfrontAccessory' => 'WaterfrontAccessory',
                    'WaterDeliveryFeature' => 'WaterDeliveryFeature',
                    'LockerNumber' => 'Locker #',
                    'LotFeatures'=>'Lot Features',
                    'AccessibilityFeatures'=>'Accessibility Features',
                    'CommunityFeatures'=>'Community Features',


                );

               
                $feature_tax = array();
                if (isset($record['HeatType']) && $record['HeatType'] != '' && strtolower($record['HeatType']) != 'null') {
                    $feature_tax['Heat Included'] = 1;
                }
                if (isset($record['CableYNA']) && $record['CableYNA'] != '' && strtolower($record['CableYNA']) != 'null') {
                    $feature_tax['Cable TV Included'] = 1;
                }
                if (isset($record['ElevatorYN']) && $record['ElevatorYN'] != '' && strtolower($record['ElevatorYN']) != 'null') {
                    $feature_tax['Elevator'] = 1;
                }
                if (isset($record['Furnished']) && $record['Furnished'] != '' && strtolower($record['Furnished']) != 'null' && $record['Furnished'] !="Unfurnished" ) {
                    $feature_tax['Furnished'] = 1;
                }
                if (isset($record['WaterfrontYN']) && $record['WaterfrontYN'] != '' && strtolower($record['WaterfrontYN']) != 'null') {
                    $feature_tax['Waterfront'] = 1;
                }
                if (isset($record['ChattelsYN']) && $record['ChattelsYN'] != '' && strtolower($record['ChattelsYN']) != 'null') {
                    $feature_tax['Chattels'] = 1;
                }
                if (isset($record['FireplaceYN']) && $record['FireplaceYN'] != '' && strtolower($record['FireplaceYN']) != 'null') {
                    $feature_tax['Fireplace'] = 1;
                }
                if (isset($record['CraneYN']) && $record['CraneYN'] != '' && strtolower($record['CraneYN']) != 'null') {
                    $feature_tax['Crane'] = 1;
                }
                if (isset($record['GarageYN']) && $record['GarageYN'] != '' && strtolower($record['GarageYN']) != 'null') {
                    $feature_tax['Garage'] = 1;
                }
                if (isset($record['SpaYN']) && $record['SpaYN'] != '' && strtolower($record['SpaYN']) != 'null') {
                    $feature_tax['Spa'] = 1;
                }
                if (isset($record['BasementYN']) && $record['BasementYN'] != '' && strtolower($record['BasementYN']) != 'null') {
                    $feature_tax['Basement'] = 1;
                }
                if (isset($record['CentralVacuumYN']) && $record['CentralVacuumYN'] != '' && strtolower($record['CentralVacuumYN']) != 'null') {
                    $feature_tax['CentralVacuum'] = 1;
                }
                if (isset($record['PropertyFeatures']) && is_array($record['PropertyFeatures'])) {
                    foreach ($record['PropertyFeatures'] as $feature) {
                        if (!empty($feature) && strtolower($feature) != 'null' && strtolower($feature) != 'none') {
                            $feature_tax[$feature] = 1;
                        }
                    }
                }
                if (isset($record['Sewer']) && is_array($record['Sewer']) && !empty($record['Sewer']) && $record['Sewer'][0] !== 'None') {
                    $feature_tax['Sewer']=1;
                }
               
                $post_meta_data['fave_property_id'] = $listing_key;
                $post_meta_data['fave_mls_field_key_value'] = $listing_key;

                $add_count = 0;
                foreach ($addition_features_keys as $feature_key => $feature_title) {
                    if (isset($record[$feature_key])) {
                        if (is_array($record[$feature_key])) {
                            $record[$feature_key] = implode(', ', $record[$feature_key]);
                        }
                        if (!empty($record[$feature_key])) {
                            if ($record[$feature_key] === 'Y') {
                                $record[$feature_key] = 'Yes';
                            } elseif ($record[$feature_key] === 'N') {
                                $record[$feature_key] = 'No';
                            }
                            $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];
                            $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';
                            $add_count++;
                        }
                    }
                }
                $main_values = array(
                    'estate_featured' => 1,
                    'estate_attr_price_5' => (int) $record['ListPrice'],
                    'estate_attr_bedrooms' => $record['BedroomsTotal'],
                    'estate_attr_bathrooms' => $record['BathroomsTotalInteger'],
                    'estate_attr_property-size' => $record['LivingAreaRange'],
                    'estate_attr_year-built'=> '',
                    'estate_attr_lot-size'=>'',
                    'estate_additional_features' => $add_count,
                    'estate_location' => '',
                    'estate_plans' => '',
                    'estate_attachments' => '',
                    'estate_sidebar_elements' => '',
                    'estate_attr_price' => '',
                    'estate_video' => $record['VirtualTourURLUnbranded'],
                );

                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;
                //     }
                // }
                if(isset($record['Latitude']) && isset($record['Longitude'])){
                    $post_meta_data['houzez_geolocation_lat'] = $record['Latitude'];
                    $post_meta_data['houzez_geolocation_long'] = $record['Longitude'];
                    $post_meta_data['fave_property_location'] = $record['Latitude'] . ',' . $record['Longitude'];
                }

                insertOrUpdatePostMetaData($post_meta_data, $property_post_id);
                $all_tax = array(
                    array('name' => 'property-type', 'value' => $record['PropertyType']),
                    array('name' => 'offer-type', 'value' => $record['propertyStatus']),
                    array('name' => 'city', 'value' => $record['City']),
                    array('name' => 'zip-code', 'value' => $record['PostalCode']),
                    array('name' => 'neighborhood', 'value' => $record['propertyArea']),
                    array('name' => 'street', 'value' => $record['StreetName'])
                );
                foreach ($feature_tax as $key => $value) {
                    $all_tax[] = array('name' => 'features', 'value' => $key);
                }

                foreach ($all_tax as $term_tax) {
                    $taxonomy = $term_tax['name'];
                    $term_value = trim($term_tax['value']);
                
                    // Skip if term value is empty
                    if (empty($term_value)) {
                        continue;
                    }
                
                    // Check if the term already exists
                    $term_info = term_exists($term_value, $taxonomy);
                
                    if (is_array($term_info)) {
                        $term_id = $term_info['term_id'];
                    } else {
                        // Term doesn't exist, so insert it
                        $term_info = wp_insert_term(
                            $term_value,
                            $taxonomy,
                            array(
                                'description' => $term_value,
                            )
                        );
                
                        // Check for errors during insert
                        if (is_wp_error($term_info)) {
                            error_log('Error inserting term: ' . print_r($term_info->get_error_messages(), true));
                            continue;
                        }
                
                        $term_id = $term_info['term_id'];
                    }
                
                    // Assign the term to the post
                    wp_set_object_terms($post_id, intval($term_id), $taxonomy, true);
                }                
                $update_query = $wpdb->prepare("UPDATE $table_name SET flag = 1 ,post_id = %s WHERE $mls_key_field = %s", $post_id, $listing_key);
                $wpdb->query($update_query);
                
            }
        }
    } catch (\Exception $e) {
        echo 'Caught exception: ', $e->getMessage(), "\n";
    }
    echo "Script finished.\n";
}

echo "Property import to wordpress Ended \n";

function get_post_id_by_meta_value($meta_key, $meta_value)
{
    $posts = get_posts([
        'meta_key' => $meta_key,
        'meta_value' => $meta_value,
        'post_type' => 'any',
        'fields' => 'ids',
        'numberposts' => 1
    ]);

    return !empty($posts) ? $posts[0] : null;
}

function insertOrUpdatePostMetaData($meta_data, $post_id)
{
    global $wpdb;


    if (!is_array($meta_data) || empty($meta_data)) {
        error_log("Error: meta_data must be a non-empty array.");
        return false;
    }

    try {

        foreach ($meta_data as $meta_key => $meta_value) {

            $meta_key_sanitized = esc_sql($meta_key);
            $meta_value_sanitized = esc_sql($meta_value);


            $existing_meta = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT meta_id FROM {$wpdb->prefix}postmeta WHERE post_id = %d AND meta_key = %s",
                    $post_id,
                    $meta_key_sanitized
                )
            );


            if ($existing_meta) {
                $update_query = $wpdb->prepare(
                    "UPDATE {$wpdb->prefix}postmeta SET meta_value = %s WHERE post_id = %d AND meta_key = %s",
                    $meta_value_sanitized,
                    $post_id,
                    $meta_key_sanitized
                );
                $result = $wpdb->query($update_query);

                if ($result === false) {
                    $error_message = $wpdb->last_error;
                    error_log("Error updating post meta data for post ID $post_id: $error_message");
                    return false;
                }
            } else {

                $insert_query = $wpdb->prepare(
                    "INSERT INTO {$wpdb->prefix}postmeta (post_id, meta_key, meta_value) VALUES (%d, %s, %s)",
                    $post_id,
                    $meta_key_sanitized,
                    $meta_value_sanitized
                );
                $result = $wpdb->query($insert_query);

                if ($result === false) {
                    $error_message = $wpdb->last_error;
                    error_log("Error inserting post meta data for post ID $post_id: $error_message");
                    return false;
                }
            }
        }


        echo "MetaData added or updated for post ID $post_id\n";
        return true;

    } catch (Exception $e) {

        error_log("Exception while inserting/updating post meta data: " . $e->getMessage());
        return false;
    }
}


function upload_images_from_urls($image_urls, $post_id)
{
 
    if (!function_exists('media_handle_sideload')) {
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');
    }

    add_filter('intermediate_image_sizes_advanced',  'disable_image_resizing');

    $attachment_ids = [];
    echo "Image Upload to post is started... \n";

    foreach ($image_urls as $index => $image_url) {

        $tmp = download_url($image_url);

        if (is_wp_error($tmp)) {
            error_log('Error downloading image: ' . $tmp->get_error_message());
            continue;
        }

        $file_array = array(
            'name' => basename($image_url),
            'tmp_name' => $tmp,
        );

        if (!file_exists($tmp)) {
            error_log("Temporary file for URL {$image_url} does not exist or is inaccessible.");
            @unlink($tmp);
            continue;
        }

        $mime_type = mime_content_type($tmp);
        if (!$mime_type || strpos($mime_type, 'image/') !== 0) {
            error_log("Invalid MIME type for file {$file_array['name']} with URL {$image_url}.");
            @unlink($tmp);
            continue;
        }

        $attachment_id = media_handle_sideload($file_array, $post_id);

        if (is_wp_error($attachment_id)) {
            error_log('Error uploading image: ' . $attachment_id->get_error_message());
            @unlink($tmp);
            continue;
        }

        wp_update_post(array(
            'ID' => $attachment_id,
            'post_author' => 1,
            'post_title' => sanitize_file_name(basename($image_url)),
            'post_parent' => $post_id,
            'post_status' => 'inherit',
            'post_mime_type' => $mime_type,
        ));



   

        $attachment_ids[] = $attachment_id;


        @unlink($tmp);
    }

   
    remove_filter('intermediate_image_sizes_advanced', 'disable_image_resizing');

    echo "Image Upload to post is ended... \n";
    return $attachment_ids;
}



function disable_image_resizing($sizes)
{
    return [];
}



function delete_post_images($post_id)
{
    delete_post_thumbnail($post_id);
    $attachments = get_posts(array(
        'post_type' => 'property',
        'posts_per_page' => -1,
        'post_parent' => $post_id,
    ));

    if ($attachments) {
        foreach ($attachments as $attachment) {
            $file_path = get_attached_file($attachment->ID);
            wp_delete_attachment($attachment->ID, true);
            if (file_exists($file_path)) {
                @unlink($file_path);
            }
        }
    }

    delete_post_meta($post_id, 'fave_property_images');
    delete_post_meta($post_id, '_thumbnail_id');
    return true;
}