HEX
Server: nginx/1.24.0
System: Linux DGT-WORDPRESS-VM-SERVER 6.14.0-1014-azure #14~24.04.1-Ubuntu SMP Fri Oct 3 20:52:11 UTC 2025 x86_64
User: ubuntu (1000)
PHP: 8.4.12
Disabled: NONE
Upload Files
File: /mnt/data/dreamsrent-wp-demo/wp-content/themes/dreamsrent/templates/rental-list.php
<?php 

/**
 * Template Name: Rental List Template
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site will use a
 * different template.
 *
 * @package Dreamsrent
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Store search parameters in session
if (isset($_GET['location'])) {
    $_SESSION['location'] = $_GET['location'];
}
if (isset($_GET['location_drop'])) {
    $_SESSION['location_drop'] = $_GET['location_drop'];
}
if (isset($_GET['pickup_date'])) {
    $_SESSION['pickup_date'] = $_GET['pickup_date'];
}
if (isset($_GET['pickup_time'])) {
    $_SESSION['pickup_time'] = $_GET['pickup_time'];
}
if (isset($_GET['return_date'])) {
    $_SESSION['return_date'] = $_GET['return_date'];
}
if (isset($_GET['return_time'])) {
    $_SESSION['return_time'] = $_GET['return_time'];
}

get_header(); 
 
  ?>
<div class="sortby-sec">
			<div class="container">
				<div class="sorting-div">
					<div class="row d-flex align-items-center">
						<div class="col-xl-4 col-lg-3 col-sm-12 col-12">
						<?php
								$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
								$posts_per_page = isset($_GET['posts_per_page']) ? intval($_GET['posts_per_page']) : 8;

								$args = array(
									'post_type'      => 'rental',
									'paged'          => $paged,
									'posts_per_page' => $posts_per_page,
									'tax_query'      => array(),
									'meta_query'     => array(),
								);
								$custom_query = new WP_Query($args);
								$start_result = ($paged - 1) * $posts_per_page + 1;
								$end_result = min($paged * $posts_per_page, $custom_query->found_posts);
								?>
								<div class="count-search">
									<p><?php echo esc_html__('Showing', 'dreamsrent') ?> <span><?php echo esc_html($start_result . '-' . $end_result); ?></span><?php echo esc_html__(' of ', 'dreamsrent') ?> <?php echo esc_html($custom_query->found_posts); ?><?php echo esc_html__(' Results', 'dreamsrent') ?> </p>
								</div>
								<?php
								wp_reset_postdata();
								?>
						</div>
						<div class="col-xl-8 col-lg-9 col-sm-12 col-12">
							<div class="product-filter-group">
								<div class="sortbyset">
									<span class="sortbytitle"><?php echo esc_html__('Show :' , 'dreamsrent') ?>  </span>
									<div class="sorting-select select-one">
										<?php $posts_per_page = isset($_GET['posts_per_page']) ? intval($_GET['posts_per_page']) : 0; ?>
										<form method="get" action="">
										<select class="form-control select" name="posts_per_page" onchange="this.form.submit()">
											<option value="8" <?php selected($posts_per_page, 8); ?>><?php echo esc_html__('8', 'dreamsrent') ?></option>
											<option value="10" <?php selected($posts_per_page, 10); ?>><?php echo esc_html__('10', 'dreamsrent') ?></option>
											<option value="12" <?php selected($posts_per_page, 12); ?>><?php echo esc_html__('12', 'dreamsrent') ?></option>
										</select>
									</form>
																		</div>
                                    <span class="sortbytitle"><?php echo esc_html__('Sort By :', 'dreamsrent') ?>  </span>

									<div class="sorting-select select-two">
                                    <form method="get" action="">
										<?php $sort_order = isset($_GET['sort']) ? $_GET['sort'] : ''; ?>
    <select class="form-control select" name="sort" onchange="this.form.submit()">
    <option value="popularity" <?php selected($sort_order, 'popularity'); ?>><?php echo esc_html__('Popularity', 'dreamsrent'); ?></option>

        <option value="low_to_high" <?php selected($sort_order, 'low_to_high'); ?>><?php echo esc_html__('Low to High', 'dreamsrent'); ?></option>
        <option value="high_to_low" <?php selected($sort_order, 'high_to_low'); ?>><?php echo esc_html__('High to Low', 'dreamsrent'); ?></option>

    </select>
</form>
									</div>
									 
								</div>
								<div class="grid-listview">
									<ul>
									<li>
											<a href="<?php echo esc_url(home_url('/rental-grid')); ?>" >
												<i class="feather-grid"></i>
											</a>
										</li>
										<li>
											<a href="<?php echo esc_url(home_url('/rental-list')); ?>" class="active">
												<i class="feather-list"></i>
											</a>
										</li>
									</ul>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>


		<section class="section car-listing"  >
			<div class="container" >
				<div class="row" >
                <div class="col-lg-3 col-12 theiaStickySidebar">
				<form id="filterForm" action="" method="post" class="sidebar-form" onsubmit="handleFormSubmission()">

						
                    <!-- Customer -->
                    <div class="sidebar-heading">
                        <h3><?php echo esc_html__('What Are You Looking For', 'dreamsrent'); ?></h3>
                    </div>
                    <div class="product-search">								
                        <div class="form-custom">														
                            <input type="text" class="form-control" name="search_keyword" >
                            <span><img src="<?php echo esc_url(get_template_directory_uri()); ?>/assets/images/search.svg" alt="Search"></span>

                        </div>
                    </div>

                        <div class="sidebar-heading">
                            <h3><?php echo esc_html__('Location', 'dreamsrent'); ?></h3>
                        </div>
                        <div class="product-search">								
                            <div class="form-custom">														
                            <select name="location" class="select form-control">
                            <option value=""><?php echo esc_html__('Select Location', 'dreamsrent'); ?></option>
                            <?php

                            $terms = get_terms(array(
                                'taxonomy'   => 'location',
                                'hide_empty' => false,
                            ));
                            if($terms){
                            foreach ($terms as $term) {
                                $selected = '';
                                if (isset($_GET['location']) && $_GET['location'] == $term->name) {
                                    $selected = 'selected';
                                }
                                ?>
                                <!-- <option value="<?php echo esc_html($term->name); ?>"><?php echo esc_html($term->name); ?></option> -->
                                <option value="<?php echo esc_html($term->name); ?>" <?php echo esc_html($selected); ?>><?php echo esc_html($term->name); ?></option>

                                <?php
                            }}
                            ?>
                        </select>
                                

                            </div>
                        </div>

                                <div class="accordion" id="accordionMain1">
                                    <div class="card-header-new" id="headingOne">
                                        <h6 class="filter-title">
                                            <a href="javascript:void(0);" class="w-100 collapsed" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                                            <?php echo esc_html__('Car Category', 'dreamsrent'); ?>	
                                                <span class="float-end"><i class="fa-solid fa-chevron-down"></i></span>
                                            </a> 
                                        </h6>
                                    </div>
                                    <div id="collapseOne" class="collapse" aria-labelledby="headingOne"  data-bs-parent="#accordionExample1">
                                        <div class="card-body-chat">
                                            <div class="row">
                                                <div class="col-md-12">
                                                    <div id="checkBoxes1">
                                                    <?php
                                                    
                                                    $carcategory = get_terms(array(
                                                        'taxonomy'   => 'carcategory',
                                                        'hide_empty' => false,
                                                    ));
                                                    
                                                    
                                                    if ($carcategory && !is_wp_error($carcategory)) {
                                                        foreach ($carcategory as $carcategorys) {
                                                            
                                                            ?>
                                                            <label class="custom_check w-100">
                                                                <input type="checkbox" name="carcategory[]" value="<?php echo esc_html($carcategorys->slug); ?>">
                                                                <span class="checkmark"></span><?php echo esc_html($carcategorys->name); ?>
                                                            </label>
                                                            <?php
                                                        }
                                                    }
                                                    ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <!-- /Customer -->

                                <div class="accordion" id="accordionMain2">
                                    <div class="card-header-new" id="headingTwo">
                                        <h6 class="filter-title">
                                            <a href="javascript:void(0);" class="w-100 collapsed"  data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">
                                            <?php echo esc_html__('Car Type', 'dreamsrent'); ?>
                                                <span class="float-end"><i class="fa-solid fa-chevron-down"></i></span>
                                            </a> 
                                        </h6>
                                    </div>
                                    <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo"  data-bs-parent="#accordionExample2">
                                        <div class="card-body-chat">
                                            <div id="checkBoxes2">
                                            <?php
                                                    
                                                    $cartype = get_terms(array(
                                                        'taxonomy'   => 'cartype',
                                                        'hide_empty' => false,
                                                    ));

                                                    if ($cartype && !is_wp_error($cartype)) {
                                                        foreach ($cartype as $cartypes) {
                                                            ?>
                                                            <label class="custom_check w-100">
                                                                <input type="checkbox" name="cartypes[]" value="<?php echo esc_html($cartypes->slug); ?>">
                                                                <span class="checkmark"></span><?php echo esc_html($cartypes->name); ?>
                                                            </label>
                                                            <?php
                                                        }
                                                    }
                                                    ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- By Status -->
                                <div class="accordion" id="accordionMain3">
                                    <div class="card-header-new" id="headingThree">
                                        <h6 class="filter-title">
                                            <a href="javascript:void(0);" class="w-100 collapsed"  data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="true" aria-controls="collapseThree">
                                            <?php echo esc_html__('Capacity', 'dreamsrent'); ?>
                                                <span class="float-end"><i class="fa-solid fa-chevron-down"></i></span>
                                            </a> 
                                        </h6>
                                    </div>
                                    <div id="collapseThree" class="collapse" aria-labelledby="headingThree"  data-bs-parent="#accordionExample3">
                                        <div class="card-body-chat">
                                            <div id="checkBoxes3">
                                            <?php
                                                    
                                                    $carcapacity = get_terms(array(
                                                        'taxonomy'   => 'carcapacity',
                                                        'hide_empty' => false,
                                                    ));

                                                    if ($carcapacity && !is_wp_error($carcapacity)) {
                                                        foreach ($carcapacity as $carcapacitys) {
                                                            ?>
                                                            <label class="custom_check w-100">
                                                                <input type="checkbox" name="carcapacity[]" value="<?php echo esc_html($carcapacitys->slug); ?>">
                                                                <span class="checkmark"></span><?php echo esc_html($carcapacitys->name); ?>
                                                            </label>
                                                            <?php
                                                        }
                                                    }
                                                    ?>
                                            </div>	
                                        </div>
                                    </div>
                                </div>
                                <!-- /By Status -->

                                <!-- By Car Year -->
                                <div class="accordion" id="accordionMain3">
                                                                <div class="card-header-new" id="headingThree">
                                                                    <h6 class="filter-title">
                                                                        <a href="javascript:void(0);" class="w-100 collapsed"  data-bs-toggle="collapse" data-bs-target="#collapsecarmake" aria-expanded="true" aria-controls="collapsecarmake">
                                                                        <?php echo esc_html__('Car Make Year', 'dreamsrent'); ?>
                                                                            <span class="float-end"><i class="fa-solid fa-chevron-down"></i></span>
                                                                        </a> 
                                                                    </h6>
                                                                </div>
                                                                <div id="collapsecarmake" class="collapse" aria-labelledby="headingThree"  data-bs-parent="#accordionExample3">
                                                                    <div class="card-body-chat">
                                                                        <div id="checkBoxes3">
                                                                        <?php
                                                                        $car_years = array(); 

                                                                        $args = array(
                                                                            'post_type'      => 'rental', 
                                                                            'posts_per_page' => -1,
                                                                            'meta_query'     => array(
                                                                                'relation' => 'AND',
                                                                                array(
                                                                                    'key'     => 'dreams_booking_meta_make_year',
                                                                                    'compare' => 'IN',
                                                                                    'type'    => 'NUMERIC',
                                                                                ),
                                                                            ),
                                                                        );

                                                                        $car_posts = new WP_Query($args);

                                                                        if ($car_posts->have_posts()) {
                                                                            while ($car_posts->have_posts()) {
                                                                                $car_posts->the_post();
                                                                                $car_year = get_post_meta(get_the_ID(), 'dreams_booking_meta_make_year', true);
                                                                                if (!in_array($car_year, $car_years)) {
                                                                                    $car_years[] = $car_year;
                                                                                }
                                                                            }
                                                                            wp_reset_postdata();

                                                                            foreach ($car_years as $car_year) {
                                                                                ?>
                                                                                <label class="custom_check w-100">
                                                                                    <input type="checkbox" name="carmakeyear[]" value="<?php echo esc_html($car_year); ?>">
                                                                                    <span class="checkmark"></span><?php echo esc_html($car_year); ?>
                                                                                </label>
                                                                                <?php
                                                                            }
                                                                        }
                                                                        ?>



                                                                        </div>	
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <!-- /By Car Make Year -->

                                                            <!-- By Car Fuel Type -->
                                                            <div class="accordion" id="accordionMain3">
                                                                <div class="card-header-new" id="headingThree">
                                                                    <h6 class="filter-title">
                                                                        <a href="javascript:void(0);" class="w-100 collapsed"  data-bs-toggle="collapse" data-bs-target="#carfueltype" aria-expanded="true" aria-controls="carfueltype">
                                                                        <?php echo esc_html__('Car Fuel Type', 'dreamsrent'); ?>
                                                                            <span class="float-end"><i class="fa-solid fa-chevron-down"></i></span>
                                                                        </a> 
                                                                    </h6>
                                                                </div>
                                                                <div id="carfueltype" class="collapse" aria-labelledby="headingThree"  data-bs-parent="#accordionExample3">
                                                                    <div class="card-body-chat">
                                                                        <div id="checkBoxes3">
                                                                        <?php
                                                                                
                                                                                $carfueltype = get_terms(array(
                                                                                    'taxonomy'   => 'carfueltype',
                                                                                    'hide_empty' => false,
                                                                                ));

                                                                                if ($carfueltype && !is_wp_error($carfueltype)) {
                                                                                    foreach ($carfueltype as $carfueltypes) {
                                                                                        ?>
                                                                                        <label class="custom_check w-100">
                                                                                            <input type="checkbox" name="carfueltype[]" value="<?php echo esc_html($carfueltypes->slug); ?>">
                                                                                            <span class="checkmark"></span><?php echo esc_html($carfueltypes->name); ?>
                                                                                        </label>
                                                                                        <?php
                                                                                    }
                                                                                }
                                                                                ?>
                                                                        </div>	
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <!-- /By Car Fuel Type -->

                                                            <!-- By Car Transmission -->
                                                            <div class="accordion" id="accordionMain3">
                                                                <div class="card-header-new" id="headingThree">
                                                                    <h6 class="filter-title">
                                                                        <a href="javascript:void(0);" class="w-100 collapsed"  data-bs-toggle="collapse" data-bs-target="#cartransmission" aria-expanded="true" aria-controls="cartransmission">
                                                                        <?php echo esc_html__('Car Transmission', 'dreamsrent'); ?>
                                                                            <span class="float-end"><i class="fa-solid fa-chevron-down"></i></span>
                                                                        </a> 
                                                                    </h6>
                                                                </div>
                                                                <div id="cartransmission" class="collapse" aria-labelledby="headingThree"  data-bs-parent="#accordionExample3">
                                                                    <div class="card-body-chat">
                                                                        <div id="checkBoxes3">
                                                                        <?php
                                                                                
                                                                                $cartransmission = get_terms(array(
                                                                                    'taxonomy'   => 'cartransmission',
                                                                                    'hide_empty' => false,
                                                                                ));

                                                                                if ($cartransmission && !is_wp_error($cartransmission)) {
                                                                                    foreach ($cartransmission as $cartransmissions) {
                                                                                        ?>
                                                                                        <label class="custom_check w-100">
                                                                                            <input type="checkbox" name="cartransmission[]" value="<?php echo esc_html($cartransmissions->slug); ?>">
                                                                                            <span class="checkmark"></span><?php echo esc_html($cartransmissions->name); ?>
                                                                                        </label>
                                                                                        <?php
                                                                                    }
                                                                                }
                                                                                ?>
                                                                        </div>	
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <!-- /By Car Transmission -->

                                                            <!-- By Car Rental Type -->
                                                            <div class="accordion" id="accordionRentalType">
                                    <div class="card-header-new" id="accordionRentalType">
                                        <h6 class="filter-title">
                                            <a href="javascript:void(0);" class="w-100 collapsed" data-bs-toggle="collapse" data-bs-target="#carrentaltype" aria-expanded="true" aria-controls="carrentaltype">
                                                <?php echo esc_html__('Car Rental Type', 'dreamsrent'); ?>
                                                <span class="float-end"><i class="fa-solid fa-chevron-down"></i></span>
                                            </a>
                                        </h6>
                                    </div>
                                    <div id="carrentaltype" class="collapse" aria-labelledby="headingThree" data-bs-parent="#accordionRentalType">
                                        <div class="card-body-chat">
                                            <div id="radioButtons3">
                                                <?php
                                                global $wpdb;

                                                // Query to get all unique values of dreams_booking_meta_rentaltype_day and dreams_booking_meta_rentaltype_hour from wp_postmeta
                                                $results_day = $wpdb->get_results("
                                                    SELECT DISTINCT meta_value 
                                                    FROM {$wpdb->prefix}postmeta 
                                                    WHERE meta_key = 'dreams_booking_meta_rentaltype_day'
                                                ");

                                                $results_hour = $wpdb->get_results("
                                                    SELECT DISTINCT meta_value 
                                                    FROM {$wpdb->prefix}postmeta 
                                                    WHERE meta_key = 'dreams_booking_meta_rentaltype_hour'
                                                ");

                                                if ($results_day) {
                                                    foreach ($results_day as $result) {
                                                        	if($result->meta_value) {
                                                        ?>
                                                        <label class="custom_check w-100">
                                                            <input type="radio" name="rental_type" value="<?php echo esc_html($result->meta_value); ?>">
                                                            <span class="checkmark"></span><?php echo esc_html(ucfirst($result->meta_value)); ?>
                                                        </label>
                                                        <?php
                                                            }
                                                    }
                                                }

                                                if ($results_hour) {
                                                    foreach ($results_hour as $result) {
                                                        	if($result->meta_value) {
                                                        ?>
                                                        <label class="custom_check w-100">
                                                            <input type="radio" name="rental_type" value="<?php echo esc_html($result->meta_value); ?>">
                                                            <span class="checkmark"></span><?php echo esc_html(ucfirst($result->meta_value)); ?>
                                                        </label>
                                                        <?php
                                                            }
                                                    }
                                                }
                                                ?>
                                            </div>	
                                        </div>
                                    </div>
                                </div>


                                                            <!-- /By Car Rental Type -->

                                <!-- Category -->
                                <div class="accordion" id="accordionMain4">
                                    <div class="card-header-new" id="headingFour">
                                        <h6 class="filter-title">
                                            <a href="javascript:void(0);" class="w-100 collapsed"  data-bs-toggle="collapse" data-bs-target="#collapseFour" aria-expanded="true" aria-controls="collapseFour">
                                            <?php echo esc_html__('Price', 'dreamsrent'); ?>
                                                <span class="float-end"><i class="fa-solid fa-chevron-down"></i></span>
                                            </a> 
                                        </h6>
                                    </div>
                                    <div id="collapseFour" class="collapse" aria-labelledby="headingFour"  data-bs-parent="#accordionExample4">
                                        <div class="card-body-chat">
                                            <div class="filter-range">
                                            <?php
                                            global $wpdb;
                                            $query = $wpdb->prepare("
                                                SELECT meta_value
                                                FROM {$wpdb->postmeta}
                                                WHERE meta_key = %s
                                            ", 'dreams_booking_meta_rdprice');

                                            $results = $wpdb->get_results($query);

                                            if ($results) {
                                                
                                                $minPrice = PHP_INT_MAX;
                                                $maxPrice = 0;

                                                foreach ($results as $result) {
                                                    $price = floatval($result->meta_value);

                                                    if ($price < $minPrice) {
                                                        $minPrice = $price;
                                                    }

                                                    if ($price > $maxPrice) {
                                                        $maxPrice = $price;
                                                    }
                                                }

                                                echo '<input type="range" class="input-range" name="pricerange" value="' . esc_html($maxPrice) . '" min="' . esc_html($minPrice) . '" max="' . esc_html($maxPrice) . '">';

                                            } 
                                        ?>


                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <!-- /Category -->

                                <div class="accordion" id="accordionMain5">
                                    <div class="card-header-new" id="headingFive">
                                        <h6 class="filter-title">
                                            <a href="javascript:void(0);" class="w-100 collapsed"  data-bs-toggle="collapse" data-bs-target="#collapseFive" aria-expanded="true" aria-controls="collapseFive">
                                            <?php echo esc_html__('Rating', 'dreamsrent'); ?>
                                                <span class="float-end"><i class="fa-solid fa-chevron-down"></i></span>
                                            </a> 
                                        </h6>
                                    </div>
                                    <div id="collapseFive" class="collapse" aria-labelledby="headingFive"  data-bs-parent="#accordionExample5">
                                        <div class="card-body-chat">
                                            <div id="checkBoxes4">
                                            <div class="selectBox-cont">
                                            <?php
                                                for ($stars = 5; $stars >= 1; $stars--) {
                                                    ?>
                                                    <label class="custom_check w-100">
                                                        <input type="checkbox" name="rating[]" value="<?php echo esc_html($stars); ?>" class="star-checkbox">
                                                        <span class="checkmark"></span>
                                                        <?php
                                                        for ($i = 1; $i <= $stars; $i++) {
                                                            echo '<i class="fas fa-star filled"></i>';
                                                        }
                                                        ?>
                                                    </label>
                                                <?php
                                                }
                                                ?>
                                                </div>
                                            </div>	
                                        </div>
                                    </div>
                                </div>

                                <button class="d-inline-flex align-items-center justify-content-center btn w-100 btn-primary filter-btn" type="submit" onclick="handleFormSubmission()"><span><i class="feather-filter me-2"></i></span><?php echo esc_html__( 'Filter Results', 'dreamsrent' ); ?></button>
                                <a href="#" class="reset-filter" onClick="resetData()"><?php echo esc_html__('Reset Filter', 'dreamsrent'); ?></a>
                                </form>
                                            </div>

 <div class="col-lg-9">
 <div class="row">
 <?php

$results_main = $wpdb->get_results($query);

if (isset($_POST['carcategory'])) {
    $carcategory = $_POST['carcategory'];
} elseif (isset($_GET['carcategory'])) {
    $carcategory = $_GET['carcategory'];
} else {
	$carcategory = '';
}

if (isset($_POST['cartypes'])) {
    $cartypes = $_POST['cartypes'];
} elseif (isset($_GET['cartypes'])) {
    $cartypes = $_GET['cartypes'];
} else {
	$cartypes = '';
}

if (isset($_POST['carcapacity'])) {
    $carcapacity = $_POST['carcapacity'];
} elseif (isset($_GET['carcapacity'])) {
    $carcapacity = $_GET['carcapacity'];
} else {
	$carcapacity = '';
}

// $carcategory = isset($_POST['carcategory']) ? $_POST['carcategory'] : array();
// $cartypes = isset($_POST['cartypes']) ? $_POST['cartypes'] : array();
// $carcapacity = isset($_POST['carcapacity']) ? $_POST['carcapacity'] : array();
$selectedMinPrice = isset($_GET['0']) ? floatval($_GET['0']) : $minPrice;
$selectedMaxPrice = isset($_GET['max_price']) ? floatval($_GET['max_price']) : $maxPrice;
$selectedRatings = isset($_GET['rating']) ? $_GET['rating'] : array();
$search_keyword = isset($_GET['search_keyword']) ? sanitize_text_field($_GET['search_keyword']) : '';
$carmakeyear = isset($_GET['carmakeyear']) ? $_GET['carmakeyear'] : array();
$carfueltype = isset($_GET['carfueltype']) ? $_GET['carfueltype'] : array();
$cartransmission = isset($_GET['cartransmission']) ? $_GET['cartransmission'] : array();
$rental_type = isset($_GET['rental_type']) ? sanitize_text_field($_GET['rental_type']) : '';

$sort_order = isset($_GET['sort']) ? $_GET['sort'] : '';

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

$meta_query = array();

// Rental Type
if (!empty($rental_type)) {
    $rental_type_meta_query = array();
    if ($rental_type == 'day') {
        $rental_type_meta_query[] = array(
            'key'     => 'dreams_booking_meta_rentaltype_day',
            'value'   => $rental_type,
            'compare' => 'LIKE',
        );
    } elseif ($rental_type == 'hour') {
        $rental_type_meta_query[] = array(
            'key'     => 'dreams_booking_meta_rentaltype_hour',
            'value'   => $rental_type,
            'compare' => 'LIKE',
        );
    }
    $meta_query[] = $rental_type_meta_query;
}

$selected_location = isset($_POST['location']) ? sanitize_text_field($_POST['location']) : '';
if (empty($selected_location) && isset($_GET['location'])) {
    $selected_location = sanitize_text_field($_GET['location']);
}
$term_data  = term_exists($selected_location, 'location');
$term_id = is_array($term_data) ? $term_data['term_id'] : $term_data;
 

$selected_location_drop = isset($_POST['location_drop']) ? sanitize_text_field($_POST['location_drop']) : '';
if (empty($selected_location_drop) && isset($_GET['location_drop'])) {
    $selected_location_drop = sanitize_text_field($_GET['location_drop']);
}
$term_data  = term_exists($selected_location_drop, 'location');
$term_id = is_array($term_data) ? $term_data['term_id'] : $term_data;
// $meta_query = array();
// if ($term_id) {
//     $meta_query[] = array(
//         'key'     => '_rent_locations',
//         'value'   => '"plocation";s:' . strlen(strval($term_id)) . ':"' . $term_id . '";',
//         'compare' => 'LIKE',
//     );
// }

// Price filter
if (!empty($selectedMinPrice) || !empty($selectedMaxPrice)) {
    $meta_query[] = array(
        'key'     => 'dreams_booking_meta_rdprice',
        'value'   => array($selectedMinPrice, $selectedMaxPrice),
        'type'    => 'NUMERIC',
        'compare' => 'BETWEEN',
    );
}

// Car Make Year filter
if (!empty($carmakeyear)) {
    $meta_query[] = array(
        'key'     => 'dreams_booking_meta_make_year',
        'value'   => $carmakeyear,
        'type'    => 'NUMERIC',
        'compare' => 'IN',
    );
}

// Rating
if (!empty($selectedRatings)) {
    $meta_query[] = array(
        'key'     => 'dreamsrent-rating',
        'value'   => $selectedRatings,
        'type'    => 'NUMERIC',
        'compare' => 'IN',
    );
}

// Car category, car types, car capacity, car fuel type, car transmission
if (!empty($carcategory) || !empty($cartypes) || !empty($carcapacity) || !empty($carfueltype) || !empty($cartransmission) || !empty($term_id)) {
    $tax_query = array();


    

	if (!empty($term_id)) {
        $tax_query[] = array(
            'taxonomy' => 'location',
            'field'    => 'slug',
            'terms'    => $term_id,
        );
    }

    if (!empty($carcategory)) {
        $tax_query[] = array(
            'taxonomy' => 'carcategory',
            'field'    => 'slug',
            'terms'    => $carcategory,
        );
    }

    if (!empty($cartypes)) {
        $tax_query[] = array(
            'taxonomy' => 'cartype',
            'field'    => 'slug',
            'terms'    => $cartypes,);
    }

    if (!empty($carcapacity)) {
        $tax_query[] = array(
            'taxonomy' => 'carcapacity',
            'field'    => 'slug',
            'terms'    => $carcapacity,
        );
    }

    if (!empty($carfueltype)) {
        $tax_query[] = array(
            'taxonomy' => 'carfueltype',
            'field'    => 'slug',
            'terms'    => $carfueltype,
        );
    }

    if (!empty($cartransmission)) {
        $tax_query[] = array(
            'taxonomy' => 'cartransmission',
            'field'    => 'slug',
            'terms'    => $cartransmission,
        );
    }

    $tax_query['relation'] = 'AND';
    $args['tax_query'] = $tax_query;
}

// Sorting
switch ($sort_order) {
    case 'low_to_high':
        $args['orderby']  = 'meta_value_num';
        $args['meta_key'] = 'dreams_booking_meta_rdprice';
        $args['order']    = 'ASC';
        break;
    case 'high_to_low':
        $args['orderby']  = 'meta_value_num';
        $args['meta_key'] = 'dreams_booking_meta_rdprice';
        $args['order']    = 'DESC';
        break;
    case 'popularity':
        $args['orderby'] = 'comment_count';
        $args['order']   = 'DESC';
        break;
    default:
        $args['orderby'] = 'date';
        $args['order']   = 'DESC';
}



// Get session dates
$pickup_date = isset($_SESSION['pickup_date']) ? $_SESSION['pickup_date'] : '';
$return_date = isset($_SESSION['return_date']) ? $_SESSION['return_date'] : '';

$pickup_time = isset($_SESSION['pickup_time']) ? $_SESSION['pickup_time'] : '';
$return_time = isset($_SESSION['return_time']) ? $_SESSION['return_time'] : '';

// var_dump($pickup_time);
// var_dump($return_time);

// Validate and convert dates
if (!empty($pickup_date)) {
    $date_obj = DateTime::createFromFormat('d-m-Y', $pickup_date);
    $pickup_date = $date_obj ? $date_obj->format('Y-m-d') : null;
} else {
    $pickup_date = '';
}

if (!empty($return_date)) {
    $date_obj = DateTime::createFromFormat('d-m-Y', $return_date);
    $return_date = $date_obj ? $date_obj->format('Y-m-d') : null;
} else {
    $return_date = '';
}

// Ensure product ID is valid
$product_id = get_post_meta(get_the_ID(), '_booking_product_id', true);
$product_id = intval($product_id);

$pickup_datetime = !empty($pickup_date) && !empty($pickup_time) ? "$pickup_date $pickup_time" : null;
$return_datetime = !empty($return_date) && !empty($return_time) ? "$return_date $return_time" : null;
 

global $wpdb;

$table_name = $wpdb->prefix . 'dreamsrent_booking';

$sql = $wpdb->prepare(
    "SELECT car_id FROM $table_name 
     WHERE (
        (pickup_date <= %s AND dropoff_date >= %s)
        OR (pickup_date BETWEEN %s AND %s)
        OR (dropoff_date BETWEEN %s AND %s)
     )",
    $return_datetime,
    $pickup_datetime,
    $pickup_datetime,
    $return_datetime,
    $pickup_datetime,
    $return_datetime
);

$excluded_ids = $wpdb->get_col($sql);

$args['post_type'] = 'rental';
$args['post_status'] = 'publish';
$args['meta_query'] = $meta_query;
$args['paged'] = $paged;
$args['posts_per_page'] = $posts_per_page;
$args['s'] = $search_keyword;
$args['post__not_in'] = $excluded_ids;


$wp_query = new WP_Query($args);
 ?>
<?php
					$group_slide = $t_items_cat = 1;
                    if( $wp_query->have_posts() ): while( $wp_query->have_posts() ):  $wp_query->the_post();
  					$img  = wp_get_attachment_image_url( get_post_thumbnail_id(), 'large' );
 					$img_one  = get_template_directory_uri() . '/assets/images/placeholder.png';
                     $image_alt = get_post_meta(get_post_thumbnail_id(), '_wp_attachment_image_alt', true);
                     if($image_alt) { 
                        $image_alt_dis = get_post_meta(get_post_thumbnail_id(), '_wp_attachment_image_alt', true);
                      } else {
                        $image_alt_dis = 'Services';
                     }
   					$min = $max = 0;
 ?>
 


<div class="listview-car">
                                <div class="card">
                                    <div class="blog-widget d-flex">
 										<div class="blog-img">
                                             
										<a href="<?php echo get_the_permalink(); ?>">
										<?php if($img) { ?>
											<img src="<?php echo esc_html($img); ?>" class="img-fluid" alt="<?php echo esc_html($image_alt_dis); ?>">
											<?php }  else {?>
												<img src="<?php echo esc_html($img_one); ?>" class="img-fluid" alt="Service">
												<?php } ?>
										</a>
 									</div>										
                                        <div class="bloglist-content w-100">
                                           <div class="card-body">
                                                <div class="blog-list-head d-flex">
                                                    <div class="blog-list-title">
                                                        <h3><a href="<?php echo get_the_permalink(); ?>"><?php echo get_the_title(); ?></a></h3>
														<?php if(dreams_getcategory('carcategory')) { ?>

                                                        <h6><?php echo esc_html__('Category','dreamsrent'); ?> : <span> <?php echo dreams_getcategory('carcategory'); ?></span></h6>
										                <?php } ?>
                                                    </div>
                                                <div class="blog-list-rate woocommerce 2">

                                         
                
 <?php $starting_from = dreamsrent_fl_framework_getoptions('starting_from_price');
 if($starting_from) { ?>
 <?php 
$dsrent_resource_name = maybe_unserialize(get_post_meta(get_the_id(), '_seasonal_rental_pricing_data', true)); 
if (!empty($dsrent_resource_name)) { 
    $prices = [];
    $count = 0;
    foreach ($dsrent_resource_name as $dsrent_resource_name_dis) {
        if (isset($dsrent_resource_name_dis['seasonal_price'])) {
            $prices[] = floatval($dsrent_resource_name_dis['seasonal_price']);
            $count++;
        }
        
    }

    // Take the first two values and calculate the average
    if (count($prices) >= 2) {
          $sum_of_two = array_sum($prices);
        $average_of_two = $sum_of_two / $count;
    } else {
        // If there's only one value, use it as the average
        $average_of_two = (!empty($prices)) ? $prices[0] : 0;
    }
    ?>

   
	<h6><?php echo get_woocommerce_currency_symbol();?><?php echo esc_html(number_format($average_of_two, 0)); ?><span>/ <?php echo esc_html_e('Day', 'dreamsrent'); ?></span></h6>
<?php }  else  {?>
	<h6><?php echo get_woocommerce_currency_symbol();?><?php dreams_display_rental_price(get_the_id());?><span>/ <?php dreams_display_rental_type(get_the_id()); ?></span></h6>
	<?php } ?>

    <?php } else { ?>
     <h6><?php echo get_woocommerce_currency_symbol();?><?php dreams_display_rental_price(get_the_id());?><span>/ <?php dreams_display_rental_type(get_the_id()); ?></span></h6>
 <?php } ?>
    
 															 											 
                                            <?php $starting_from = dreamsrent_fl_framework_getoptions('starting_from');
											if($starting_from) { ?>
											<div class="me-1"> <?php echo esc_html($starting_from); ?></div>
									       <?php } ?>
											
                                                     </div>
                                                </div>	
                                                <div class="listing-details-group">
 <ul>
    <?php
    $post_id = get_the_ID(); // Or use your specific post ID
    $terms = get_the_terms($post_id, 'cartransmission');

    if (!empty($terms) && !is_wp_error($terms)) {
        $first_term = $terms[0]; // Get the first term
        ?>
        <li>
            <span><img src="<?php echo esc_url( get_template_directory_uri() . '/assets/images/car-parts-01.svg' ); ?>" alt="Gear Type"></span>
            <p><?php echo esc_html($first_term->name); ?></p>
        </li>
    <?php } ?>

<?php $mileage= get_post_meta(get_the_id(), 'mileage', true);
if (!empty($mileage)) { 
 ?>
	<li>
            <span><img src="<?php echo esc_url( get_template_directory_uri() . '/assets/images/car-parts-02.svg' ); ?>" alt="Gear Type"></span>
            <p><?php echo esc_html($mileage); ?> <?php echo esc_html('KM', 'dreamsrent'); ?></p>
        </li>
 <?php } ?>

 

<?php
 $terms = get_the_terms($post_id, 'carfueltype');
 if (!empty($terms) && !is_wp_error($terms)) {
	$first_term = $terms[0]; // Get the first term
	?>
	<li>
		<span><img src="<?php echo esc_url( get_template_directory_uri() . '/assets/images/car-parts-03.svg' ); ?>" alt="Gear Type"></span>
		<p><?php echo esc_html($first_term->name); ?></p>
	</li>
<?php } ?>

 <?php
 $terms = get_the_terms($post_id, 'carsteering');
 if (!empty($terms) && !is_wp_error($terms)) {
	$first_term = $terms[0]; // Get the first term
	?>
	<li>
		<span><img src="<?php echo esc_url( get_template_directory_uri() . '/assets/images/car-parts-04.svg' ); ?>" alt="Gear Type"></span>
		<p><?php echo esc_html($first_term->name); ?></p>
	</li>
<?php } ?>



<?php $year_of_car= get_post_meta(get_the_id(), 'year_of_car', true);
if (!empty($year_of_car)) { 
 ?>
	<li>
            <span><img src="<?php echo esc_url( get_template_directory_uri() . '/assets/images/car-parts-05.svg' ); ?>" alt="Gear Type"></span>
            <p><?php echo esc_html($year_of_car); ?></p>
        </li>
 <?php } ?>

 
<?php $passengers= get_post_meta(get_the_id(), 'passengers', true);
if (!empty($passengers)) { 
 ?>
	<li>
            <span><img src="<?php echo esc_url( get_template_directory_uri() . '/assets/images/car-parts-06.svg' ); ?>" alt="Gear Type"></span>
            <p><?php echo esc_html($passengers); ?> <?php esc_html_e('Persons', 'dreamsrent'); ?></p>
        </li>
 <?php } ?>


</ul>

  </div>	

 <div class="blog-list-head list-head-bottom d-flex ">
     <div class="blog-list-title">
        <div class="title-bottom">

        <div class="listing-features">
											<a href="javascript:void(0)" class="author-img">

											<?php 
											// $authorId = get_the_author_id();
											$authorId = get_the_author_meta('ID');
											echo get_avatar($authorId, 100);  ?>
 											</a>
										</div> 
            <div class="address-info">
                
 <h6><i class="feather-map-pin me-1"></i><?php 
$main_location_id = get_post_meta(get_the_ID(), 'main_locations', true);
 if (!empty($main_location_id)) {
    $term = get_term($main_location_id, 'location'); // 'location' is your taxonomy
    if ($term && !is_wp_error($term)) {
        echo esc_html($term->name); // Output the term name
    }
}
?></h6>
							            </div>
        </div>	
    </div>
    <div class="listing-button">
            <a href="<?php echo get_the_permalink(); ?>" class="btn btn-order"><span><i class="feather-calendar me-2"></i></span><?php echo esc_html__( 'Rent Now', 'dreamsrent' ); ?></a>
                                                    </div>
                                                </div>	
                                            </div>					 
                                        </div>			 
                                    </div> 
                                </div>
							</div>

 

							<?php 

$group_slide++;
$t_items_cat++;


endwhile; 
dreams_pagination_theme();
else :  ?>
<div class="col-md-12">
<div class="d-flex justify-content-center align-items-center">
 <h4><?php echo esc_html__( 'No Results Found', 'dreamsrent' ); ?></h4>
</div>
</div>

<?php 
 endif;  ?>
 
<?php 
 wp_reset_postdata();
?>
 
							 
						</div>	
						 

					</div>
				</div>		
		  	</div>	
		</section>

		<script>
			/** URL Parameters**/
    	document.addEventListener("DOMContentLoaded", function () {
        // Check the URL for parameters and set the checkboxes accordingly
        var urlParams = new URLSearchParams(window.location.search);
        var carcategory = document.getElementsByName('carcategory[]');
        var cartypes = document.getElementsByName('cartypes[]');
		var carcapacity = document.getElementsByName('carcapacity[]');
		var carRating = document.getElementsByName('rating[]');
		var carmakeyear = document.getElementsByName('carmakeyear[]');
		var carfueltype = document.getElementsByName('carfueltype[]');
		var cartransmission = document.getElementsByName('cartransmission[]');
		var rentalType = document.getElementsByName('rental_type');

		var rentalTypeParam = urlParams.get('rental_type');
    if (rentalTypeParam) {
        rentalType.forEach(function (radio) {
            if (radio.value === rentalTypeParam) {
                radio.checked = true;
            }
        });
    }

		var searchKeywordParam = urlParams.get('search_keyword');
    if (searchKeywordParam) {
        document.getElementsByName('search_keyword')[0].value = searchKeywordParam;
    }

	var location = urlParams.get('location');
    if (location) {
        document.getElementsByName('location')[0].value = location;
    }

	var locationSelect = document.getElementsByName('location')[0];
	var storedLocation = localStorage.getItem('selectedLocation');
    if (storedLocation) {
        locationSelect.value = storedLocation;
    }

    // Listen for changes in the location select element
    locationSelect.addEventListener('change', function () {
        // Store the selected location in local storage
        localStorage.setItem('selectedLocation', locationSelect.value);
    });

        carcategory.forEach(function (checkbox) {
            var value = checkbox.value;
            if (urlParams.has('carcategory[]')) {
                var selectedValues = urlParams.getAll('carcategory[]');
                if (selectedValues.includes(value)) {
                    checkbox.checked = true;
                }
            }
        });

        cartypes.forEach(function (checkbox) {
            var value = checkbox.value;
            if (urlParams.has('cartypes[]')) {
                var selectedValues = urlParams.getAll('cartypes[]');
                if (selectedValues.includes(value)) {
                    checkbox.checked = true;
                }
            }
        });

		carcapacity.forEach(function (checkbox) {
            var value = checkbox.value;
            if (urlParams.has('carcapacity[]')) {
                var selectedValues = urlParams.getAll('carcapacity[]');
                if (selectedValues.includes(value)) {
                    checkbox.checked = true;
                }
            }
        });

		carmakeyear.forEach(function (checkbox) {
            var value = checkbox.value;
            if (urlParams.has('carmakeyear[]')) {
                var selectedValues = urlParams.getAll('carmakeyear[]');
                if (selectedValues.includes(value)) {
                    checkbox.checked = true;
                }
            }
        }); 

		carfueltype.forEach(function (checkbox) {
            var value = checkbox.value;
            if (urlParams.has('carfueltype[]')) {
                var selectedValues = urlParams.getAll('carfueltype[]');
                if (selectedValues.includes(value)) {
                    checkbox.checked = true;
                }
            }
        })

		cartransmission.forEach(function (checkbox) {
            var value = checkbox.value;
            if (urlParams.has('cartransmission[]')) {
                var selectedValues = urlParams.getAll('cartransmission[]');
                if (selectedValues.includes(value)) {
                    checkbox.checked = true;
                }
            }
        })
		carRating.forEach(function (checkbox) {
            var value = checkbox.value;
            if (urlParams.has('rating[]')) {
                var selectedValues = urlParams.getAll('rating[]');
                if (selectedValues.includes(value)) {
                    checkbox.checked = true;
                }
            }
        });

		
    });


	/** function handleFormSubmission **/
    function handleFormSubmission() {
        var carcategory = document.getElementsByName('carcategory[]');
        var cartypes = document.getElementsByName('cartypes[]');
		var carcapacity = document.getElementsByName('carcapacity[]');
		var carRating = document.getElementsByName('rating[]');
		var searchKeyword = document.getElementsByName('search_keyword')[0].value;
		var location = document.getElementsByName('location')[0].value;
		var carmakeyear = document.getElementsByName('carmakeyear[]');
		var carfueltype = document.getElementsByName('carfueltype[]');
		var cartransmission = document.getElementsByName('cartransmission[]');
    	var rentalType = document.getElementsByName('rental_type');

		
        var selectedCarCategories = [];
        var selectedCarTypes = [];
        var selectedCarCapacity = [];
		var selectedcarmakeyear = [];		
		var selectedcarfueltype = [];
		var selectedCarRating = [];
		var selectedcartransmission = [];
		var selectedRentalType;

		rentalType.forEach(function (radio) {
        if (radio.checked) {
            selectedRentalType = radio.value;
        }
    });


        carcategory.forEach(function (checkbox) {
            if (checkbox.checked) {
                selectedCarCategories.push(checkbox.value);
            }
        });

        cartypes.forEach(function (checkbox) {
            if (checkbox.checked) {
                selectedCarTypes.push(checkbox.value);
            }
        });

		carcapacity.forEach(function (checkbox) {
            if (checkbox.checked) {
                selectedCarCapacity.push(checkbox.value);
            }
        });

		carmakeyear.forEach(function (checkbox) {
            if (checkbox.checked) {
                selectedcarmakeyear.push(checkbox.value);
            }
        });

		carfueltype.forEach(function (checkbox) {
            if (checkbox.checked) {
                selectedcarfueltype.push(checkbox.value);
            }
        });

		cartransmission.forEach(function (checkbox) {
            if (checkbox.checked) {
                selectedcartransmission.push(checkbox.value);
            }
        });

		carRating.forEach(function (checkbox) {
            if (checkbox.checked) {
                selectedCarRating.push(checkbox.value);
            }
        });

		var selectedMinPrice = 0;
		var selectedMaxPrice = jQuery(".input-range").data("from");

		
 		
        // Construct the query parameters
        var params = new URLSearchParams();

		if (selectedRentalType) {
        params.append('rental_type', selectedRentalType);
    }
        selectedCarCategories.forEach(function (value) {
            params.append('carcategory[]', value);
        });

        selectedCarTypes.forEach(function (value) {
            params.append('cartypes[]', value);
        });

		selectedCarCapacity.forEach(function (value) {
            params.append('carcapacity[]', value);
        });

		selectedcarmakeyear.forEach(function (value) {
            params.append('carmakeyear[]', value);
        });

		selectedcarfueltype.forEach(function (value) {
            params.append('carfueltype[]', value);
        });

		selectedcartransmission.forEach(function (value) {
            params.append('cartransmission[]', value);
        });

		selectedCarRating.forEach(function (value) {
            params.append('rating[]', value);
        });
		params.append('min_price', selectedMinPrice);
        params.append('max_price', selectedMaxPrice);
		if (searchKeyword.trim() !== '') {
    params.append('search_keyword', searchKeyword);
}
 // Include the text input value
 if(location.trim() !== '') {
		params.append('location', location); // Include the text input value
 }
 
        var currentUrl = new URL(window.location.href);
        currentUrl.search = params.toString();

        history.pushState(null, '', currentUrl);
        console.log('Updated URL:', currentUrl.href);
    }

	/** slider **/
    jQuery(document).ready(function ($) {

        if ($('.input-range').length > 0) {
            $(".input-range").ionRangeSlider({
                type: "single",
                grid: true,
                min: 0,
                max: <?php echo esc_js($maxPrice) ?>,
                from:<?php echo esc_js($maxPrice) ?>,
                to: <?php echo esc_js($maxPrice) ?>,
                onUpdate: function (data) {
                    handleFormSubmission();
                }


            });
        }

      
    });


	/** Star Rating **/

   jQuery(document).ready(function () {
    jQuery('.star-checkbox').change(function () {
        var selectedStars = jQuery('.star-checkbox:checked').map(function () {
            return this.value;
        }).get();

        jQuery.ajax({
            type: 'POST',
            data: { stars: selectedStars }, // Add the action parameter
            success: function (data) {
				
            },
		
           
        });
    });
});

/** Reset Form **/
function resetData() {
	document.getElementById("filterForm").reset();
    var baseUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
    window.location.href = baseUrl;
}

</script>
 <?php
 get_footer(); ?>