<?php
namespace Elementor;
use Elementor\Group_Control_Typography;
use Elementor\Core\Schemes\Typography;
use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Background;
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**
 * Elementor Hello World
 *
 * Elementor widget for hello world.
 *
 * @since 1.0.0
 */
class Jws_Rental_Filter extends Widget_Base {

	/**
	 * Retrieve the widget name.
	 *
	 * @since 1.0.0
	 *
	 * @access public
	 *
	 * @return string Widget name.
	 */
	public function get_name() {
		return 'jws_rental_filter';
	}

	/**
	 * Retrieve the widget title.
	 *
	 * @since 1.0.0
	 *
	 * @access public
	 *
	 * @return string Widget title.
	 */
	public function get_title() {
		return esc_html__( 'Jws Rental Filter', 'idealauto' );
	}

	/**
	 * Retrieve the widget icon.
	 *
	 * @since 1.0.0
	 *
	 * @access public
	 *
	 * @return string Widget icon.
	 */
	public function get_icon() {
		return 'eicon-site-search';
	}

	/**
	 * Retrieve the list of categories the widget belongs to.
	 *
	 * Used to determine where to display the widget in the editor.
	 *
	 * Note that currently Elementor supports only one category.
	 * When multiple categories passed, Elementor uses the first one.
	 *
	 * @since 1.0.0
	 *
	 * @access public
	 *
	 * @return array Widget categories.
	 */
	public function get_categories() {
		return [ 'jws-elements' ];
	}

    /**
	 * Retrieve the list of scripts the image carousel widget depended on.
	 *
	 * Used to set scripts dependencies required to run the widget.
	 *
	 * @since 0.0.1
	 * @access public
	 *
	 * @return array Widget scripts dependencies.
	 */
    public function get_style_depends() {
		return [ 'datetimepicker'];
	} 
	public function get_script_depends() {
		return [ 'datetimepicker' , 'moment-min'];
	}
	/**
	 * Register the widget controls.
	 *
	 * Adds different input fields to allow the user to change and customize the widget settings.
	 *
	 * @since 1.0.0
	 *
	 * @access protected
	 */
	protected function register_controls() {
		$this->start_controls_section(
			'section_search_setting',
			[
				'label' => esc_html__( 'Toggle', 'idealauto' ),
			]
		);
        $this->add_control(
			'layouts',
			[
				'label'     => esc_html__( 'Layout', 'idealauto' ),
				'type'      => Controls_Manager::SELECT,
				'default'   => 'layout1',
				'options'   => [
					'layout1'   => esc_html__( 'Layout 1', 'idealauto' ),
					'layout2'   => esc_html__( 'Layout 2', 'idealauto' ),
				],
                
			]
		);
        $this->add_control(
			'rental_ajax_shop',
			[
				'label' => esc_html__( 'Use Ajax For Shop', 'idealauto' ),
				'type' => \Elementor\Controls_Manager::SWITCHER,
				'label_on' => esc_html__( 'On', 'idealauto' ),
				'label_off' => esc_html__( 'Off', 'idealauto' ),
                'default' => '',
				'return_value' => 'yes',
			]
		);
       
		$this->end_controls_section();
  
	}

	/**
	 * Render the widget output on the frontend.
	 *
	 * Written in PHP and used to generate the final HTML.
	 *
	 * @since 1.0.0
	 *
	 * @access protected
	 */
	protected function render() {
		$settings = $this->get_settings_for_display();
        global $jws_option;
        if($settings['layouts'] == 'layout1') {
            $columns1 = 'jws-search-av-item col-xl-12';
            $columns2 = 'jws-search-av-item col-xl-6 col-lg-6 col-12';
            $columns3 = 'jws-search-av-item col-xl-4 col-lg-4 col-12'; 
        }else{
            $columns1 = 'jws-search-av-item col-xl-3 col-lg-3 col-12';
            $columns2 = 'jws-search-av-item col-xl-3 col-lg-3 col-12';
            $columns3 = 'jws-search-av-item col-xl-3 col-lg-3 col-12';
        }
        
        $shop_ajax = ($settings['rental_ajax_shop'] == 'yes') ? ' yes' : ' no' ;
            
        
        
        ?>
        
        <div class="jws-adsearch-filter <?php echo esc_attr($settings['layouts']).$shop_ajax; ?>">
			<!-- Search form -->
			<div class="form-search light">
				<form action="<?php echo esc_url( get_permalink( wc_get_page_id( ( 'shop' ) ) ) ); ?>" method="get">
                    <div class="row">
					<div class="<?php echo ''.$columns1; ?>">
						<label><?php esc_html_e( 'Pick-up Location', 'idealauto' ); ?></label>
						<select name="dropin" type="text" class="drolocation formSearchUpLocation" placeholder="<?php esc_html_e( 'Pick-up Location', 'idealauto' ); ?>" >
                                <option value="" > <?php esc_html_e( 'Enter your pick-up location', 'idealauto' ); ?> </option>
                                <?php
                                   $selected = ''; 
    						       if ( isset( $_GET['dropin'] ) ) {
    							      $selected = esc_html( $_GET['dropin'] );
    						       } else {
    							       if ( function_exists( 'jws_get_date_s' ) ) {
    								      $selected = jws_get_date_s( 'dropin_location' );
    							       }
    						       }

                                    $locations = $jws_option['locations'];
                                 
                                    if ( count( $locations ) > 0 ):
                                    foreach( $locations as $key => $location) {
                                            $id = $location;
                                                $active = $selected == $location
                                				? 'selected '
                                				: '';
                                    
                                            	echo '<option '.$active.'value="' . $id. '" ' . '>' .
    											$id . '</option>';
                                    }
                                    else:
    									echo '<option value="">' . esc_html__( 'No locations found.', 'idealauto' ) . '</option>';
    								endif;
                                    

									?>
                        
                        </select>
                        <i class="jws-icon-icon_pin"></i>
					</div>
                    <?php 
                    if($settings['layouts'] == 'layout1') :
                    ?>
                    <div class="<?php echo 'return-change '.$columns1; ?>">
                        <label>
                        <input  class="return-two-location" type="checkbox" value=""/>
                        <?php echo esc_html__('Return to a different location','idealauto'); ?></label>
                    </div>
                    
                    <script>
                        jQuery(document).ready(function ($) {
                           $change_return = $('.return-two-location');
                           $change_return.on('change',function(){
                              var one_value = $('.formSearchUpLocation').val();  
                              var isChecked=$(this).is(":checked");
                                if(isChecked) {
                                    $('.location-off').slideDown(); 
                                }else {
                                    $('.location-off').slideUp();
                                    $('.formSearchOffLocation').select2('destroy').val(one_value).select2(); 
                                }
                            });
                            
                            $('.formSearchUpLocation ').on('change',function(){
                              var one_value = $(this).val();  
                              var isChecked=$('.return-two-location').is(":checked");
                                if(!isChecked) {
                                   $('.formSearchOffLocation').select2('destroy').val(one_value).select2();  
                                }
                            });
                        });
                    </script>
                    <?php endif; ?>
					<div class="<?php echo 'location-off '.$columns1; ?>">
						<label>  <?php esc_html_e( 'Drop off Location', 'idealauto' ); ?></label>
						<select name="dropoff" type="text" class="drolocation formSearchOffLocation" placeholder="<?php esc_html_e( 'Drop off Location', 'idealauto' ); ?>" >
                        <option value="" > <?php esc_html_e( 'Enter your drop off location', 'idealauto' ); ?> </option>
                            <?php
                                   $selected = ''; 
    						       if ( isset( $_GET['dropoff'] ) ) {
    							      $selected = esc_html( $_GET['dropoff'] );
    						       } else {
    							       if ( function_exists( 'jws_get_date_s' ) ) {
    								      $selected = jws_get_date_s( 'dropoff_location' );
    							       }
    						       }

                                       
                                    $locations = $jws_option['locations'];
                                 
                                    if ( count( $locations ) > 0 ):
                                    foreach( $locations as $key => $location) {
                                            $id = $location;
                                                $active = $selected == $location
                                				? 'selected '
                                				: '';
                                    
                                            	echo '<option '.$active.'value="' . $id. '" ' . '>' .
    											$id . '</option>';
                                    }
                                    else:
    									echo '<option value="">' . esc_html__( 'No locations found.', 'idealauto' ) . '</option>';
    								endif;
                                        

									?>
                        </select>
                        <i class="jws-icon-icon_pin"></i>
					</div>

					<div class="<?php echo ''.$columns2; ?>">
						<label for="formSearchUpDate30"> <?php esc_html_e( 'Pick-up Date & Time', 'idealauto' ); ?></label>
						<input autocomplete="off" name="start_date" type="text" class="form-control jws-date-timepicker-start" id="formSearchUpDate30" placeholder="<?php esc_html_e( 'Pick-up Date & Time', 'idealauto' ); ?>"
						       value="<?php
						       if ( isset( $_GET['start_date'] ) && ! empty( $_GET['start_date'] ) ) {
							       echo esc_attr( $_GET['start_date'] );
						       }
						       ?>"
						>
                        <i class="jws-icon-calendar2"></i>
					</div>
	                <div class="<?php echo ''.$columns2; ?>">
						<label for="formSearchUpDate30"> <?php esc_html_e( 'Return Date & Time', 'idealauto' ); ?></label>
						<input autocomplete="off" name="end_date" type="text" class="form-control jws-date-timepicker-end" id="formSearchOffDate3" placeholder="<?php esc_html_e( 'Return Date & Time', 'idealauto' ); ?>"
						       value="<?php
						       if ( isset( $_GET['end_date'] ) && ! empty( $_GET['end_date'] ) ) {
							       echo esc_attr( $_GET['end_date'] );
						       }
						       ?>"
						>
                        <i class="jws-icon-calendar2"></i>
					</div>

                    <?php 
                        $dFormat = get_option('date_format');
                        $tFormat = 'H:i';
                        $dFormat = (preg_match_all("/[d].[m].[yY]/", $dFormat)) ? 'm/d/Y' : $dFormat;
                        $dateTimeFormat = $dFormat . " " . $tFormat;
                    ?>
                <script>
                          jQuery(document).ready(function ($) {
                        var jwsStartVal = $('.jws-date-timepicker-start').val();
                        var jwsEndVal = $('.jws-date-timepicker-end').val();
            
                        /*Timepicker*/
                        var jwsToday = new Date();
                        var jwsTomorrow = new Date(+new Date() + 86400000);
                        var jwsStartDate = false;
                        var jwsEndDate = false;
                        var startDate = (jwsStartVal != '') ? jwsStartVal : false;
                        var endDate = (jwsEndVal != '') ? jwsEndVal : false;
                        var dateTimeFormat = '<?php echo esc_js($dateTimeFormat); ?>';
                        var dateTimeFormatHide = 'YYYY/MM/DD HH:mm';   
                        $('.jws-date-timepicker-start').datetimepicker({
                        formatTime: 'H:i',
                        formatDate: '<?php echo esc_js($dFormat); ?>',
                        format: dateTimeFormat,
                        dayOfWeekStart: <?php echo get_option('start_of_week');?>,
                        defaultDate: jwsToday,
                        defaultSelect: false,
                        closeOnDateSelect: false,
                        timeHeightInTimePicker: 40,
                        validateOnBlur: false,
                        fixed: false,
                        onShow: function( ct ) {
                            $('body').addClass('jws_background_overlay jws-lock');
        
                            var jwsEndDate = $('.jws-date-timepicker-end').val() ? moment($('.jws-date-timepicker-end').val()).format(dateTimeFormatHide) : false;
        
                            if(jwsEndDate) {
                                jwsEndDate = jwsEndDate.split(' ');
                                jwsEndDate = new Date(jwsEndDate[0]);
                            }
        
                            this.setOptions({
                                minDate: new Date(),
                                maxDate: jwsEndDate
                            });
        
                            $(".xdsoft_time_variant").css('margin-top', '-600px');
                        },
                        onSelectDate: function() {
                            $('.jws-date-timepicker-start').datetimepicker('close');
        
                            $('.xdsoft_time').removeClass('xdsoft_current');
                        },
                        onClose: function( ct,$i ) {
                            startDate = ct;
        
                           
        
                           
                            $('body').removeClass('jws_background_overlay jws-lock');
        
                        },
                        onGenerate: function () {
                            if($('.jws-date-timepicker-start').val() == '') {
                                $('.xdsoft_time').removeClass('xdsoft_current');
                            }
                        }
                    });

                    $('.jws-date-timepicker-end').datetimepicker({
                        formatTime: 'H:i',
                        formatDate: '<?php echo esc_js($dFormat); ?>',
                        format:dateTimeFormat,
                        dayOfWeekStart: <?php echo get_option('start_of_week');?>,
                        defaultDate: jwsTomorrow,
                        defaultSelect: false,
                        closeOnDateSelect: false,
                        timeHeightInTimePicker: 40,
                        validateOnBlur: false,
                   
                        fixed: false,
              
                        onShow:function( ct ){
                            $('body').addClass('jws_background_overlay jws-lock');
        
                            var jwsStartDate = $('.jws-date-timepicker-start').val() ? moment(startDate).add(1, 'day').format(dateTimeFormatHide) : false;
        
                            if(jwsStartDate) {
                                jwsStartDate = jwsStartDate.split(' ');
                                jwsStartDate = new Date(jwsStartDate[0]);
                            } else {
                                jwsStartDate = new Date();
                            }
        
                            //if($('.jws-date-timepicker-end').val()) jwsStartDate = new Date($('.jws-date-timepicker-end').val().split(' ')[0]);
        
                            this.setOptions({
                                minDate: jwsStartDate
                            })
                        },
                        onSelectDate: function() {
                            $('.xdsoft_time').removeClass('xdsoft_current');
                            $('.jws-date-timepicker-end').datetimepicker('close');
                        },
                        onClose: function( ct, $i ) {
                            endDate = ct;
        
                            if(ct < new Date()) {
                                $('.jws-date-timepicker-end').datetimepicker('reset');
                            }
        
                            $('.jws-date-timepicker-end').attr('data-dt-hide', moment(ct).format('M/D/YYYY HH:mm'));
        
                         
                            var s = moment(startDate);
                            var e = moment(ct);
        
                            if(e.diff(s) < 0) {
                                s = s.add('days', 1);
        
                                $('.jws-date-timepicker-end').val('');
                                $('.jws-date-timepicker-end').attr('data-dt-hide', '');
        
                                s = s.format(dateTimeFormatHide);
                                s = s.split(' ');
                                s = new Date(s[0]);
        
                                this.setOptions({
                                    minDate: s,
                                    defaultDate: s
                                })
        
                                $('.jws-date-timepicker-end').datetimepicker(reset);
                            }
        
                            $('body').removeClass('jws_background_overlay jws-lock');
                        },
                        onGenerate: function () {
                            if($('.jws-date-timepicker-end').val() == '') {
                                $('.xdsoft_time').removeClass('xdsoft_current');
                            }
                        }
                    });
                    });
                 </script>
               <?php
                   $age_cat = (isset($jws_option['select_rent_age']) && !empty($jws_option['select_rent_age'])) ? $jws_option['select_rent_age'] : '';  
    
                   if(!empty($age_cat)) :  
				?>
                <div class="<?php echo ''.$columns3; ?>">
						<label for="formSearchAge"><?php esc_html_e( 'Driver&rsquo;s Age', 'idealauto' ); ?></label>
                       
						<select name="filter_<?php echo esc_attr($age_cat); ?>" type="text" class="form-control formSearchAge" id="formSearchAge"  placeholder="<?php echo esc_html( 'Driver&rsquo;s Age', 'idealauto' ); ?>" >
                        <option value="" > <?php esc_html_e( 'Please select an age', 'idealauto' ); ?> </option>
                           			<?php
                   
						  $cats = get_terms( 'pa_'.$age_cat, array( 'hide_empty' => '1' ) );

							$cat_age = '';
							if ( isset( $_GET[ 'filter_'.$age_cat][0] ) ) {
								$cat_age = sanitize_text_field( $_GET[ 'filter_'.$age_cat] );
							}
                   

							foreach ( $cats as $cat ) {
								if ( ! isset( $cat->name ) ) {
									continue;
								}
                       
								?>
								<option
									value='<?php echo (int) $cat->slug ?>'
									<?php
									if (!empty($cat_age)) {

										if ( $cat->slug == $cat_age ) {
											echo 'selected="selected"';
										}
									}

									?>

								><?php echo esc_html( $cat->name ); ?></option>
							<?php } ?>

						
                        
                        </select>
                        <i title="<?php echo esc_attr__('The minimum age to rent for all vehicles is 30. Renters aged 25 or older may rent the car categories Mini, Economy, Compact, Intermediate and Standard as well as Vans. No additional surcharges apply. Renters aged 19 years or older who have held a full driving licence for at least one year, can access a vehicle through Enterprise Car Club.','idealauto'); ?>" class="jws-icon-icon_info_alt"></i> 
				       
                	</div>
                    
                    <script>
                        jQuery(document).ready(function ($) {
                            $('.formSearchAge').select2({
                                placeholder: $('.formSearchAge').attr("placeholder"),
                                
                            });
                        });
                    </script>
                     <?php endif; ?>
                	<?php
                        $body_cat = (isset($jws_option['select_rent_body']) && !empty($jws_option['select_rent_body'])) ? $jws_option['select_rent_body'] : '';
                        if(!empty($body_cat)) :  
					?>
					<div class="<?php echo ''.$columns3; ?>">
						<label><?php esc_html_e( 'Vehicle Type', 'idealauto' ); ?></label>
					
						<select name="filter_<?php echo esc_attr($body_cat); ?>"
						        class="selectpicker input-price car_type" data-live-search="true"
						        data-width="100%"
						        data-toggle="tooltip" title="<?php esc_html_e( 'Select', 'idealauto' ); ?>" placeholder="<?php echo esc_html__( 'Vehicle Type', 'idealauto' ); ?>"   >
		                    <option value=""> <?php esc_html_e( 'Show me all', 'idealauto' ); ?> </option>
							<?php
					
                            $cats = get_terms( 'pa_'.$body_cat, array( 'hide_empty' => '1' ) );
                           
							$cat_grup = '';
							if ( isset( $_GET['filter_'.$body_cat][0] ) ) {
								$cat_grup = sanitize_text_field( $_GET['filter_'.$body_cat] );
							}

							foreach ( $cats as $cat ) {
								if ( ! isset( $cat->name ) ) {
									continue;
								}
								//var_dump($cat);
								?>
								<option
									value='<?php echo esc_attr($cat->slug) ?>'
									<?php
									if ( !empty($cat_grup) ) {

										if ( $cat->slug == $cat_grup ) {
											echo 'selected="selected"';
										}
								     }   

									?>

								><?php echo esc_html( $cat->name ); ?></option>
							<?php } ?>
						</select>
                        <i class="fas fa-car"></i>
                        
                        
					</div>
                     <script>
                        jQuery(document).ready(function ($) {
                            $('.car_type').select2({
                                placeholder: $('.car_type').attr("placeholder"),
                                
                            });
                             $( function() {
                                $( '.icon_info_alt' ).tooltip();
                              } );
                        });
                     </script>
                    <?php endif; ?>
                    <div class="<?php echo ''.$columns3; ?>">
						<label><?php esc_html_e( 'Promo Code', 'idealauto' ); ?></label>
                     <input autocomplete="off" class="" name="coupon_code" type="text" value="<?php if ( isset( $_GET['coupon_code'][0] ) ) {  echo ''.$_GET['coupon_code']; }  ?>" />
                     <i title="<?php echo esc_attr__('Use this field to enter a code for coupon or other special rate.','idealauto'); ?>" class="jws-icon-icon_info_alt"></i>   
					</div>
                    <?php echo wc_query_string_form_fields( null, array( 'dropin', 'dropoff' , 'start_date' , 'end_date' , 'filter_'.$age_cat , 'filter_'.$body_cat  , 'paged'  , 'coupon' ), '', true ); ?> 
                    <div class="<?php echo ''.$columns1; ?>">
    					<button type="submit" id="formSearchSubmit3"
    				        class="btn-theme"> <?php  esc_html_e('Check Availiability','idealauto'); ?><i class="jws-icon-icon_search2"></i>
    					</button>
                    </div>

                </div>
				</form>
			</div>
			<!-- /Search form -->
		</div>
        
        <?php

	}

	/**
	 * Render the widget output in the editor.
	 *
	 * Written as a Backbone JavaScript template and used to generate the live preview.
	 *
	 * @since 1.0.0
	 *
	 * @access protected
	 */
	protected function content_template() {}
}