<?php 

//Function add to favourites
function jws_ajax_add_to_favourites()
{


    $response = array();
    $count = 0;

    if ( !empty( $_POST['car_id'] ) ) {
        $car_id = intval( $_POST['car_id'] );
        $post_status = get_post_status( $car_id );

        if ( !$post_status ) {
            $post_status = 'deleted';
        }

        if ( is_user_logged_in() and $post_status == 'publish' or $post_status == 'pending' or $post_status == 'draft' or $post_status == 'deleted' ) {
            $user = wp_get_current_user();
            $user_id = $user->ID;
            $user_added_fav = get_the_author_meta( 'jws_user_favourites', $user_id );
            if ( empty( $user_added_fav ) ) {
                update_user_meta( $user_id, 'jws_user_favourites', $car_id );
            } else {
                $user_added_fav = array_filter( explode( ',', $user_added_fav ) );
                $response['fil'] = $user_added_fav;
                $response['id'] = $car_id;
                if ( in_array( strval( $car_id ), $user_added_fav ) ) {
                    $user_added_fav = array_diff( $user_added_fav, array( $car_id ) );
                } else {
                    $user_added_fav[] = $car_id;
                }
                $user_added_fav = implode( ',', $user_added_fav );

                update_user_meta( $user_id, 'jws_user_favourites', $user_added_fav );
            }

            $user_added_fav = get_the_author_meta( 'jws_user_favourites', $user_id );
            $user_added_fav = count( array_filter( explode( ',', $user_added_fav ) ) );
            $response['count'] = intval( $user_added_fav );
        }
    }

    wp_send_json( $response );
    exit;
}

add_action( 'wp_ajax_jws_ajax_add_to_favourites', 'jws_ajax_add_to_favourites' );
add_action( 'wp_ajax_nopriv_jws_ajax_add_to_favourites', 'jws_ajax_add_to_favourites' );

function jws_ajax_get_favourites()
{


    $ids = array_filter(
        explode( ',', get_the_author_meta( 'jws_user_favourites', get_current_user_id() ) )
    );

    wp_send_json( $ids );
    exit;
}

add_action( 'wp_ajax_jws_ajax_get_favourites', 'jws_ajax_get_favourites' );
?>