<?php  

function car_compare() {

    $addToCompare = esc_html__('Add to compare', 'idealauto');

    if (empty($_COOKIE['compare_ids'])) {
        $compare_ids = array();
    } else {
        $compare_ids = $_COOKIE['compare_ids'];
    }
 

    
    $cars_taxonomy_array = jws_get_cars_taxonomy();
    $filter_options_label = jws_compare_column_fields();

    $empty_cars = 3 - count($compare_ids);
    $counter = 0;
    ob_start();
    ?>
    
    <div class="container">
        <?php if (!empty($compare_ids) or count($compare_ids) != 0): ?>
            <?php $args = array(
                'post_type' => 'cars',
                'post_status' => 'publish',
                'posts_per_page' => 100,

                'post__in' => $compare_ids,
            );
            $compares = new WP_Query($args);

            if ($compares->have_posts()): ?>
                <div class="row car-listing-row jws-car-compare-row">
                    <div class="col-xl-3 col-lg-3 hidden_mobile">
                        <h2 class="compare-title"><?php echo esc_html__('Compare', 'idealauto'); ?></h2>
                          <?php if (!empty($filter_options_label)): ?>
                            <div class="compare-options">
                                <table>
                                    <?php foreach ($filter_options_label as $key => $val): ?>
                                            <tr>
                                                <td class="compare-value-hover"
                                                    data-value="<?php echo esc_html( $key ); ?>">
                                                    <?php echo esc_html( $val ); ?>
                                                </td>
                                            </tr>
                                    
                                    <?php endforeach; ?>
                                </table>
                            </div>
                        <?php endif; ?>
                        <h4 class="jws-compare-features"><?php esc_html_e('Additional features', 'idealauto'); ?></h4>
                    </div>
                    <div class="col-xl-9">
                    <div class="compare-list">
                    <div class="compare-list-inner">                    
                    <?php while ($compares->have_posts()): $compares->the_post();
                        $counter++; ?>
                        <!--Compare car description-->
                        <div
                            class="compare-col-jws compare-col-jws-<?php echo esc_attr(get_the_ID()); ?>">
                          <div class="car-detail">
                              <a href="<?php the_permalink(); ?>" class="rmv_txt_drctn">
                                <div class="compare-col-jws-empty">
                                    <div class="image">
                                        <?php $car_images = get_post_meta( get_the_ID() , 'car_images',  true ); if(!empty($car_images)) {  ?>
                                            <div class="jws-compare-car-img">
                                              <?php
                                                $img_car = jws_getImageBySize(array('attach_id' => $car_images[0], 'thumb_size' => '408x235', 'class' => 'car-images-'.$car_images[0].''));
                                                echo ''.$img_car['thumbnail'];
                                              ?>
                                            </div>
                                        <?php } else { ?>
                                            <i class="jws-icon-art"></i>
                                        <?php }; ?>
                                    </div>
                                </div>
                            </a>
                            <div class="remove-compare-unlinkable">
									<span
                                        class="remove-from-compare"
                                        data-id="<?php echo esc_attr(get_the_ID()); ?>"
                                        data-action="remove">
										<i class="jws-icon-remove"></i>
										<span><?php esc_html_e('Remove from list', 'idealauto'); ?></span>
									</span>
                            </div>
                            <a href="<?php the_permalink(); ?>" class="rmv_txt_drctn">
                                <div class="listing-car-item-meta">
                                    <div class="car-meta-top heading-font clearfix">
                                    
                                              <?php jws_car_price_html( '', get_the_ID() , false, true ); ?>
                                 
                                       
                                        <div class="car-title"><?php the_title(); ?></div>
                                    </div>
                                </div>
                            </a>
                          </div>

                          <div class="compare-values">
                                 <table>    
                            <?php
                            foreach ( $filter_options_label as $key => $val ) {
                        			$cars_taxonomy = "car_$key";
                        			if ( in_array( $cars_taxonomy, $cars_taxonomy_array, true ) ) {
                        				?>
                        				<tr class="<?php echo esc_attr( $key ); ?>">
                        					<td data-id="<?php echo esc_attr( get_the_ID() ); ?>">
                        						<?php
                        						$car_year = wp_get_post_terms( get_the_ID(), $cars_taxonomy );
                        						if ( empty($car_year[0]->name) ) {
                        							echo '--';
                        						} else {
                        							echo esc_html( $car_year[0]->name );
                        						}
                        						?>
                        					</td>
                        				</tr>
                        				<?php
                        			}
                        	
                        	}
                            ?>
                                </table>
                                </div>
                                 <?php     
                                 
                                 $html = '';
				
                    
                    $terms = get_the_terms( get_the_ID() , 'car_features_options');
                    $cat_name = array();
                    $terms_check = array();
                    if($terms) {
                        foreach( $terms as $term ) {
                            $terms_check[] = $term->slug;
                            $term = get_term_by("id", $term->parent, "car_features_options");
                            
                            if (isset($term->parent) && $term->parent > 0) {
                                $term = get_term_by("id", $term->parent, "car_features_options");
                            }
                            if(isset($term->term_id)) {
                                $cat_obj = get_term($term->term_id, 'car_features_options');
                                $cat_name[] = $cat_obj->slug;  
                            }
                            
                        }
                    }

         
          
                    if(!empty($cat_name)) {
                        $cat_name = array_unique($cat_name);
                        $not_child = array();
                        foreach($cat_name as $key => $option) {

                                $category =  get_term_by( 'slug', $option, 'car_features_options' );
             
                                $ids = $category->term_id;
                                $label = $category->name;
                            
                                $childrens = get_categories(
                                  array(
                                    'taxonomy' => 'car_features_options',
                                    'parent' =>$ids,
                                    'hide_empty' => false
                                  )
                                );
                             
                                
                                if ( $childrens ) { 
                                    $html.= '<ul class="ct_ul_ol jws-compare-features-list">';
                                    foreach( $childrens as $children )
                                    { 
                                        if(in_array($children->slug, $terms_check)) {
                                           $html.= '<li><i class="jws-icon-icon_check"></i>'.esc_html( $children->name ).'</li>'; 
                                        }
                                        
                                    }
                                    $html.= '</ul>';
                                }else {
                                    $not_child[] = $option->slug ;
                                }
              
            		   } 
                        if(!empty($not_child)) {
                           $html.= '<ul class="ct_ul_ol jws-compare-features-list">';
                            foreach( $not_child as $children )
                            { 
                                $html.= '<li><i class="jws-icon-icon_check"></i>'.esc_html( $children ).'</li>';
                            }
                            $html.= '</ul>';  
                        } 
                     
                    }else {
        
                    $options = get_the_terms( get_the_ID() , 'car_features_options');
                
                      
					$html.= '<ul class="ct_ul_ol list-2 jws-compare-features-list">';
						  if(!empty($options)) {
    						    foreach ( $options as $option ) {
    							
    								$html.= '<li class="col-xl-4 col-lg-4 col-6"><i class="jws-icon-icon_check"></i>'.esc_html( $option->name ).'</li>';
    							
    							}  
						  }	
					$html.= '</ul>';
				
                    }

                    echo ''.$html;
                        			?>
                        </div> <!--md-3-->
                    <?php endwhile; ?>
           
                    </div>
                    </div>                    
                   </div> 
                </div> <!--row-->
            <?php endif; ?>
            
        <?php endif; ?>


    <div class="compare-empty-car-bottom">
        <?php if (!empty($filter_options_label)): ?>
            <div class="col-xl-3 col-lg-3">
                <div class="compare-options">
                    <table>
                        <?php foreach ($filter_options_label as $key => $val): ?>
                                <tr>
                                    <td class="compare-value-hover"
                                        data-value="<?php echo esc_html( $key ); ?>">
                                        <?php echo esc_html( $val ); ?>
                                    </td>
                                </tr>
                        
                        <?php endforeach; ?>
                    </table>
                </div>       
            </div>
        <?php endif; ?>
    </div>
     
    <script>
      jQuery(document).ready(function ($) {
        var heigth = 0;
        $('.compare-values table tbody tr td').each(function(){
            heigth = $(this).height();

            $('.' + $(this).attr('data-value')).each(function () {
                if($(this).height() > heigth || heigth > 0) {
                    heigth = $(this).height() + 18;
                    $('.' + $(this).attr('data-value')).css('height', heigth + 'px');
                }
            });
        });

        $('.compare-value-hover').on('hover', function () {
            var dataValue = $(this).data('value');
            $('.compare-value-hover[data-value = ' + dataValue + ']').addClass('hovered');
        }, function () {
            $('.compare-value-hover').removeClass('hovered');
        })
 
     function function_compare() {
           
                 var width = 0;
                $('.compare-col-jws').each(function() {
                    width += $(this).outerWidth( true );
                });
                $('.compare-col-jws').show();
                $('.compare-list-inner').css('width', width);
                
                console.log(width);
                
                const slider = document.querySelector('.compare-list');
                
                let isDown = false;
                let startX;
                let scrollLeft;
                
                slider.addEventListener('mousedown', e => {
                  isDown = true;
                  slider.classList.add('active');
                  startX = e.pageX - slider.offsetLeft;
                  scrollLeft = slider.scrollLeft;
                });
                slider.addEventListener('mouseleave', () => {
                  isDown = false;
                  slider.classList.remove('active');
                });
                slider.addEventListener('mouseup', () => {
                  isDown = false;
                  slider.classList.remove('active');
                });
                slider.addEventListener('mousemove', e => {
                  if (!isDown) return;
                  e.preventDefault();
                  const x = e.pageX - slider.offsetLeft;
                  const walk = (x - startX) * 2; //scroll-fast
                  slider.scrollLeft = scrollLeft - walk;
      
                });

     }
     
     function_compare();
    $(window).on("load resize",function(e){function_compare(); }); 
      
      
     $(document).on('click', '.remove-from-compare',  function(e){
         e.preventDefault();
        var $el = $(e.currentTarget);
        var dataId = $el.attr('data-id');
        var dataAction = $el.attr('data-action');
        function_compare();
        if (typeof dataId === 'undefined') {
            return;
        }
        
        
        $.ajax({
            url: jws_script.ajax_url,
            type: "POST",
            dataType: 'json',
            data: '&post_id=' + dataId + '&post_action=' + dataAction + '&action=jws_ajax_add_to_compare',
            context: this,
            beforeSend: function (data) {
                $el.addClass('loading');
                if (parseFloat($('.jws-current-cars-in-compare').text()) > 0) {
                    $('.jws-current-cars-in-compare').text(parseFloat($('.jws-current-cars-in-compare:first').text()) - 1);
                }

                $('.car-listing-row .compare-col-jws-' + dataId).remove();
                    $('.car-listing-row').append($('.compare-empty-car-top').html());

                $('.jws-compare-row .compare-col-jws-' + dataId).remove();
                    $('.jws-compare-row').append($('.compare-empty-car-bottom').html());
                 $('.row-compare-features .compare-col-jws-' + dataId).remove();
                    if ($('.row-compare-features .col-md-3').length < 2) {
                        $('.row-compare-features').slideUp();
                    }
                
            }
        });
     });
        })
    </script>
    <?php return ob_get_clean(); ?>

<?php }

if(function_exists('insert_shortcode')){
	insert_shortcode('car_compare_shortcode','car_compare');
}

if ( ! function_exists( 'jws_compare_column_fields' ) ) {
	/**
	 * Compare column field
	 */
	function jws_compare_column_fields() {

		$data = array(
	
	
			'year'             => esc_html__( 'Year', 'idealauto' ),
			'make'             => esc_html__( 'Make', 'idealauto' ),
			'model'            => esc_html__( 'Model', 'idealauto' ),
			'body_style'       => esc_html__( 'Body Style', 'idealauto' ),
			'mileage'          => esc_html__( 'Mileage', 'idealauto' ),
			'fuel_economy'     => esc_html__( 'Fuel Economy', 'idealauto' ),
			'transmission'     => esc_html__( 'Transmission', 'idealauto' ),
			'condition'        => esc_html__( 'Condition', 'idealauto' ),
			'drivetrain'       => esc_html__( 'Drivetrain', 'idealauto' ),
			'engine'           => esc_html__( 'Engine', 'idealauto' ),
			'exterior_color'   => esc_html__( 'Exterior Color', 'idealauto' ),
			'interior_color'   => esc_html__( 'Interior Color', 'idealauto' ),
			'stock_number'     => esc_html__( 'Stock Number', 'idealauto' ),
			'vin_number'       => esc_html__( 'Vin Number', 'idealauto' ),
		);
		/**
		 * Filters the array of vehicle attributes label displayed in compare vehicle pop-up.
		 *
		 * @since 1.0
		 * @return          Array of vehicle attributes label displayed in compare pop-up.
		 * @visible         true
		 */
		$data = apply_filters( 'jws_compare_column_fields', $data );
		return $data;
	}
}

if ( ! function_exists( 'jws_compare_column_attributes_data' ) ) {
	/**
	 * Compare column delete
	 *
	 * @param string $compare_fields .
	 * @param string $class .
	 * @param string $car_id .
	 */
	function jws_compare_column_attributes_data( $compare_fields, $class, $car_id ) {
		$cars_taxonomy_array = jws_get_cars_taxonomy();
		foreach ( $compare_fields as $key => $val ) {
			$cars_taxonomy = "car_$key";
			if ( in_array( $cars_taxonomy, $cars_taxonomy_array, true ) ) {
				?>
				<tr class="<?php echo esc_attr( $key ); ?>">
					<td class="<?php echo esc_attr( $class ); ?>" data-id="<?php echo esc_attr( $car_id ); ?>">
						<?php
						$car_year = wp_get_post_terms( $car_id, $cars_taxonomy );
						if ( ! isset( $car_year ) || empty( $car_year ) ) {
							echo '&nbsp;';
						} else {
							echo esc_html( $car_year[0]->name );
						}
						?>
					</td>
				</tr>
				<?php
			}
	
		}
	}
}


//Ajax add to compare
function jws_ajax_add_to_compare()
{


    $response['response'] = '';
    $response['status'] = '';
    $response['empty'] = '';
    $response['empty_table'] = '';
    $response['add_to_text'] = esc_html__( 'Add to compare', 'idealauto' );
    $response['in_com_text'] = esc_html__( 'In compare list', 'idealauto' );
    $response['remove_text'] = esc_html__( 'Remove from list', 'idealauto' );

    if ( empty( $_COOKIE['compare_ids'] ) ) {
        $_COOKIE['compare_ids'] = array();
    }
    if ( !empty( $_POST['post_action'] ) and $_POST['post_action'] == 'remove' ) {
        if ( !empty( $_POST['post_id'] ) ) {
            $new_post = intval( $_POST['post_id'] );
            setcookie( 'compare_ids[' . $new_post . ']', '', time() - 3600, '/' );
            unset( $_COOKIE['compare_ids'][$new_post] );

            $response['status'] = 'success';
            $response['response'] = get_the_title( $_POST['post_id'] ) . ' ' . esc_html__( 'was removed from compare', 'idealauto' );
        }
    } else {
        if ( !empty( $_POST['post_id'] ) ) {
            $new_post = intval($_POST['post_id']);
            if ( !in_array( $new_post, $_COOKIE['compare_ids'] ) ) {
             
                    setcookie( 'compare_ids[' . $new_post . ']', $new_post, time() + ( 86400 * 30 ), '/' );
                    $_COOKIE['compare_ids'][$new_post] = $new_post;
                    $response['status'] = 'success';
                    $response['response'] = get_the_title( $_POST['post_id'] ) . ' - ' . esc_html__( 'Added to compare', 'idealauto' );
               
            } else {
                $response['status'] = 'warning';
                $response['response'] = get_the_title( $_POST['post_id'] ) . ' ' . esc_html__( 'has been added', 'idealauto' );
            }
        }
    }

    $response['length'] = count( $_COOKIE['compare_ids'] );

    $response['ids'] = $_COOKIE['compare_ids'];

    wp_send_json( $response );
    exit;
}

add_action( 'wp_ajax_jws_ajax_add_to_compare', 'jws_ajax_add_to_compare' );
add_action( 'wp_ajax_nopriv_jws_ajax_add_to_compare', 'jws_ajax_add_to_compare' );