HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: /var/www/html/israel-rentals/wp-content/themes/israel-rentals/functions.php
<?php
function lakewood_rentals_theme_scripts()
{
    // Bootstrap CSS
    wp_enqueue_style('bootstrap-css', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css');

    // Slick Carousel CSS
    wp_enqueue_style('slick-carousel-css', 'https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css');
    wp_enqueue_style('slick-theme-css', 'https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick-theme.css');

    wp_enqueue_style('date-picker-css', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.10.0/css/bootstrap-datepicker.standalone.min.css');

    // Custom Styles
    wp_enqueue_style('common-css', get_template_directory_uri() . '/css/common.css');
    wp_enqueue_style('header-css', get_template_directory_uri() . '/css/header.css');
    wp_enqueue_style('banner-css', get_template_directory_uri() . '/css/banner.css');
    wp_enqueue_style('listing-css', get_template_directory_uri() . '/css/listing.css');
    wp_enqueue_style('footer-css', get_template_directory_uri() . '/css/footer.css');
    wp_enqueue_style('testimonials-css', get_template_directory_uri() . '/css/testimonials.css');
    wp_enqueue_style('contact-css', get_template_directory_uri() . '/css/contact.css');
    wp_enqueue_style('add-property-modal-css', get_template_directory_uri() . '/css/add-property-modal.css');

    // JavaScript Files
    wp_enqueue_script('jquery', 'https://code.jquery.com/jquery-3.6.0.min.js', array(), '3.6.0', true);
    wp_enqueue_script('bootstrap-bundle', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.bundle.min.js', array('jquery'), '5.3.3', true);
    wp_enqueue_script('slick-carousel', 'https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js', array('jquery'), '1.8.1', true);
    wp_enqueue_script('lakewood-custom-js', get_template_directory_uri() . '/js/custom.js', array('jquery', 'slick-carousel'), null, true);
    wp_enqueue_script('parsley', 'https://cdn.jsdelivr.net/npm/parsleyjs@2.9.2/dist/parsley.min.js', array('jquery'), null, true);
    wp_enqueue_script('date-picker', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js', array('jquery'), '1.9.0', true);



    wp_localize_script('lakewood-custom-js', 'ajax_obj', array(
        'ajaxurl' => admin_url('admin-ajax.php')  // Provides the ajaxurl variable

    ));
    wp_localize_script('lakewood-custom-js', 'myTheme', array(
        'templateUrl' => get_template_directory_uri()
    ));
}


add_action('wp_enqueue_scripts', 'lakewood_rentals_theme_scripts');


function enqueue_fancybox()
{
    wp_enqueue_style('fancybox-css', 'https://cdn.jsdelivr.net/npm/@fancyapps/ui@4.0.27/dist/fancybox.css');
    wp_enqueue_script('fancybox-js', 'https://cdn.jsdelivr.net/npm/@fancyapps/ui@4.0.27/dist/fancybox.umd.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_fancybox');



function my_custom_scripts()
{
    wp_enqueue_script('jquery');
    wp_localize_script('my-script', 'myScriptData', array(
        'ajaxurl' => admin_url('admin-ajax.php'),
    ));
}
add_action('wp_enqueue_scripts', 'my_custom_scripts');
function custom_admin_styles()
{
    // Path to the CSS file
    wp_enqueue_style('custom-admin-style', get_template_directory_uri() . '/css/admin-style-custom.css');
}
add_action('admin_enqueue_scripts', 'custom_admin_styles');

function lakewood_custom_js_variables()
{
    ?>
    <script type="text/javascript">
        var slickPrevArrowURL = '<?php echo get_template_directory_uri(); ?>/img/left-slider-arrow.svg';
        var slickNextArrowURL = '<?php echo get_template_directory_uri(); ?>/img/arrow1.png';
    </script>
    <?php
}
add_action('wp_footer', 'lakewood_custom_js_variables');

function create_property_post_type()
{
    register_post_type(
        'property',
        array(
            'labels' => array(
                'name' => __('Properties'),
                'singular_name' => __('Property'),
                'add_new_item' => __('Add New Property'),
                'edit_item' => __('Edit Property'),
            ),
            'public' => true,
            'has_archive' => true,
            'supports' => array('title', 'editor', 'thumbnail'),
            'menu_position' => 5,
            'menu_icon' => 'dashicons-admin-home',
        )
    );
}
add_action('init', 'create_property_post_type');
function property_custom_fields()
{
    add_meta_box(
        'property_details',      // ID
        'Property Details',      // Title
        'property_custom_fields_callback', // Callback
        'property'               // Post type
    );
}
add_action('add_meta_boxes', 'property_custom_fields');

function property_custom_fields_callback($post)
{
    // Retrieve existing values
    $location = get_post_meta($post->ID, '_property_location', true);
    $bedrooms = get_post_meta($post->ID, '_property_bedrooms', true);
    $bathrooms = get_post_meta($post->ID, '_property_bathrooms', true);
    $garages = get_post_meta($post->ID, '_property_garages', true);
    $price = get_post_meta($post->ID, '_property_price', true);
    $utilities = get_post_meta($post->ID, '_property_utilities', true);
    $property_condition = get_post_meta($post->ID, '_property_condition', true);
    $contact_info = get_post_meta($post->ID, '_property_contact_info', true);
    $email = get_post_meta($post->ID, '_property_email', true);
    $property_sqft = get_post_meta($post->ID, '_property_sqft', true);
    // $date = get_post_meta($post->ID, '_property_date', true);
    // if (!empty($date)) {
    //     // Convert the date to yyyy-mm-dd format for the input field
    //     // $dateFormatted = DateTime::createFromFormat('m/d/Y', $date)->format('Y-m-d');
    //     $dateFormatted = DateTime::createFromFormat('m/d/Y', $date);
    //     if ($dateFormatted instanceof DateTime) {
    //         $formattedDate = $dateFormatted->format('Y-m-d');
    //     }
    // } else {
    //     $dateFormatted = '';
    // }
    // $email = get_post_meta($post->ID, '_property_email', true);
    $additional_info = get_post_meta($post->ID, '_property_additional_info', true);
    $residence_type = get_post_meta($post->ID, '_property_residence_type', true);
    $term = get_post_meta($post->ID, '_property_term', true);
    $images = get_post_meta($post->ID, '_property_images', true);

    // Property Details Form
    ?>
    <div class="form-group">
        <label for="property_location">Location:</label>
        <input class="form-control" type="text" id="property_location" name="property_location"
            value="<?php echo $location; ?>" />
    </div>
    <div class="form-group">
        <label for="property_bedrooms">Bedrooms:</label>
        <input class="form-control" type="number" id="property_bedrooms" name="property_bedrooms"
            value="<?php echo $bedrooms; ?>" />
    </div>
    <div class="form-group">
        <label for="property_bathrooms">Bathrooms:</label>
        <input class="form-control" type="number" id="property_bathrooms" name="property_bathrooms"
            value="<?php echo $bathrooms; ?>" />
    </div>

    <!-- <div class="form-group">
        <label for="property_garages">Garages:</label>
        <input class="form-control" type="number" id="property_garages" name="property_garages" value="<?php echo $garages; ?>" />
    </div> -->

    <div class="form-group">
        <label for="property_price">Price:</label>
        <input class="form-control" type="number" id="property_price" name="property_price" value="<?php echo $price; ?>" />
    </div>

    <div class="form-group">
        <label for="property_residence_type">Type of Residence:</label>
        <input type="radio" name="property_residence_type" value="House" <?php checked($residence_type, 'House'); ?> />
        House
        <input type="radio" name="property_residence_type" value="Townhouse" <?php checked($residence_type, 'Townhouse'); ?> /> Town House
        <input type="radio" name="property_residence_type" value="Apartment" <?php checked($residence_type, 'Apartment'); ?> /> Apartment
        <input type="radio" name="property_residence_type" value="Basement Apartment" <?php checked($residence_type, 'Basement Apartment'); ?> /> Basement Apartment
        <input type="radio" name="property_residence_type" value="Office" <?php checked($residence_type, 'Office'); ?> />
        Office
        <input type="radio" name="property_residence_type" value="Garages" <?php checked($residence_type, 'Garages'); ?> />
        Garages
    </div>



    <div class="form-group">
        <label for="property_term">Rental Period:</label>
        <input type="radio" name="property_term" value="Long Term" <?php checked($term, 'Long Term'); ?> /> Long Term
        <input type="radio" name="property_term" value="Short Term" <?php checked($term, 'Short Term'); ?> /> Short Term
    </div>

    <div class="form-group">
        <label for="property_utilities">Utilities:</label>
        <input type="radio" name="property_utilities" value="Included" <?php checked($utilities, 'Included'); ?> /> Included
        <input type="radio" name="property_utilities" value="Not Included" <?php checked($utilities, 'Not Included'); ?> />
        Not Included
    </div>

    <div class="form-group">
        <label for="property_condition">Property Condition:</label>
        <input type="radio" name="property_condition" value="Furnished" <?php checked($property_condition, 'Furnished'); ?> /> Furnished
        <input type="radio" name="property_condition" value="Non-Furnished" <?php checked($property_condition, 'Non-Furnished'); ?> /> Non-Furnished
        <input type="radio" name="property_condition" value="Semi-Furnished" <?php checked($property_condition, 'Semi-Furnished'); ?> /> Semi-Furnished
    </div>

    <div class="form-group">
        <label for="property_contact_info">Phone Number:</label>
        <input class="form-control" type="text" id="property_contact_info" name="property_contact_info"
            value="<?php echo $contact_info; ?>" />
    </div>

    <div class="form-group">
        <label for="property_contact_info">Email:</label>
        <input class="form-control" type="text" id="property_email" name="property_email" value="<?php echo $email; ?>" />
    </div>

    <!-- <div class="form-group">
        <label for="property_contact_info">Available Starting:</label>
        <input class="form-control" type="date" name="property_date" value="<?php echo $dateFormatted; ?>">

    </div> -->
    <div class="form-group">
        <label for="property_sqft">Sq. Feet area:</label>
        <input class="form-control" type="text" id="property_sqft" name="property_sqft"
            value="<?php echo $property_sqft; ?>" />
    </div>

    <div class="form-group">
        <label for="property_additional_info">Additional Information:</label>
        <textarea class="form-control" id="property_additional_info"
            name="property_additional_info"><?php echo $additional_info; ?></textarea>
    </div>


    <?php
}

// Save the custom fields
function save_property_custom_fields($post_id)
{
    // Save each custom field
    if (isset($_POST['property_location'])) {
        update_post_meta($post_id, '_property_location', sanitize_text_field($_POST['property_location']));
    }
    if (isset($_POST['property_bedrooms'])) {
        update_post_meta($post_id, '_property_bedrooms', sanitize_text_field($_POST['property_bedrooms']));
    }
    if (isset($_POST['property_bathrooms'])) {
        update_post_meta($post_id, '_property_bathrooms', sanitize_text_field($_POST['property_bathrooms']));
    }
    if (isset($_POST['property_garages'])) {
        update_post_meta($post_id, '_property_garages', sanitize_text_field($_POST['property_garages']));
    }
    if (isset($_POST['property_price'])) {
        update_post_meta($post_id, '_property_price', sanitize_text_field($_POST['property_price']));
    }
    if (isset($_POST['property_residence_type'])) {
        update_post_meta($post_id, '_property_residence_type', sanitize_text_field($_POST['property_residence_type']));
    }
    if (isset($_POST['property_term'])) {
        update_post_meta($post_id, '_property_term', sanitize_text_field($_POST['property_term']));
    }
    if (isset($_POST['property_utilities'])) {
        update_post_meta($post_id, '_property_utilities', sanitize_text_field($_POST['property_utilities']));
    }
    if (isset($_POST['property_condition'])) {
        update_post_meta($post_id, '_property_condition', sanitize_text_field($_POST['property_condition']));
    }
    if (isset($_POST['property_contact_info'])) {
        update_post_meta($post_id, '_property_contact_info', sanitize_text_field($_POST['property_contact_info']));
    }
    if (isset($_POST['property_email'])) {
        update_post_meta($post_id, '_property_email', sanitize_text_field($_POST['property_email']));
    }
    // if (isset($_POST['property_date'])) {
    //     update_post_meta($post_id, '_property_date', sanitize_text_field($_POST['property_date']));
    // }
    if (isset($_POST['property_sqft'])) {
        update_post_meta($post_id, '_property_sqft', sanitize_text_field($_POST['property_sqft']));
    }
    if (isset($_POST['property_additional_info'])) {
        update_post_meta($post_id, '_property_additional_info', sanitize_textarea_field($_POST['property_additional_info']));
    }



}
add_action('save_post', 'save_property_custom_fields');


function property_meta_box()
{
    add_meta_box('property_images', 'Property Images', 'property_images_callback', 'property');
}
add_action('add_meta_boxes', 'property_meta_box');

function property_images_callback($post)
{
    wp_nonce_field('save_property_images', 'property_images_nonce');

    $images = get_post_meta($post->ID, '_property_images', true);
    ?>
    <div id="property-images-container">
        <?php if (!empty($images)): ?>
            <?php foreach ($images as $image): ?>
                <div class="property-image">
                    <img src="<?php echo esc_url($image); ?>" style="width: 100px; height: auto;" />
                    <input type="hidden" name="property_images[]" value="<?php echo esc_url($image); ?>" />
                    <button class="remove-image">Remove</button>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
    <button id="upload-image" class="button">Upload Images</button>
    <input type="hidden" id="no-images" name="no_images" value="0" />
    <script>
        jQuery(document).ready(function ($) {
            var mediaUploader;
            $('#upload-image').click(function (e) {
                e.preventDefault();
                if (mediaUploader) {
                    mediaUploader.open();
                    return;
                }
                mediaUploader = wp.media({
                    title: 'Upload Images',
                    button: {
                        text: 'Add Images'
                    },
                    multiple: true // Set to true for multiple uploads
                }).on('select', function () {
                    var attachments = mediaUploader.state().get('selection').toJSON();
                    attachments.forEach(function (attachment) {
                        $('#property-images-container').append('<div class="property-image"><img src="' + attachment.url + '" style="width: 100px; height: auto;" /><input type="hidden" name="property_images[]" value="' + attachment.url + '" /><button class="remove-image">Remove</button></div>');
                    });
                }).open();
            });

            // Remove Image Button Click
            $(document).on('click', '.remove-image', function (e) {
                e.preventDefault();
                $(this).closest('.property-image').remove();

                // Check if there are no images left
                if ($('#property-images-container').children().length === 0) {
                    $('#no-images').val('1'); // Set the "no images" flag to indicate no images left
                }
            });
        });
    </script>
    <?php
}

function save_property_images($post_id)
{
    // Verify nonce
    if (!isset($_POST['property_images_nonce']) || !wp_verify_nonce($_POST['property_images_nonce'], 'save_property_images')) {
        return;
    }

    // Check if user has permission to save
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }

    // Check if "no_images" flag is set
    if (isset($_POST['no_images']) && $_POST['no_images'] == '1') {
        // No images left, delete the meta field
        delete_post_meta($post_id, '_property_images');
    } else {
        // Save the images if there are any
        if (isset($_POST['property_images']) && !empty($_POST['property_images'])) {
            update_post_meta($post_id, '_property_images', $_POST['property_images']);
        } else {
            delete_post_meta($post_id, '_property_images'); // Ensure the field is deleted if no images are left
        }
    }
}
add_action('save_post', 'save_property_images');



//----------------------------------------------------------------------------------------


//----------------------------------------------------------------------------------------

add_action('wp_ajax_add_property', 'handle_add_property_form');  // For logged-in users
add_action('wp_ajax_nopriv_add_property', 'handle_add_property_form');  // For non-logged-in users


function handle_add_property_form()
{
    // Check for nonce security or other validation
    if (!empty($_FILES['img_files'])) {
        $uploaded_files = $_FILES['img_files'];
        $image_urls = array();

        foreach ($uploaded_files['name'] as $key => $value) {
            if ($uploaded_files['name'][$key]) {
                $file = array(
                    'name' => $uploaded_files['name'][$key],
                    'type' => $uploaded_files['type'][$key],
                    'tmp_name' => $uploaded_files['tmp_name'][$key],
                    'error' => $uploaded_files['error'][$key],
                    'size' => $uploaded_files['size'][$key]
                );

                // Handle each file individually
                $upload = wp_handle_upload($file, array('test_form' => false));

                // Check for upload errors
                if (!isset($upload['error']) && isset($upload['url'])) {
                    $image_urls[] = esc_url_raw($upload['url']);  // Store uploaded image URL
                }
            }
        }

    }
    $property_name = sanitize_textarea_field($_POST['property_name']);
    $additional_info = sanitize_textarea_field($_POST['property_info']);

    // Insert data into custom post type (example)
    $property_post = array(
        'post_title' => $property_name,
        'post_content' => $additional_info,
        'post_type' => 'property', // Assuming 'property' is your custom post type
        'post_status' => 'pending', // Keep it pending for review
    );

    $post_id = wp_insert_post($property_post);

    if ($post_id) {
        // Save the image URLs to post meta
        if (!empty($image_urls)) {
            update_post_meta($post_id, '_property_images', $image_urls);
        }
        if (isset($_POST['property_location'])) {
            update_post_meta($post_id, '_property_location', sanitize_text_field($_POST['property_location']));
        }
        if (isset($_POST['property_bedrooms'])) {
            update_post_meta($post_id, '_property_bedrooms', sanitize_text_field($_POST['property_bedrooms']));
        }
        if (isset($_POST['property_bathrooms'])) {
            update_post_meta($post_id, '_property_bathrooms', sanitize_text_field($_POST['property_bathrooms']));
        }
        if (isset($_POST['property_garages'])) {
            update_post_meta($post_id, '_property_garages', sanitize_text_field($_POST['property_garages']));
        }
        if (isset($_POST['property_price'])) {
            update_post_meta($post_id, '_property_price', sanitize_text_field($_POST['property_price']));
        }
        if (isset($_POST['typeofRes'])) {
            update_post_meta($post_id, '_property_residence_type', sanitize_text_field($_POST['typeofRes']));
        }
        if (isset($_POST['property_email'])) {
            update_post_meta($post_id, '_property_email', sanitize_text_field($_POST['property_email']));
        }
        if (isset($_POST['rentalPeriod'])) {
            update_post_meta($post_id, '_property_term', sanitize_text_field($_POST['rentalPeriod']));
        }
        if (isset($_POST['utilities'])) {
            update_post_meta($post_id, '_property_utilities', sanitize_text_field($_POST['utilities']));
        }
        if (isset($_POST['property_phoneNo'])) {
            update_post_meta($post_id, '_property_contact_info', sanitize_text_field($_POST['property_phoneNo']));
        }
        if (isset($_POST['property_info'])) {
            update_post_meta($post_id, '_property_additional_info', sanitize_textarea_field($_POST['property_info']));
        }
        if (isset($_POST['property_condition'])) {
            update_post_meta($post_id, '_property_condition', sanitize_textarea_field($_POST['property_condition']));
        }
        // if (isset($_POST['property_date'])) {
        //     update_post_meta($post_id, '_property_date', sanitize_textarea_field($_POST['property_date']));
        // }
        if (isset($_POST['property_condition'])) {
            update_post_meta($post_id, '_property_condition', sanitize_textarea_field($_POST['property_condition']));
        }
        if (isset($_POST['property_sqft'])) {
            update_post_meta($post_id, '_property_sqft', sanitize_textarea_field($_POST['property_sqft']));
        }
        if (isset($_POST['property_consent'])) {
            update_post_meta($post_id, '_property_consent', sanitize_textarea_field($_POST['property_consent']));
        }
        // Email notification to admin
        $admin_email = get_option('admin_email'); // Get the admin email
        $subject = 'New Property Submission: ' . $property_name;
        $message = sprintf(
            "A new property has been submitted and is awaiting approval.\n\nTitle: %s\nLink: %s\n\nPlease review it in the admin panel.",
            $property_name,
            admin_url('post.php?post=' . $post_id . '&action=edit')
        );
        wp_mail($admin_email, $subject, $message);
        wp_send_json_success(array('message' => 'Property submitted successfully.'));
    } else {
        wp_send_json_error(array('message' => 'Property submission failed.'));
    }
}

// add_action('wp_ajax_add_property', 'add_property_function');
// add_action('wp_ajax_nopriv_add_property', 'add_property_function'); // For non-logged-in users

// function add_property_function() {
//     // Check nonce if you are using it


//     // Process your data (check for required fields, etc.)
//     if (!isset($_POST['property_name']) || empty($_POST['property_name'])) {
//         wp_send_json_error(['message' => 'Property name is required.']);
//         wp_die(); // Exit to avoid sending any additional output
//     }

//     // Proceed with data processing (e.g., saving to database)

//     // Return a success response
//     wp_send_json_success(['message' => 'Property added successfully.']);
//     wp_die(); // Exit to avoid sending any additional output
// }


// Hook the AJAX actions (for both logged-in and non-logged-in users)
add_action('wp_ajax_submit_contact_form', 'handle_ajax_contact_form');
add_action('wp_ajax_nopriv_submit_contact_form', 'handle_ajax_contact_form');

// contact form
function custom_contact_form_shortcode()
{
    ob_start();
    ?>
    <form id="custom-contact-form" class="form" data-parsley-validate>
        <div id="form-result"></div>
        <div class="row">
            <div class="col-lg-12">
                <div class="form-group">
                    <label for="cf-name" class="form-label">Name</label>
                    <input type="text" name="cf-name" id="cf-name" class="form-control" placeholder="Enter your name"
                        required data-parsley-pattern="^[a-zA-Z\s]+$" data-parsley-trigger="focusout" />
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-lg-6">
                <div class="form-group">
                    <label for="cf-email" class="form-label">Email ID</label>
                    <input type="email" name="cf-email" id="cf-email" class="form-control" placeholder="Enter Email Id"
                        required data-parsley-type="email" data-parsley-trigger="focusout" />
                </div>
            </div>
            <div class="col-lg-6">
                <div class="form-group phone">
                    <label for="cf-phone" class="form-label">Phone Number</label>
                    <div class="input-group">
                        <select class="input-group-text" required
                            data-parsley-required-message="Please select a country code.">
                            <option value="+1">+1</option>
                            <option value="+44">+44</option>
                            <option value="+61">+61</option>
                            <option value="+55">+55</option>
                            <option value="+91">+91</option>
                            <option value="+81">+81</option>
                            <option value="+33">+33</option>
                            <option value="+49">+49</option>
                            <option value="+86">+86</option>
                            <option value="+7">+7</option>
                            <option value="+39">+39</option>
                            <option value="+34">+34</option>
                            <option value="+64">+64</option>
                            <option value="+27">+27</option>
                            <option value="+52">+52</option>
                            <option value="+82">+82</option>
                            <option value="+351">+351</option>
                            <option value="+47">+47</option>
                            <option value="+65">+65</option>
                            <option value="+60">+60</option>
                            <option value="+62">+62</option>
                            <option value="+20">+20</option>
                            <option value="+234">+234</option>
                            <option value="+63">+63</option>
                            <option value="+46">+46</option>
                            <option value="+31">+31</option>
                            <option value="+32">+32</option>
                            <option value="+41">+41</option>
                        </select>
                        <input type="text" class="form-control" required name="cf-phone" id="cf-phone"
                            placeholder="Enter Ph No" data-parsley-trigger="focusout"
                            data-parsley-error-message="Please enter a valid phone number" id="countryCode"
                            data-parsley-country-code="countryCode" data-parsley-country-length="property_phoneNo">
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-lg-12">
                <div class="form-group">
                    <label for="cf-message" class="form-label">Message</label>
                    <textarea name="cf-message" id="cf-message" class="form-control" placeholder="Type here" required
                        data-parsley-minlength="10"></textarea>
                </div>
                <button class="btn btn-primary btn-submit saveContactUs" type="submit">Submit</button>
            </div>
        </div>
    </form>

    <?php
    return ob_get_clean();
}
add_shortcode('custom_contact_form', 'custom_contact_form_shortcode');


function handle_ajax_contact_form()
{
    // Sanitize input values
    $name = sanitize_text_field($_POST['cf-name']);
    $email = sanitize_email($_POST['cf-email']);
    $phone = sanitize_text_field($_POST['cf-phone']);
    $message = sanitize_textarea_field($_POST['cf-message']);

    // Email to send form data
    $to = get_option('admin_email'); // Or specify the email address
    $subject = "New contact form submission from $name";
    $headers = "From: $name <$email>" . "\r\n";

    // Construct the message
    $body = "Name: $name\nEmail: $email\nPhone: $phone\n\nMessage:\n$message";
    // Send email
    if (wp_mail($to, $subject, $body, $headers)) {
        echo 'Thank you for contacting us. We will be in touch shortly!';
    } else {
        echo 'Failed to send the message. Please try again later.';
    }

    wp_die(); // Required to terminate the AJAX request
}

// Get the search query
$search_query = get_search_query();

// Custom query to fetch property posts based on search
$args = array(
    'post_type' => 'property',
    's' => $search_query, // Use the search query
    'posts_per_page' => -1, // Number of properties to display (-1 for all)
);
$property_query = new WP_Query($args);



//--------------------------Property search--------------------------

add_action('wp_ajax_fetch_properties', 'fetch_properties');
add_action('wp_ajax_nopriv_fetch_properties', 'fetch_properties');

function fetch_properties()
{
    // Get the search query from the request
    $search_query = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';

    // Custom query to fetch property posts
    $args = array(
        'post_type' => 'property',
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key' => '_property_location',
                'value' => $search_query,
                'compare' => 'LIKE'
            ),
            array(
                'key' => '_property_residence_type',
                'value' => $search_query,
                'compare' => 'LIKE'
            ),
            array(
                'key' => '_property_bedrooms',
                'value' => $search_query,
                'compare' => 'LIKE'
            ),
            array(
                'key' => '_property_bathrooms',
                'value' => $search_query,
                'compare' => 'LIKE'
            ),
            array(
                'key' => '_property_term',
                'value' => $search_query,
                'compare' => 'LIKE'
            ),
            array(
                'key' => '_property_price',
                'value' => $search_query,
                'compare' => 'LIKE'
            ),
            array(
                'key' => '_property_additional_info',
                'value' => $search_query,
                'compare' => 'LIKE'
            ),
        ),
    );

    $property_query = new WP_Query($args);
    $total_properties = $property_query->found_posts;
    ob_start();
    // Check if there are any properties
    if ($property_query->have_posts()) {
        while ($property_query->have_posts()) {
            $property_query->the_post();
            $post_id = get_the_ID();
            // Get post meta (property data)
            $location = get_post_meta($post_id, '_property_location', true);
            $type = get_post_meta($post_id, '_property_residence_type', true);
            $bedrooms = get_post_meta($post_id, '_property_bedrooms', true);
            $bathrooms = get_post_meta($post_id, '_property_bathrooms', true);
            $term = get_post_meta($post_id, '_property_term', true);
            $price = get_post_meta($post_id, '_property_price', true);
            $additional_info = get_post_meta($post_id, '_property_additional_info', true);
            $images = get_post_meta($post_id, '_property_images', true);
            ?>
            <?php if ($_POST['searchFlag'] == 1) { ?>
                <div class="col-md-6 box">
                <?php } else { ?>
                    <div class="col-md-4 box">
                    <?php } ?>
                    <div class="property-box">
                        <div class="image-slider slick-slider">
                            <?php
                            // Loop through images if they exist (example handling of multiple image uploads)
                            if (!empty($images)) {
                                foreach ($images as $image_id) { ?>
                                    <div class="images-buttn-text">
                                        <a class="img" href="<?= get_permalink($post_id); ?>">
                                            <img src="<?= esc_url($image_id) ?>" alt="House 1" />
                                        </a>
                                        <div class="btn-text">
                                            <span><img src="<?php echo get_template_directory_uri(); ?>/img/loaction.png" /></span>
                                            <span class="loc"><?php echo esc_html($location); ?></span>
                                        </div>
                                    </div>
                                <?php }
                            }
                            ?>
                        </div>
                        <div class="property-description">
                            <div class="top-sec">
                                <div class="lt-sec"><?php echo esc_html($type); ?></div>
                                <div class="rt-sec"><?php echo esc_html($term); ?></div>
                            </div>
                            <div class="subtext"><?php the_title(); // Display property title ?></div>
                            <div class="texts"><?php echo esc_html($additional_info); ?></div>
                            <div class="prperty-detils">
                                <div class="money">
                                    <span><?php echo '$' . number_format(esc_html($price)) . '/mo'; ?></span>
                                    <!-- <span class="squre-ft">- $6.000.00/sq ft</span> -->
                                </div>
                            </div>
                        </div>
                        <div class="overlay">
                            <a href="<?= get_permalink($post_id); ?>" class="overlay-link-wrp">
                                <div class="details">
                                    <div class="property-description1">
                                        <div class="btn-text">
                                            <span><img src="<?php echo get_template_directory_uri(); ?>/img/loaction.png" /></span>
                                            <span class="loc"><?php echo esc_html($location); ?></span>
                                        </div>
                                        <div class="top-sec-btns tags">
                                            <div class="tag1"><?php echo esc_html($type); ?></div>
                                            <div class="tag1"><?php echo esc_html($term); ?></div>
                                        </div>
                                        <div class="subtext"><?php the_title(); // Display property title ?></div>
                                        <div class="texts"><?php echo esc_html($additional_info); ?></div>
                                        <div class="prperty-detils">
                                            <div class="money">
                                                <span><?php echo '$' . number_format(esc_html($price)) . '/mo'; ?></span>
                                                <!-- <span class="squre-ft">- $6.000.00/sq ft</span> -->
                                            </div>
                                        </div>
                                    </div>

                                    <div class="room-details">
                                        <!-- <div class="area">
                        <div class="head">Area</div>
                        <div class="sq-fts">2100 m2</div>
                      </div> -->
                                        <div class="area">
                                            <div class="head">Beds</div>
                                            <div class="sq-fts"><?= esc_html($bedrooms) ?></div>
                                        </div>
                                        <div class="area">
                                            <div class="head">Baths</div>
                                            <div class="sq-fts"><?= esc_html($bathrooms) ?></div>
                                        </div>
                                        <div class="area">
                                            <div class="head">Garages</div>
                                            <div class="sq-fts">1</div>
                                        </div>
                                    </div>
                                </div>
                                <div class="last-sec">
                                    <div class="rtt-secs">
                                        <span class="img-sec"><img
                                                src="<?php echo get_template_directory_uri(); ?>/img/calendar.png" /></span>
                                        <?php
                                        // Get the date when the post was published
                                        $post_date = get_the_date('U');
                                        $current_time = current_time('U');
                                        $time_diff = human_time_diff($post_date, $current_time);
                                        ?>
                                        <span><?php echo 'Listed ' . $time_diff . ' ago' ?></span>
                                    </div>
                                    <div class="lt-secs">
                                        <span><img src="<?php echo get_template_directory_uri(); ?>/img/swimming-pool.png" /></span>
                                        <span><img src="<?php echo get_template_directory_uri(); ?>/img/restaurant.png" /></span>
                                        <span><img src="<?php echo get_template_directory_uri(); ?>/img/last-ico.png" /></span>
                                    </div>
                                </div>
                            </a>
                            <div class="enquire-btn">
                                <a href="#" class="btn-enquire" data-title="<?php echo the_title(); ?>"
                                    data-post-id="<?php echo $post_id; ?>" data-location="<?php echo esc_attr($location); ?>"
                                    data-type="<?php echo esc_attr($type); ?>"
                                    data-additionalinfo="<?php echo esc_attr($additional_info); ?>">Inquire Now</a>
                            </div>
                        </div>
                    </div>
                </div>
                <?php
        }
    } else {
        echo '<p class="text-center">No properties found</p>';
    }

    // Reset Post Data
    wp_reset_postdata();

    $output = ob_get_clean();

    // Return the total properties count and the HTML response as a JSON object
    wp_send_json_success(array(
        'html' => $output,
        'total_properties' => $total_properties,
    ));

    die(); // End the AJAX request

}
add_action('wp_ajax_fetch_properties_home', 'fetch_properties_home');
add_action('wp_ajax_nopriv_fetch_properties_home', 'fetch_properties_home');

function fetch_properties_home()
{
    // Get the search query from the request
    $search_query = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';

    // Custom query to fetch property posts
    $args = array(
        'post_type' => 'property',
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key' => '_property_location',
                'value' => $search_query,
                'compare' => 'LIKE'
            ),
            array(
                'key' => '_property_residence_type',
                'value' => $search_query,
                'compare' => 'LIKE'
            ),
            array(
                'key' => '_property_bedrooms',
                'value' => $search_query,
                'compare' => 'LIKE'
            ),
            array(
                'key' => '_property_bathrooms',
                'value' => $search_query,
                'compare' => 'LIKE'
            ),
            array(
                'key' => '_property_term',
                'value' => $search_query,
                'compare' => 'LIKE'
            ),
            array(
                'key' => '_property_price',
                'value' => $search_query,
                'compare' => 'LIKE'
            ),
            array(
                'key' => '_property_additional_info',
                'value' => $search_query,
                'compare' => 'LIKE'
            ),
        ),
    );

    $property_query = new WP_Query($args);
    $total_properties = $property_query->found_posts;

    // Predefined array of residence types
    $residence_types = array('All', 'House', 'Townhouse', 'Base Apartments', 'Apartment', 'Office', 'Garages');

    // Array to hold properties by residence type
    $properties_by_type = array_fill_keys($residence_types, array());

    // Check if there are any properties
    if ($property_query->have_posts()) {
        while ($property_query->have_posts()) {
            $property_query->the_post();
            $post_id = get_the_ID();
            // Get post meta (property data)
            $type = get_post_meta($post_id, '_property_residence_type', true);

            // Store the property under its type
            if (in_array($type, $residence_types)) {
                $properties_by_type[$type][] = $post_id;
            } else {
                // If the type does not match predefined types, categorize it as 'Others'
                $properties_by_type['Others'][] = $post_id;
            }
        }
    }
    ob_start(); ?>
        <ul class="nav nav-tabs" id="propertyTab" role="tablist">
            <?php foreach ($residence_types as $type): ?>
                <li class="nav-item">
                    <a class="nav-link <?php echo $type === 'All' ? 'active' : ''; ?>"
                        id="<?php echo sanitize_title($type); ?>-tab" data-bs-toggle="tab"
                        href="#<?php echo sanitize_title($type); ?>" role="tab"
                        aria-controls="<?php echo sanitize_title($type); ?>"
                        aria-selected="<?php echo $type === 'All' ? 'true' : 'false'; ?>">
                        <?php echo esc_html($type); ?>
                    </a>
                </li>
            <?php endforeach; ?>
        </ul>

        <div class="tab-content" id="propertyTabContent">
            <!-- Tab Pane for All -->
            <div class="tab-pane fade show active" id="all" role="tabpanel" aria-labelledby="all-tab">
                <div class="row searchProperty">
                    <?php
                    // Display all properties
                    $property_query->rewind_posts(); // Reset the loop
                    if ($property_query->have_posts()) {
                        while ($property_query->have_posts()) {
                            $post_id = get_the_ID();
                            $property_query->the_post();
                            echo render_property($post_id);
                        }
                    } else {
                        echo '<p class="text-center">No properties found</p>';
                    }
                    ?>
                </div>
            </div>
            <?php foreach ($properties_by_type as $type => $posts): ?>
                <div class="tab-pane fade" id="<?php echo sanitize_title($type); ?>" role="tabpanel"
                    aria-labelledby="<?php echo sanitize_title($type); ?>-tab">
                    <div class="row searchProperty">
                        <?php if (!empty($posts)): ?>
                            <?php foreach ($posts as $post_id): ?>
                                <?php echo render_property($post_id); ?>
                            <?php endforeach; ?>
                            <div class="view-more">
                                <a href="<?= site_url('listing-page') ?>" class="view"><span>View more</span>
                                    <span><img src="<?php echo get_template_directory_uri(); ?>/img/arrow-right.png"
                                            alt="arrow-right" /></span></a>
                            </div>
                        <?php else: ?>
                            <div class="col-12">
                                <p class="text-center">No properties found</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>


    <?php $output = ob_get_clean();

    // Return the total properties count and the HTML response as a JSON object
    wp_send_json_success(array(
        'html' => $output,
        'total_properties' => $total_properties,
    ));

    die(); // End the AJAX request

}

function render_property($post_id)
{
    // Get post meta (property data)
    $location = get_post_meta($post_id, '_property_location', true);
    $type = get_post_meta($post_id, '_property_residence_type', true);
    $bedrooms = get_post_meta($post_id, '_property_bedrooms', true);
    $bathrooms = get_post_meta($post_id, '_property_bathrooms', true);
    $term = get_post_meta($post_id, '_property_term', true);
    $price = get_post_meta($post_id, '_property_price', true);
    $additional_info = get_post_meta($post_id, '_property_additional_info', true);
    $images = get_post_meta($post_id, '_property_images', true);

    ob_start(); ?>

    <div class="col-md-4 box">
        <div class="property-box">
            <div class="image-slider slick-slider">
                <?php
                // Loop through images if they exist (example handling of multiple image uploads)
                if (!empty($images)) {
                    foreach ($images as $image_id) { ?>
                        <div class="images-buttn-text">
                            <a class="img" href="<?= get_permalink($post_id); ?>">
                                <img src="<?= esc_url($image_id) ?>" alt="House 1" />
                            </a>
                            <div class="btn-text">
                                <span><img src="<?php echo get_template_directory_uri(); ?>/img/loaction.png" /></span>
                                <span class="loc"><?php echo esc_html($location); ?></span>
                            </div>
                        </div>
                    <?php }
                }
                ?>
            </div>
            <div class="property-description">
                <div class="top-sec">
                    <div class="lt-sec"><?php echo esc_html($type); ?></div>
                    <div class="rt-sec"><?php echo esc_html($term); ?></div>
                </div>
                <div class="subtext"><?php the_title(); // Display property title ?></div>
                <div class="texts"><?php echo esc_html($additional_info); ?></div>
                <div class="prperty-detils">
                    <div class="money">
                        <span><?php echo '$' . number_format(esc_html($price)) . '/mo'; ?></span>
                        <!-- <span class="squre-ft">- $6.000.00/sq ft</span> -->
                    </div>
                </div>
            </div>
            <div class="overlay">
                <a href="<?= get_permalink($post_id); ?>" class="overlay-link-wrp">
                    <div class="details">
                        <div class="property-description1">
                            <div class="btn-text">
                                <span><img src="<?php echo get_template_directory_uri(); ?>/img/loaction.png" /></span>
                                <span class="loc"><?php echo esc_html($location); ?></span>
                            </div>
                            <div class="top-sec-btns tags">
                                <div class="tag1"><?php echo esc_html($type); ?></div>
                                <div class="tag1"><?php echo esc_html($term); ?></div>
                            </div>
                            <div class="subtext"><?php the_title(); // Display property title ?></div>
                            <div class="texts"><?php echo esc_html($additional_info); ?></div>
                            <div class="prperty-detils">
                                <div class="money">
                                    <span><?php echo '$' . number_format(esc_html($price)) . '/mo'; ?></span>
                                    <!-- <span class="squre-ft">- $6.000.00/sq ft</span> -->
                                </div>
                            </div>
                        </div>

                        <div class="room-details">
                            <!-- <div class="area">
                <div class="head">Area</div>
                <div class="sq-fts">2100 m2</div>
                </div> -->
                            <div class="area">
                                <div class="head">Beds</div>
                                <div class="sq-fts"><?= esc_html($bedrooms) ?></div>
                            </div>
                            <div class="area">
                                <div class="head">Baths</div>
                                <div class="sq-fts"><?= esc_html($bathrooms) ?></div>
                            </div>
                            <div class="area">
                                <div class="head">Garages</div>
                                <div class="sq-fts">1</div>
                            </div>
                        </div>
                    </div>
                    <div class="last-sec">
                        <div class="rtt-secs">
                            <span class="img-sec"><img
                                    src="<?php echo get_template_directory_uri(); ?>/img/calendar.png" /></span>
                            <?php
                            // Get the date when the post was published
                            $post_date = get_the_date('U');
                            $current_time = current_time('U');
                            $time_diff = human_time_diff($post_date, $current_time);
                            ?>
                            <span><?php echo 'Listed ' . $time_diff . ' ago' ?></span>
                        </div>
                        <div class="lt-secs">
                            <span><img src="<?php echo get_template_directory_uri(); ?>/img/swimming-pool.png" /></span>
                            <span><img src="<?php echo get_template_directory_uri(); ?>/img/restaurant.png" /></span>
                            <span><img src="<?php echo get_template_directory_uri(); ?>/img/last-ico.png" /></span>
                        </div>
                    </div>
                </a>
                <div class="enquire-btn">
                    <a href="#" class="btn-enquire" data-title="<?php echo the_title(); ?>"
                        data-post-id="<?php echo $post_id; ?>" data-location="<?php echo esc_attr($location); ?>"
                        data-type="<?php echo esc_attr($type); ?>"
                        data-additionalinfo="<?php echo esc_attr($additional_info); ?>">Inquire Now</a>
                </div>
            </div>
        </div>
    </div>
    <?php return ob_get_clean();
}
add_action('wp_ajax_filter_properties', 'filter_properties');
add_action('wp_ajax_nopriv_filter_properties', 'filter_properties');

function filter_properties()
{
    // Get filter inputs from the AJAX request
    $property_types = isset($_POST['property_types']) ? $_POST['property_types'] : [];
    $rental_periods = isset($_POST['rental_periods']) ? $_POST['rental_periods'] : [];
    $utilities = isset($_POST['utilities']) ? $_POST['utilities'] : [];
    $property_conditions = isset($_POST['property_conditions']) ? $_POST['property_conditions'] : [];

    // Build custom query arguments
    $args = array(
        'post_type' => 'property', // Change this to your custom post type
        'posts_per_page' => -1,
        'post_status' => 'publish',
        'meta_query' => array('relation' => 'AND')
    );

    // Filter by property types
    if (!empty($property_types)) {
        $args['meta_query'][] = array(
            'key' => '_property_residence_type', // Adjust to your custom field
            'value' => $property_types,
            'compare' => 'IN',
        );
    }

    // Filter by listing types
    if (!empty($rental_periods)) {
        $args['meta_query'][] = array(
            'key' => '_property_term', // Adjust to your custom field
            'value' => $rental_periods,
            'compare' => 'IN',
        );
    }

    // Filter by area types
    if (!empty($utilities)) {
        $args['meta_query'][] = array(
            'key' => '_property_utilities', // Adjust to your custom field
            'value' => $utilities,
            'compare' => 'IN',
        );
    }
    if (!empty($property_conditions)) {
        $args['meta_query'][] = array(
            'key' => '_property_condition', // Adjust to your custom field
            'value' => $property_conditions,
            'compare' => 'IN',
        );
    }

    // Custom query to fetch property posts
    $property_query = new WP_Query($args);
    $total_properties = $property_query->found_posts;
    ob_start();

    // Check if there are any properties
    if ($property_query->have_posts()) {
        while ($property_query->have_posts()) {
            $property_query->the_post();
            $post_id = get_the_ID();
            // Get post meta (property data)
            $location = get_post_meta($post_id, '_property_location', true);
            $type = get_post_meta($post_id, '_property_residence_type', true);
            $bedrooms = get_post_meta($post_id, '_property_bedrooms', true);
            $bathrooms = get_post_meta($post_id, '_property_bathrooms', true);
            $term = get_post_meta($post_id, '_property_term', true);
            $price = get_post_meta($post_id, '_property_price', true);
            $additional_info = get_post_meta($post_id, '_property_additional_info', true);
            $images = get_post_meta($post_id, '_property_images', true);
            ?>
            <div class="col-md-6 box">
                <div class="property-box">
                    <div class="image-slider slick-slider">
                        <?php
                        // Loop through images if they exist (example handling of multiple image uploads)
                        if (!empty($images)) {
                            foreach ($images as $image_id) { ?>
                                <div class="images-buttn-text">
                                    <a class="img" href="<?= get_permalink($post_id); ?>">
                                        <img src="<?= esc_url($image_id) ?>" alt="House 1" />
                                    </a>
                                    <div class="btn-text">
                                        <span><img src="<?php echo get_template_directory_uri(); ?>/img/loaction.png" /></span>
                                        <span class="loc"><?php echo esc_html($location); ?></span>
                                    </div>
                                </div>
                            <?php }
                        }
                        ?>
                    </div>
                    <div class="property-description">
                        <div class="top-sec">
                            <div class="lt-sec"><?php echo esc_html($type); ?></div>
                            <div class="rt-sec"><?php echo esc_html($term); ?></div>
                        </div>
                        <div class="subtext"><?php the_title(); // Display property title ?></div>
                        <div class="texts"><?php echo esc_html($additional_info); ?></div>
                        <div class="prperty-detils">
                            <div class="money">
                                <span><?php echo '$' . number_format(esc_html($price)) . '/mo'; ?></span>
                                <!-- <span class="squre-ft">- $6.000.00/sq ft</span> -->
                            </div>
                        </div>
                    </div>
                    <div class="overlay">
                        <a href="<?= get_permalink($post_id); ?>" class="overlay-link-wrp">
                            <div class="details">
                                <div class="property-description1">
                                    <div class="btn-text">
                                        <span><img src="<?php echo get_template_directory_uri(); ?>/img/loaction.png" /></span>
                                        <span class="loc"><?php echo esc_html($location); ?></span>
                                    </div>
                                    <div class="top-sec-btns tags">
                                        <div class="tag1"><?php echo esc_html($type); ?></div>
                                        <div class="tag1"><?php echo esc_html($term); ?></div>
                                    </div>
                                    <div class="subtext"><?php the_title(); // Display property title ?></div>
                                    <div class="texts"><?php echo esc_html($additional_info); ?></div>
                                    <div class="prperty-detils">
                                        <div class="money">
                                            <span><?php echo '$' . number_format(esc_html($price)) . '/mo'; ?></span>
                                            <!-- <span class="squre-ft">- $6.000.00/sq ft</span> -->
                                        </div>
                                    </div>
                                </div>

                                <div class="room-details">
                                    <!-- <div class="area">
                        <div class="head">Area</div>
                        <div class="sq-fts">2100 m2</div>
                      </div> -->
                                    <div class="area">
                                        <div class="head">Beds</div>
                                        <div class="sq-fts"><?= esc_html($bedrooms) ?></div>
                                    </div>
                                    <div class="area">
                                        <div class="head">Baths</div>
                                        <div class="sq-fts"><?= esc_html($bathrooms) ?></div>
                                    </div>
                                    <div class="area">
                                        <div class="head">Garages</div>
                                        <div class="sq-fts">1</div>
                                    </div>
                                </div>
                            </div>
                            <div class="last-sec">
                                <div class="rtt-secs">
                                    <span class="img-sec"><img
                                            src="<?php echo get_template_directory_uri(); ?>/img/calendar.png" /></span>
                                    <?php
                                    // Get the date when the post was published
                                    $post_date = get_the_date('U');
                                    $current_time = current_time('U');
                                    $time_diff = human_time_diff($post_date, $current_time);
                                    ?>
                                    <span><?php echo 'Listed ' . $time_diff . ' ago' ?></span>
                                </div>
                                <div class="lt-secs">
                                    <span><img src="<?php echo get_template_directory_uri(); ?>/img/swimming-pool.png" /></span>
                                    <span><img src="<?php echo get_template_directory_uri(); ?>/img/restaurant.png" /></span>
                                    <span><img src="<?php echo get_template_directory_uri(); ?>/img/last-ico.png" /></span>
                                </div>
                            </div>
                        </a>
                        <div class="enquire-btn">
                            <a href="#" class="btn-enquire" data-title="<?php echo the_title(); ?>"
                                data-post-id="<?php echo $post_id; ?>" data-location="<?php echo esc_attr($location); ?>"
                                data-type="<?php echo esc_attr($type); ?>"
                                data-additionalinfo="<?php echo esc_attr($additional_info); ?>">Inquire Now</a>
                        </div>
                    </div>
                </div>
            </div>
            <?php
        }
    } else {
        echo '<p class="text-center">No properties found</p>';
    }

    // Reset Post Data
    wp_reset_postdata();
    $output = ob_get_clean();

    // Return the total properties count and the HTML response as a JSON object
    wp_send_json_success(array(
        'html' => $output,
        'total_properties' => $total_properties,
    ));

    die(); // End the AJAX request
}

function filter_properties_by_sort()
{
    $sort_by = isset($_POST['sort_by']) ? sanitize_text_field($_POST['sort_by']) : '';

    // Setup query arguments for sorting
    $args = array(
        'post_type' => 'property',
        'posts_per_page' => -1,
        'post_status' => 'publish',
    );

    if ($sort_by == 'date_desc') {
        // Sort by post date (newest to oldest)
        $args['orderby'] = 'date';
        $args['order'] = 'DESC';
    } elseif ($sort_by == 'year_desc') {
        // Sort by year (newest year to oldest year)
        $args['orderby'] = 'date';
        $args['order'] = 'ASC';
    }

    // Custom query to fetch property posts
    $property_query = new WP_Query($args);
    $total_properties = $property_query->found_posts;
    ob_start();

    // Check if there are any properties
    if ($property_query->have_posts()) {
        while ($property_query->have_posts()) {
            $property_query->the_post();
            $post_id = get_the_ID();
            // Get post meta (property data)
            $location = get_post_meta($post_id, '_property_location', true);
            $type = get_post_meta($post_id, '_property_residence_type', true);
            $bedrooms = get_post_meta($post_id, '_property_bedrooms', true);
            $bathrooms = get_post_meta($post_id, '_property_bathrooms', true);
            $term = get_post_meta($post_id, '_property_term', true);
            $price = get_post_meta($post_id, '_property_price', true);
            $additional_info = get_post_meta($post_id, '_property_additional_info', true);
            $images = get_post_meta($post_id, '_property_images', true);
            ?>
            <div class="col-md-6 box">
                <div class="property-box">
                    <div class="image-slider slick-slider">
                        <?php
                        // Loop through images if they exist (example handling of multiple image uploads)
                        if (!empty($images)) {
                            foreach ($images as $image_id) { ?>
                                <div class="images-buttn-text">
                                    <a class="img" href="<?= get_permalink($post_id); ?>">
                                        <img src="<?= esc_url($image_id) ?>" alt="House 1" />
                                    </a>
                                    <div class="btn-text">
                                        <span><img src="<?php echo get_template_directory_uri(); ?>/img/loaction.png" /></span>
                                        <span class="loc"><?php echo esc_html($location); ?></span>
                                    </div>
                                </div>
                            <?php }
                        }
                        ?>
                    </div>
                    <div class="property-description">
                        <div class="top-sec">
                            <div class="lt-sec"><?php echo esc_html($type); ?></div>
                            <div class="rt-sec"><?php echo esc_html($term); ?></div>
                        </div>
                        <div class="subtext"><?php the_title(); // Display property title ?></div>
                        <div class="texts"><?php echo esc_html($additional_info); ?></div>
                        <div class="prperty-detils">
                            <div class="money">
                                <span><?php echo '$' . number_format(esc_html($price)) . '/mo'; ?></span>
                                <!-- <span class="squre-ft">- $6.000.00/sq ft</span> -->
                            </div>
                        </div>
                    </div>
                    <div class="overlay">
                        <a href="<?= get_permalink($post_id); ?>" class="overlay-link-wrp">
                            <div class="details">
                                <div class="property-description1">
                                    <div class="btn-text">
                                        <span><img src="<?php echo get_template_directory_uri(); ?>/img/loaction.png" /></span>
                                        <span class="loc"><?php echo esc_html($location); ?></span>
                                    </div>
                                    <div class="top-sec-btns tags">
                                        <div class="tag1"><?php echo esc_html($type); ?></div>
                                        <div class="tag1"><?php echo esc_html($term); ?></div>
                                    </div>
                                    <div class="subtext"><?php the_title(); // Display property title ?></div>
                                    <div class="texts"><?php echo esc_html($additional_info); ?></div>
                                    <div class="prperty-detils">
                                        <div class="money">
                                            <span><?php echo '$' . number_format(esc_html($price)) . '/mo'; ?></span>
                                            <!-- <span class="squre-ft">- $6.000.00/sq ft</span> -->
                                        </div>
                                    </div>
                                </div>

                                <div class="room-details">
                                    <!-- <div class="area">
                        <div class="head">Area</div>
                        <div class="sq-fts">2100 m2</div>
                      </div> -->
                                    <div class="area">
                                        <div class="head">Beds</div>
                                        <div class="sq-fts"><?= esc_html($bedrooms) ?></div>
                                    </div>
                                    <div class="area">
                                        <div class="head">Baths</div>
                                        <div class="sq-fts"><?= esc_html($bathrooms) ?></div>
                                    </div>
                                    <div class="area">
                                        <div class="head">Garages</div>
                                        <div class="sq-fts">1</div>
                                    </div>
                                </div>
                            </div>
                            <div class="last-sec">
                                <div class="rtt-secs">
                                    <span class="img-sec"><img
                                            src="<?php echo get_template_directory_uri(); ?>/img/calendar.png" /></span>
                                    <?php
                                    // Get the date when the post was published
                                    $post_date = get_the_date('U');
                                    $current_time = current_time('U');
                                    $time_diff = human_time_diff($post_date, $current_time);
                                    ?>
                                    <span><?php echo 'Listed ' . $time_diff . ' ago' ?></span>
                                </div>
                                <div class="lt-secs">
                                    <span><img src="<?php echo get_template_directory_uri(); ?>/img/swimming-pool.png" /></span>
                                    <span><img src="<?php echo get_template_directory_uri(); ?>/img/restaurant.png" /></span>
                                    <span><img src="<?php echo get_template_directory_uri(); ?>/img/last-ico.png" /></span>
                                </div>
                            </div>
                        </a>
                        <div class="enquire-btn">
                            <a href="#" class="btn-enquire" data-title="<?php echo the_title(); ?>"
                                data-post-id="<?php echo $post_id; ?>" data-location="<?php echo esc_attr($location); ?>"
                                data-type="<?php echo esc_attr($type); ?>"
                                data-additionalinfo="<?php echo esc_attr($additional_info); ?>">Inquire Now</a>
                        </div>
                    </div>
                </div>
            </div>
            <?php
        }
    } else {
        echo '<p class="text-center">No properties found</p>';
    }


    // Reset Post Data
    wp_reset_postdata();
    $output = ob_get_clean();

    // Return the total properties count and the HTML response as a JSON object
    wp_send_json_success(array(
        'html' => $output,
        'total_properties' => $total_properties,
    ));

    die(); // End the AJAX request
}
add_action('wp_ajax_filter_properties_by_sort', 'filter_properties_by_sort');
add_action('wp_ajax_nopriv_filter_properties_by_sort', 'filter_properties_by_sort');

//----------------------------------------News letter---------------------------------
// Enqueue the script and localize the ajax URL
function enqueue_newsletter_script()
{
    wp_enqueue_script('newsletter-script', get_template_directory_uri() . '/js/newsletter.js', array('jquery'), null, true);

    // Localize the script to make the ajaxurl accessible in JavaScript
    wp_localize_script('newsletter-script', 'myAjax', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'enqueue_newsletter_script');

// Handle the AJAX request for subscribing to the newsletter
function newsletter_subscribe()
{
    // Get the email address from the AJAX request
    $email = sanitize_email($_POST['email']);

    // Basic email validation
    if (!is_email($email)) {
        echo 'Invalid email address.';
        wp_die();
    }

    // Add the email to the database (example using wp_options)
    $subscribers = get_option('newsletter_subscribers', []);
    if (!in_array($email, $subscribers)) {
        $subscribers[] = $email;
        update_option('newsletter_subscribers', $subscribers);
        wp_send_json_success(array('message' => 'Thank you for subscribing!'));
    } else {
        wp_send_json_error(array('message' => 'You are already subscribed!'));
    }

    wp_die(); // Required to end the AJAX request
}
add_action('wp_ajax_newsletter_subscribe', 'newsletter_subscribe');
add_action('wp_ajax_nopriv_newsletter_subscribe', 'newsletter_subscribe');


//------Register the Custom REST API Endpoint-------------------------------------

add_action('rest_api_init', function () {
    register_rest_route('ywn/v1', '/publish/', [
        'methods' => 'POST',
        'callback' => 'ywn_publish_article',
        'permission_callback' => '__return_true'
    ]);
});

function ywn_publish_article($request)
{
    return rest_ensure_response([
        'message' => '✅ API is working!',
        'data' => $request->get_json_params()
    ]);
}


// add_action('rest_api_init', function () {
//     register_rest_route('ywn/v1', '/publish/', [
//         'methods' => 'POST',
//         'callback' => 'ywn_publish_article',
//         'permission_callback' => 'ywn_api_permission_check',
//         'args' => [
//             'title' => ['required' => true],
//             'content' => ['required' => true],
//             'category' => ['required' => false],
//             'image_url' => ['required' => false],
//         ]
//     ]);
// });

// function ywn_publish_article($request)
// {
//     $params = $request->get_json_params();

//     $title = sanitize_text_field($params['title']);
//     $content = wp_kses_post($params['content']);
//     $category = isset($params['category']) ? intval($params['category']) : null;
//     $image_url = isset($params['image_url']) ? esc_url_raw($params['image_url']) : null;

//     // Set up the post data
//     $post_data = [
//         'post_title' => $title,
//         'post_content' => $content,
//         'post_status' => 'publish',
//         'post_type' => 'post',
//     ];

//     if ($category) {
//         $post_data['post_category'] = [$category];
//     }

//     // Insert the post
//     $post_id = wp_insert_post($post_data);

//     if (is_wp_error($post_id)) {
//         return new WP_Error('post_error', 'Failed to create post', ['status' => 500]);
//     }

//     // If there's an image URL, download and set it as featured image
//     if ($image_url) {
//         $image_id = ywn_download_and_attach_image($image_url, $post_id);
//         if (!is_wp_error($image_id)) {
//             set_post_thumbnail($post_id, $image_id);
//         }
//     }

//     return [
//         'success' => true,
//         'post_id' => $post_id,
//         'edit_link' => get_edit_post_link($post_id)
//     ];
// }

// function ywn_download_and_attach_image($image_url, $post_id)
// {
//     require_once ABSPATH . 'wp-admin/includes/file.php';
//     require_once ABSPATH . 'wp-admin/includes/media.php';
//     require_once ABSPATH . 'wp-admin/includes/image.php';

//     $tmp = download_url($image_url);

//     if (is_wp_error($tmp)) {
//         return $tmp;
//     }

//     $file_array = [
//         'name' => basename($image_url),
//         'tmp_name' => $tmp
//     ];

//     // Upload the image to media library
//     $image_id = media_handle_sideload($file_array, $post_id);

//     if (is_wp_error($image_id)) {
//         @unlink($tmp); // cleanup temp file
//     }

//     return $image_id;
// }