<?php
/* Template Name: Property Listing */
get_header();
// Check if 'property-status' is present in the URL
$getstatus = isset($_REQUEST['status']) ? sanitize_text_field($_REQUEST['status']) : '';  ?>

<section class="listing_sec">
    <div class="top_form">
        <div class="container">
            <div class="row">
                <div class="col-12">
                    <form id="property-filter-form">
                        <div class="inputs">
                            <div class="input srch">
                                <input type="text" placeholder="City , ZIP Code..." id="search-location"
                                    name="search-location">
                            </div>

                            <div class="input w-145">
                                <?php
                                // Get all terms from the 'type' taxonomy
                                $terms_type = get_terms(array(
                                    'taxonomy'   => 'type', // Replace with your taxonomy name
                                    'hide_empty' => false,  // Show even if no posts are assigned
                                )); ?>
                                <?php if (!empty($terms_type) && !is_wp_error($terms_type)) { ?>
                                <select id="property-type" name="property-type">
                                    <option selected disabled>Property Type</option>
                                    <?php foreach ($terms_type as $type) { ?>
                                    <option value="<?php echo esc_attr($type->slug); ?>">
                                        <?php echo esc_html($type->name); ?></option>
                                    <?php } ?>
                                </select>
                                <?php } ?>
                            </div>

                            
                            <div class="input">
                                <select id="property-status" name="property-status">

                                    <option disabled <?php echo empty($getstatus) ? 'selected' : ''; ?>>Status</option>
                                    <option value="coming-soon"
                                        <?php echo ($getstatus == 'coming-soon') ? 'selected' : ''; ?>>Coming Soon
                                    </option>
                                    <option value="for-lease"
                                        <?php echo ($getstatus == 'for-lease') ? 'selected' : ''; ?>>For Lease</option>
                                    <option value="for-sale"
                                        <?php echo ($getstatus == 'for-sale') ? 'selected' : ''; ?>>For Sale</option>
                                    <option value="sold" <?php echo ($getstatus == 'sold') ? 'selected' : ''; ?>>Sold
                                    </option>
                                    <option value="leased" <?php echo ($getstatus == 'leased') ? 'selected' : ''; ?>>Leased
                                    </option>
                                </select>
                            </div>

                            <?php
                            // Get all terms from the 'Country' taxonomy
                            $terms_country = get_terms(array(
                                'taxonomy'   => 'region', // Replace with your taxonomy name
                                'hide_empty' => false,  // Show even if no posts are assigned
                            )); ?>
                            <?php if (!empty($terms_country) && !is_wp_error($terms_country)) { ?>
                            <div class="input">
                                <select id="property-county" name="property-county">
                                    <option selected disabled>County</option>
                                    <?php foreach ($terms_country as $country) { ?>
                                    <option value="<?php echo esc_attr($country->slug); ?>">
                                        <?php echo esc_html($country->name); ?></option>
                                    <?php } ?>
                                </select>
                            </div>
                            <?php } ?>

                            <?php
                            // Get all terms from the 'city' taxonomy
                            $terms_city = get_terms(array(
                                'taxonomy'   => 'city', // Replace with your taxonomy name
                                'hide_empty' => false,  // Show even if no posts are assigned
                            )); ?>
                            <?php if (!empty($terms_city) && !is_wp_error($terms_city)) { ?>
                            <div class="input">
                                <select id="property-city" name="property-city">
                                    <option selected disabled>City</option>
                                    <?php foreach ($terms_city as $city) { ?>
                                    <option value="<?php echo esc_attr($city->slug); ?>">
                                        <?php echo esc_html($city->name); ?></option>
                                    <?php } ?>
                                </select>
                            </div>
                            <?php } ?>


                            <?php
                            // Get all terms from the 'property_year' taxonomy
                            $pyear = get_terms(array(
                                'taxonomy'   => 'property_year', // Replace with your taxonomy name
                                'hide_empty' => false,  // Show even if no posts are assigned
                            )); ?>
                            <?php if (!empty($pyear) && !is_wp_error($pyear)) {
                            $sorted_terms = wp_list_sort($pyear, 'name', 'ASC'); ?>
                            <div class="input">
                                <select id="property-year">
                                    <option selected disabled>Year</option>
                                    <?php foreach ($sorted_terms as $p_y) { ?>
                                    <option value="<?php echo esc_attr($p_y->slug); ?>">
                                        <?php echo esc_html($p_y->name); ?></option>
                                    <?php } ?>
                                </select>
                            </div>
                            <?php } ?>

                        </div>
                        <div class="btn_dv">
                            <a href="<?php echo esc_url( home_url( '/' ) ); ?>listing-page" class="btn">Clear Filter</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>



    <div class="lisitng" id="search-results" style="display: none;"></div>
    <div class="lisitng" id="allproperty">

        <div class="container">

            <div class="row">
                <?php $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

            $args = array(
                'post_type'      => 'property',
                'posts_per_page' => 6,
                'paged'          => $paged,
                'post_status'    => 'publish',
                'tax_query'      => array(
                    array(
                        'taxonomy' => 'status',
                        'field'    => 'slug',
                        'terms'    => $getstatus ? array($getstatus) : array('coming-soon', 'for-sale', 'for-lease', 'sold', 'closed', 'expired', 'leased', 'off-market', 'withdrawn'),
                        //'terms'    => array('coming-soon', 'for-sale', 'for-lease', 'sold'),
                        'operator' => 'IN',
                    ),
                ),
                'orderby' => 'property-year', // Order by numeric value
                'order' => 'DESC' // Change to ASC for ascending order
            );
            $loop = new WP_Query($args);
            $total_properties = $loop->found_posts; // Get the total count of matching posts
            //$property_locations = array(); // Array to store property locations ?>
                <?php if ( $loop->have_posts() ){ ?>
                <div class="col-lg-6">
                    <div class="lists">

                        <h4>All Properties</h4>
                        <div class="dtls">
                            <p><?php echo $total_properties; ?> results</p>
                            <span>Newest <img
                                    src="<?php echo get_template_directory_uri(); ?>/assets/images/dbl_arrw.png"
                                    alt=""></span>
                        </div>

                        <div id="property-list">
                            <?php while ($loop->have_posts()) : $loop->the_post();
                            $property_price = get_field('property_price');
                            $lease_price = get_field('lease_price');
                            $highlights_building_size = get_field('highlights_building_size');
                            $location = get_field('location');
                            $address = $location['street_number'] . ' ' . $location['street_name_short'] . ', ' . $location['city'] . ', ' . $location['state_short'];
                            $property_short_description = get_field('property_short_description');
                            $_lot_size = get_field( 'highlights_lot_size' );
                            $lot_size_text = get_field( 'lot_size_text', 'option' );
                            $newaddress = $location['address'] ?? '';
                            $postid = get_the_id();
                            $term_obj_list = get_the_terms( $postid, 'status' );   ?>
                            <a href="<?php the_permalink(); ?>" class="sub_dv">
                                <div class="list_card">
                                    <div class="toplistsec">
                                    <?php if (has_post_thumbnail()) { ?>
                                    <?php the_post_thumbnail('full', array('class' => 'ig')); ?>
                                    <?php } else {
                                        $all_images = array();

                                        if (have_rows('property_main_slideshow')) {
                                            while (have_rows('property_main_slideshow')) {
                                                the_row();
                                                $image = get_sub_field('property_slideshow_image');
                                                if (!empty($image)) {
                                                    $all_images[] = $image;
                                                }
                                            }
                                        }

                                        if (!empty($all_images)) {
                                            echo '<img src="' . esc_url($all_images[0]) . '" alt="Property Image" class="ig">';
                                        } 
                                        } ?>

                                        <div class="staustag">
                                            <?php  if (!empty($term_obj_list) && !is_wp_error($term_obj_list)) {
                                                $term_links = [];

                                                foreach ($term_obj_list as $term) {
                                                    $term_links[] =  esc_html($term->name);
                                                }

                                                echo implode(', ', $term_links);
                                            } ?>
                                        </div>
                                    </div>
                                    <div class="data">
                                        <h5><?php if(!empty($property_short_description)){ echo $property_short_description; }else{ ?><?php the_title(); } ?>
                                        </h5>
                                        <?php if (!empty($newaddress)) {
                                            // Split the address by commas
                                            $parts = explode(',', $newaddress);
                                            
                                            // Remove last part if it's 'USA' or contains 'USA'
                                            $last = trim(end($parts));
                                            if (strtolower($last) === 'usa') {
                                                array_pop($parts);
                                            }

                                            // Join remaining parts back into a string
                                            $cleaned_address = implode(', ', $parts);
                                            
                                            echo wpautop(esc_html($cleaned_address));
                                        } ?>

                                        <p><?php if(!empty($property_price)){ echo $property_price. '<br>'; } ?><?php if(!empty($lease_price)){ echo $lease_price; } ?></p>
                                        <?php if (!empty($highlights_building_size)) { ?><p>Building Size :
                                            <?php echo $highlights_building_size; ?></p><?php }else{ ?><p><?php echo $lot_size_text; ?> : <?php echo $_lot_size; ?></p><?php } ?>

                                    </div>
                                </div>
                            </a>
                            <?php  endwhile; ?>

                        </div>

                        <button id="load-more" data-page="1" data-max="<?php echo $loop->max_num_pages; ?>"
                            class="btn">Load More</button>
                    </div>
                </div>
                <?php }else{  ?>
                <div class="col-lg-4">
                    <div class="lists">
                        <h4>No properties found.</h4>
                    </div>
                </div>
                <?php } ?>
                <?php wp_reset_postdata(); ?>
                <?php $args1 = array(
                    'post_type'      => 'property',
                    'posts_per_page' => -1,
                    'post_status'    => 'publish',
                );
                $loop1 = new WP_Query($args1); ?>
                <?php if ( $loop1->have_posts() ){ ?>
                <div class="col-lg-5">
                    <div id="property-map" class="map">
                        <?php $property_locations = array(); 
                        while ($loop1->have_posts()) : $loop1->the_post();
                            $location = get_field('location'); // Assuming 'location' is the ACF Google Map field
                            if (!empty($location)) {
                                $property_locations[] = array(
                                    'title' => get_the_title(),
                                    'address' => esc_html($location['address']),
                                    'lat' => floatval($location['lat']),
                                    'lng' => floatval($location['lng']),
                                    'permalink' => get_permalink(),
                                );
                            }
                        endwhile; ?>

                        <script type="text/javascript">
                        var propertyLocations = <?php echo json_encode($property_locations); ?>
                        </script>
                    </div>
                </div>
                <?php } ?>
                <?php wp_reset_postdata(); ?>
            </div>

        </div>


    </div>


</section>


<?php get_footer();