<?php 
if ( ! defined( 'ABSPATH' ) ) {
	exit( 'Direct script access denied.' );
}

function check_km_location($origin,$destination) {
           global $jws_option; 
           require_once( ABSPATH.'/wp-admin/includes/file.php' ); 
           WP_Filesystem();
           global $wp_filesystem;
	   
    			$api =  ( isset( $jws_option['google_api'] ) && '' !== $jws_option['google_api'] ) ? $jws_option['google_api'] : '';
                
    	
           // In metric unit. This is default
           $distance_data = $wp_filesystem->get_contents('https://maps.googleapis.com/maps/api/distancematrix/json?&origins='.urlencode($origin).'&destinations='.urlencode($destination).'&key='.$api.'');

           $distance_arr = json_decode($distance_data);
        
        if ($distance_arr->status=='OK') {
            $destination_addresses = $distance_arr->destination_addresses[0];
            $origin_addresses = $distance_arr->origin_addresses[0];
        } else {
          return false;
          exit();
        }
        
           if ($origin_addresses=="" or $destination_addresses=="") {
              return "<p>Destination or origin address not found</p>";
              exit();
           }
        
           // Get the elements as array
           $elements = $distance_arr->rows[0]->elements;
           
           if($elements[0]->status == 'OK') {
               $distance = $elements[0]->distance->value;
                
           }else {
              $distance = '10000000000000000000000000000000000';  
           }
           
           
           return $distance;
                   
}         


function dealer_review_html($ratings) {
   ?>
    <div class="inner">
        <div class="jws-star-rating-upper"
             style="width:<?php echo esc_attr($ratings['average_width']); ?>"></div>
        <div class="jws-star-rating-lower"></div>
    </div>
    <span class="rating-count"><?php echo esc_attr($ratings['average']); ?> (<?php echo esc_html($ratings['count']).esc_html__(' reviews','idealauto'); ?>)</span>
  <?php
}

function return_dealer_id_from_query() {
    $args = array(
            'post_type'     => 'cars',
            'post_status'   => 'publish',
            'posts_per_page' => -1
        );
     if(isset($_GET['make_dealer']) && !empty($_GET['make_dealer'])) {
        $args['meta_query'][] = array(
			'key'   => 'make',
			'value'   => $_GET['make_dealer'],
            'compare'   => 'LIKE'
		);
     } 
    $post_query = get_posts($args);  
    $author_name = array();

    foreach ( $post_query as $post ) {

       $author_name[] += $post->post_author;
    }

    return $author_name;
                
}

function return_zipcode_from_distance() { 
   $args_all_user = array(
      'order' => 'DESC',
   );  
   $all_user = new WP_User_Query($args_all_user); 
   $zipcode = array();
   if(!empty($all_user) && (isset($_GET['zipcode']) && isset($_GET['dealer_radius']))) {
        foreach ( $all_user->get_results() as $all_users ) {  
       
            $author_id = $all_users->ID;
            $long = get_field('dealer_location', 'user_'. $author_id );
            if(!empty($long)) {
                
                $lat_lng = getLnt($_GET['zipcode']);
                if(!empty($lat_lng)) {
                    $check = check_km_location($long['lat'],$long['lng'],$lat_lng['lat'],$lat_lng['lng']);
                }else{
                    $check = '';
                }

                if($_GET['dealer_radius'] > $check && !empty($check)) {
                      $zipcode[] = $long['post_code'];
                     
                }else{
                   $zipcode[] = $_GET['zipcode'];
                }

            }

        }
  } 
  return $zipcode;
}

if( ! function_exists( 'jws_ajax_load_dealer_content' ) ) {
    	function jws_ajax_load_dealer_content() {
    	      
      
            get_template_part( 'template-parts/content/dealer/content','dealer' );
     
    		die();
    	}
        // Note: Keep default AJAX actions in case WooCommerce endpoint URL is unavailable
        add_action('wp_ajax_jws_ajax_load_dealer_content', 'jws_ajax_load_dealer_content');
        add_action('wp_ajax_nopriv_jws_ajax_load_dealer_content', 'jws_ajax_load_dealer_content'); 
}   


function get_cars_number_in_dealer($user_id, $post_type = 'cars')
{
    $args = array(
        'post_type'      => $post_type,
        'author'         => $user_id,
        'post_status'    => 'publish',
        'posts_per_page' => -1
    );

    $query = new WP_Query($args);

    return $query->found_posts;
}

if ( !function_exists( 'jws_submit_review' ) ) {
    function jws_submit_review()
    {

        //check_ajax_referer( 'jws_submit_review', 'security' );
        global $jws_option;
        $response = array();
        $response['message'] = '';
        $error = false;
        $user_id = 0;

        $demo = false;

        if ( $demo ) {
            $error = true;
            $response['message'] = esc_html__( 'Site is on demo mode.', 'idealauto' );
        }

        /*Post parts*/
        $title = '';
        $content = '';
    
        $ratings = array();

        if ( !empty( $_POST['jws_title'] ) ) {
            $title = sanitize_text_field( $_POST['jws_title'] );
        } else {
            $error = true;
            $response['message'] = esc_html__( 'Please, enter review title.', 'idealauto' );
        }

        if ( empty( $_POST['jws_user_on'] ) ) {
            $error = true;
            $response['message'] = esc_html__( 'Do not cheat!', 'idealauto' );
        } else {
            $user_on = intval( $_POST['jws_user_on'] );
        }

        if ( !empty( $_POST['jws_content'] ) ) {
            $content = sanitize_text_field( $_POST['jws_content'] );
        } else {
            $error = true;
            $response['message'] = esc_html__( 'Please, enter review text.', 'idealauto' );
        }

        if ( empty( $_POST['jws_required'] ) ) {
            $error = true;
            $response['message'] = esc_html__( 'Please, check you are not a dealer.', 'idealauto' );
        } else {
            if ( $_POST['jws_required'] !== 'on' ) {
                $error = true;
                $response['message'] = esc_html__( 'Please, check you are not a dealer.', 'idealauto' );
            }
        }

        if ( empty( $_POST['jws_rate'] ) ) {
            $error = true;
            $response['message'] = esc_html__( 'Please add rating', 'idealauto' );
        } 

        /*Check if user already added comment*/
        $current_user = wp_get_current_user();
        if ( is_wp_error( $current_user ) ) {
            $error = true;
            $response['message'] = esc_html__( 'You are not logged in', 'idealauto' );
        } else {
            if ( !empty( $user_on ) ) {
                $user_id = $current_user->ID;
                $get_user_reviews = jws_get_user_reviews( $user_id, $user_on );

                $response['q'] = $get_user_reviews;

                if ( !empty( $get_user_reviews->posts ) ) {
                    foreach ( $get_user_reviews->posts as $user_post ) {
                        wp_delete_post( $user_post->ID, true );
                    }
                }
            } else {
                $error = true;
                $response['message'] = esc_html__( 'Do not cheat', 'idealauto' );
            }
        }

        if ( !$error ) {

            if ( $jws_option['dealer_review_pending'] )
                $post_status = 'pending';
            else
                $post_status = 'publish';

            $post_data = array(
                'post_type' => 'dealer_review',
                'post_title' => sanitize_text_field( $title ),
                'post_content' => sanitize_text_field( $content ),
                'post_status' => $post_status
            );

            $insert_post = wp_insert_post( $post_data, true );
            //$insert_post = 0;

            if ( is_wp_error( $insert_post ) ) {
                $response['message'] = $insert_post->get_error_message();
            } else {

                /*Ratings*/
                if ( !empty($_POST['jws_rate']) ) {
                    update_post_meta( $insert_post, 'jws_rate', intval( $_POST['jws_rate'] ) );
                }

                update_post_meta( $insert_post, 'dealer_review_added_by', $user_id );
                update_post_meta( $insert_post, 'dealer_review_added_on', $user_on );

                $response['updated'] = get_author_posts_url($user_on) . '#jws_d_rev';


            }

        }

        wp_send_json( $response );
        exit;
    }
}

add_action( 'wp_ajax_jws_submit_review', 'jws_submit_review' );
add_action( 'wp_ajax_nopriv_jws_submit_review', 'jws_submit_review' );


if ( !function_exists( 'jws_get_dealer_reviews' ) ) {
    function jws_get_dealer_reviews( $dealer_id = '', $per_page = 6, $offset = 0 )
    {
        if ( !empty( $dealer_id ) ) {
            $args = array(
                'post_type' => 'dealer_review',
                'posts_per_page' => intval( $per_page ),
                'offset' => intval( $offset ),
                'post_status' => 'publish',
                'meta_query' => array(
                    array(
                        'key' => 'dealer_review_added_on',
                        'value' => intval( $dealer_id ),
                        'compare' => '='
                    )
                )
            );

            $query = new WP_Query( $args );

            return $query;
        }
    }
}

if ( !function_exists( 'jws_get_user_reviews' ) ) {
    function jws_get_user_reviews( $dealer_id = '', $dealer_id_from = '' )
    {
        if ( !empty( $dealer_id ) and !empty( $dealer_id_from ) ) {
            $args = array(
                'post_type' => 'dealer_review',
                'post_status' => 'publish',
                'meta_query' => array(
                    array(
                        'key' => 'dealer_review_added_by',
                        'value' => intval( $dealer_id ),
                        'compare' => '='
                    ),
                    array(
                        'key' => 'dealer_review_added_on',
                        'value' => intval( $dealer_id_from ),
                        'compare' => '='
                    )
                )
            );

            $query = new WP_Query( $args );

            return $query;
        }
    }
}

//Add car helpers

if ( !function_exists( 'jws_get_dealer_marks' ) ) {
    function jws_get_dealer_marks( $dealer_id = '' )
    {
        if ( !empty( $dealer_id ) ) {
            $args = array(
                'post_type' => 'dealer_review',
                'posts_per_page' => -1,
                'post_status' => 'publish',
                'meta_query' => array(
                    array(
                        'key' => 'dealer_review_added_on',
                        'value' => intval( $dealer_id ),
                        'compare' => '='
                    )
                )
            );

            $query = new WP_Query( $args );
            
            $querys = get_posts( $args );
            
            $ratings = array(
                'average' => 0,
                'rate' => 0,
                'count' => 0
            );
            
            
            foreach($querys as $query) {
                  
                  
                    $rate = get_post_meta( $query->ID, 'jws_rate', true );
   
                    if ( !empty( $rate ) ) {
                
                        $ratings['rate'] = intval( $rate );
                    }
                    $total = count( $querys );

                   
                    $ratings['count'] = $total;
    
                    $average_num = 0;
 
                    $ratings['rate'] = round( $ratings['rate'] / $ratings['count'], 1 );
    
                    $ratings['rate_width'] = ( ( $ratings['rate'] * 100 ) / 5 ) . '%';
    
                    $ratings['average'] = $ratings['average'] + $ratings['rate'];
    
                    $average_num++;

    
                    $ratings['average'] = number_format( round( $ratings['average'] / $average_num, 1 ), '1', '.', '' );
                    $ratings['average_width'] = ( ( $ratings['average'] * 100 ) / 5 ) . '%';
    
       
            }

            return $ratings;
        }
    }
}
if(!function_exists('jws_display_user_name')) {
    function jws_display_user_name( $user_id, $user_login = '', $f_name = '', $l_name = '' )
    {
       

        $display_name = get_the_author_meta('display_name',$user_id);


        echo apply_filters( 'jws_filter_display_user_name', $display_name, $user_id, $user_login, $f_name, $l_name );

    }
}

if (!function_exists('jws_user_listings_query')) {

    function jws_user_listings_query($user_id, $status = "any", $per_page = -1, $popular = false, $offset = 0, $data_desc = false, $getAll = false)
    {
        $ppl = ($getAll) ? array() : array( 'key' => 'pay_per_listing', 'compare' => 'NOT EXISTS', 'value' => '' );

        $args = array(
            'post_type' => 'cars',
            'post_status' => $status,
            'posts_per_page' => $per_page,
            'offset' => $offset,
            'author' => $user_id,
        );

        if ($popular) {
            $args['order'] = 'ASC';
            $args['orderby'] = 'jws_car_views';
        }

        $query = new WP_Query($args);
        wp_reset_postdata();

        return $query;

    }
}


if (!function_exists('jws_get_post_limits')) {
    /**
     * Get user adds and media limitations
     *
     * @param $user_id
     *
     * @return mixed|void
     */
    function jws_get_post_limits($user_id, $type = '')
    {
        $user_id = intval($user_id);
        global $jws_option;
        $restrictions = array(
            'posts' => 0,
            'images' => 0,
        );

        if (!empty($user_id)) {

            $created_posts = 0;

            $post_status = array('publish', 'pending', 'draft');

            $args = array(
                'post_type' => 'cars',
                'post_status' => $post_status,
                'posts_per_page' => -1,
                'meta_query' => array(
                    'relation' => 'AND',
                    array(
                        'key' => 'jws_car_user',
                        'value' => $user_id,
                        'compare' => '='
                    ),

                )
            );

            $query = new WP_Query($args);

            if (!empty($query->found_posts)) {
                $created_posts = intval($query->found_posts);
            }


            $posts_allowed = (isset($jws_option)) ? $jws_option['jws_cars_limit'] : '5';
            $restrictions['posts_allowed'] = intval($posts_allowed);
            //$restrictions['premoderation'] = get_theme_mod('user_premoderation', true);
            $restrictions['images'] = isset($jws_option['jws_image_limit']) ? $jws_option['jws_image_limit'] : '100';
            $restrictions['role'] = 'user';
            
            if ( class_exists( 'Subscriptio' ) || class_exists( 'RP_SUB' ) ) {
				$user_subscriptions = array();

				if ( function_exists( 'subscriptio_get_customer_subscriptions' ) ) {
					$user_subscriptions = subscriptio_get_customer_subscriptions( $user_id );
				}

				if ( ! empty( $user_subscriptions ) ) {

					$user_subscription = reset( $user_subscriptions );

					$status = $user_subscription->get_status();

					$_product_id = '';

					if ( 'active' === $status ) {
						$posts_allowed = intval( get_user_meta( $user_id, 'jws_car_limt', true ) );
                        $restrictions['images'] = intval( get_user_meta( $user_id, 'jws_img_limt', true ) );
					}
				}
			}
            
            $user_can_create = intval($posts_allowed) - intval($created_posts);

            if ($user_can_create < 1) {
                $user_can_create = 0;
            }

            $restrictions['posts'] = intval($user_can_create);
            
            
        } else {
            //$restrictions['premoderation'] = get_theme_mod('user_premoderation', true);
            $restrictions['posts'] = isset($jws_option) ? $jws_option['jws_cars_limit'] : '5';
            $restrictions['images'] = isset($jws_option['jws_image_limit']) ? $jws_option['jws_image_limit'] : '100';
            $restrictions['role'] = 'user';
        }

        /*IF is admin, set all */
        if (user_can($user_id, 'manage_options')) {
            //$restrictions['premoderation'] = false;
            $restrictions['posts'] = '9999';
            $restrictions['images'] = '9999';
            $restrictions['role'] = 'user';
        }

        return apply_filters('jws_filter_user_restrictions', $restrictions, $user_id, $type);

    }
}

add_action( 'subscriptio_subscription_status_changing', 'jws_subscription_status_changing', 10, 3 );
/**
 * Subscription status changing
 *
 * @param string $subscription .
 * @param string $old_status .
 * @param string $new_status .
 */
function jws_subscription_status_changing( $subscription, $old_status, $new_status ) {

	$temp_car_limt = 0;

	$subscription_id = $subscription->get_id();
	$customer_id     = $subscription->get_customer_id();

	$user_car_limt = get_user_meta( $customer_id, 'jws_car_limt', true );
	$user_img_limt = get_user_meta( $customer_id, 'jws_img_limt', true );

	$user_car_limt = ( $user_car_limt < 1 ) ? 0 : intval( $user_car_limt );
	$user_img_limt = ( $user_img_limt < 1 ) ? 0 : intval( $user_img_limt );

	$subscription_car_limt = get_post_meta( $subscription_id, 'jws_car_limt', true );
	$subscription_img_limt = get_post_meta( $subscription_id, 'jws_img_limt', true );

	$subscription_car_limt = intval( $subscription_car_limt );

	if ( 'pending' !== $old_status ) {
		if ( 'active' === $new_status ) {
			$temp_car_limt = $user_car_limt + $subscription_car_limt;
			$temp_car_limt = ( $temp_car_limt < 1 ) ? 0 : intval( $temp_car_limt );

			update_user_meta( $customer_id, 'jws_car_limt', $temp_car_limt );
		}

		if ( 'paused' === $new_status || 'set-to-cancel' === $new_status || 'cancelled' === $new_status ) {
			$temp_car_limt = $user_car_limt - $subscription_car_limt;
			$temp_car_limt = ( $temp_car_limt < 1 ) ? 0 : intval( $temp_car_limt );

			update_user_meta( $customer_id, 'jws_car_limt', $temp_car_limt );
		}
	} else {
		if ( 'active' === $new_status ) {
			$items = $subscription->get_items();
			foreach ( $items as $item ) {
				$_product_id = $item->get_product_id();
				if ( subscriptio_is_subscription_product( $_product_id ) ) {

					$post_limit  = intval( get_post_meta( $_product_id, 'jws_car_quota', true ) );
					$image_limit = intval( get_post_meta( $_product_id, 'jws_car_images_quota', true ) );

					$jws_img_limit = intval( $image_limit );
					$jws_car_limit = intval( $user_car_limt ) + intval( $post_limit );

					$subscription_img_limt = intval( $image_limit );
					$subscription_car_limt = intval( $subscription_car_limt ) + intval( $post_limit );

					update_post_meta( $subscription_id, 'jws_car_limt', $subscription_car_limt );
					update_post_meta( $subscription_id, 'jws_img_limt', $subscription_img_limt );

					update_user_meta( $customer_id, 'jws_car_limt', $jws_car_limit );
					update_user_meta( $customer_id, 'jws_img_limt', $jws_img_limit );
				}
			}
		}
	}

}


add_action( 'woocommerce_thankyou', 'jws_custom_process_order', 10, 1 );

if ( ! function_exists( 'jws_custom_process_order' ) ) {
	/**
	 * Add/update meta after order place.
	 *
	 * @param string $order_id .
	 */
	function jws_custom_process_order( $order_id ) {
		if ( class_exists( 'Subscriptio' ) || class_exists( 'RP_SUB' ) ) {
			$order   = new WC_Order( $order_id );
			$data    = $order->get_data();
			$items   = $order->get_items();
			$user_id = $order->get_user_id();

			$jws_car_limit = 0;
			$jws_img_limit = 0;

			foreach ( $items as $item ) {
				$product_id     = $item->get_product_id();
				$post_limit     = get_post_meta( $product_id, 'jws_car_quota', true );
				$image_limit    = get_post_meta( $product_id, 'jws_car_images_quota', true );
				$is_subscriptio = ( get_post_meta( $product_id, '_subscriptio', true ) );

				if ( 'yes' === $is_subscriptio ) {
					$user_car_limt = get_user_meta( $user_id, 'jws_car_limt', true );
					$user_img_limt = get_user_meta( $user_id, 'jws_img_limt', true );

					$user_car_limt = ( $user_car_limt < 1 ) ? 0 : intval( $user_car_limt );
					$user_img_limt = ( $user_img_limt < 1 ) ? 0 : intval( $user_img_limt );

					$post_limit  = intval( get_post_meta( $product_id, 'jws_car_quota', true ) );
					$image_limit = intval( get_post_meta( $product_id, 'jws_car_images_quota', true ) );

					$jws_car_limit = intval( $user_car_limt ) + intval( $post_limit );
					$jws_img_limit = intval( $image_limit );

					update_user_meta( $user_id, 'jws_car_limt', $jws_car_limit );
					update_user_meta( $user_id, 'jws_img_limt', $jws_img_limit );
				}
			}
		}
		return $order_id;
	}
}

function jws_dealer_filter() {
    
    global $jws_option;
    $olumns = 'dealer-item';
    ?>
       <div class="form-search-dealer">
         <form action="http://idealauto.jwsuperthemes.com/dealer-list/" method="get">

                  <div class="<?php echo esc_attr($olumns); ?>">
                      <?php 
                        $address_value = (isset($_GET['address']) && !empty($_GET['address'])) ?  $address_value = $_GET['address'] : '';
                      ?>      
                      <label> <?php echo esc_html__('Your location','idealauto'); ?> </label>
                      <input class="item-dealer-filters" id="pac-input" data-id="address"  type="text"  placeholder="<?php echo esc_attr__('ZIP code, City or State','idealauto'); ?>" name="address" value="<?php echo esc_attr($address_value); ?>">
                 </div> 
                <div class="<?php echo esc_attr($olumns); ?>">
                    <label> <?php echo esc_html__('Make','idealauto'); ?> </label>
                    <?php 
                        $taxonomies = get_terms( array(
                            'taxonomy' => 'car_make',
                            'hide_empty' => true,
                        ) );
                         
                        if ( !empty($taxonomies) ) :
                           $selected = ( isset( $_GET['make_dealer'] ) ) ? esc_html( $_GET['make_dealer'] ) : '';
                            $output = '<select class="item-dealer-filters" data-id="make_dealer" name="make_dealer">';
                            $output .= '<option value="" > '.esc_html__( 'Any Make', 'idealauto' ).'</option>';
                            foreach( $taxonomies as $category ) {
                                $active = $selected == $category->term_id
                                        				? 'selected '
                                        				: '';
                                $output.= '<option '.$active.' value="'. esc_attr( $category->term_id ) .'">
                                    '. esc_html( $category->name ) .'</option>';
            
                                }
                                $output.='</select>';
                                echo ''.$output;
                         endif;
                    ?>
                </div>
          
             <div class="<?php echo esc_attr($olumns); ?>">
                  <label> <?php echo esc_html__('Search radius','idealauto'); ?> </label>   
                 <select class="item-dealer-filters" data-id="dealer_radius" name="dealer_radius">
                    <?php 
                        $distance = $jws_option['dealer_distance'];
                       $selected = ( isset( $_GET['dealer_radius'] ) ) ? esc_html( $_GET['dealer_radius'] ) : '';
				    
                        if(!empty($distance)) {
                            echo '<option value="" > '.esc_html__( 'Distance', 'idealauto' ).'</option>';
                            foreach( $distance  as $distance_item ) {
                            $active = $selected == $distance_item
                                				? 'selected '
                                				: '';
                            echo '<option '.$active.' value="'. esc_attr($distance_item ) .'">
                                '. esc_html( $distance_item ) .' km</option>';
                            }   
                        }  
                    ?>
              </select>
             </div> 
              
              <div class="<?php echo esc_attr($olumns); ?>">
                <label> <?php echo esc_html__('Results','idealauto'); ?> </label>
                  <?php 
                    $results_value = (isset($_GET['results']) && !empty($_GET['results'])) ?  $address_value = $_GET['results'] : '';
                  ?>      
                  <select class="item-dealer-filters" name="results" data-id="results">
                         <?php 
                           $result = $jws_option['dealer_results'];
                           $selected = ( isset( $_GET['dealer_results'] ) ) ? esc_html( $_GET['dealer_results'] ) : '';
    				    
                            if(!empty($result)) {
                                echo '<option value="" > '.esc_html__( 'All Results', 'idealauto' ).'</option>';
                                foreach( $result  as $result_item ) {
                                $active = $selected == $result_item
                                    				? 'selected '
                                    				: '';
                                echo '<option '.$active.' value="'. esc_attr($result_item ) .'">
                                    '. esc_html( $result_item ) .'</option>';
                                }   
                            }  
                        ?>
                  </select>  
             </div>  
            <div class="<?php echo esc_attr($olumns); ?>">
            
                        <button id="filter-dealer" class="filter-dealer"><?php echo esc_html__('Search','idealauto'); ?></button>  
           
            </div>
            <input class="item-dealer-filters dealer-lat" data-id="lat" type="hidden" name="lat" value="<?php echo (isset($_GET['lat']) && !empty($_GET['lat'])) ? $_GET['lat'] : ''; ?>"/>
            <input class="item-dealer-filters dealer-lng" data-id="lng" type="hidden" name="lng" value="<?php echo (isset($_GET['lng']) && !empty($_GET['lng'])) ?  $_GET['lng'] : ''; ?>"/>
    
              
          </form>
        </div>
    <?php  
}


add_action( 'show_user_profile', 'jws_car_list_user_profile_fields' );
add_action( 'edit_user_profile', 'jws_car_list_user_profile_fields' );

function jws_car_list_user_profile_fields( $user ) { ?>
    <h3><?php echo esc_html__("User Car List", "idealauto"); ?></h3>
    <p><?php echo esc_html__("Checkbox to public the cars", "idealauto"); ?></p>
    <div class="jws_cars_user_list_ad">
    <ul>
    <?php 

        $args = array(
            'post_type'      => 'cars',
            'author'         => $user->ID,
            'post_status' => array('publish', 'pending'),
            'posts_per_page' => -1
        );

        $query = new WP_Query($args);
        
        if ( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post();
        $checkked = '';
        if(get_post_status() == 'publish') {
          $checkked  = 'checked="checked"';
        }
        
        ?>
            <li>
                <span data-id="<?php echo get_the_ID(); ?>">
                    <input type="checkbox" <?php echo esc_attr($checkked); ?>/>
                    <label><?php the_title(); ?></label>
                </span>
            </li>
        
        <?php
        
        endwhile;
        endif;
        wp_reset_postdata();
            
    ?>
    </ul>
    </div>
<?php }


function jws_change_status_cars_form_user() {
    if($_POST['status'] == 'pen') {
        $status = 'pending';
    }else {
       $status = 'publish'; 
    }
    
    // Puslish post 37
    $my_post = array(
      'ID'           => $_POST['id'],
      'post_status'   => $status,
    );
      
    // Update the post into the database
    wp_update_post( $my_post );
}  
   
    
add_action( 'wp_ajax_jws_change_status_cars_form_user', 'jws_change_status_cars_form_user');
add_action( 'wp_ajax_jws_change_status_cars_form_user', 'jws_change_status_cars_form_user' );