<?php
defined( 'ABSPATH' ) || exit; // Exit if accessed directly
add_action( 'wp_ajax_nopriv_kanews_bookmark_process', 'kanews_bookmark_process' );
add_action( 'wp_ajax_kanews_bookmark_process', 'kanews_bookmark_process' );
function kanews_bookmark_process() {
	// Security
	$nonce = isset( $_REQUEST['nonce'] ) ? sanitize_text_field( $_REQUEST['nonce'] ) : 0;
	if ( !wp_verify_nonce( $nonce, 'kanews-bookmark-nonce' ) ) {
		exit( __( 'İzin verilmedi!', 'kanews' ) );
	}
	// Test if javascript is disabled
	$disabled = ( isset( $_REQUEST['disabled'] ) && $_REQUEST['disabled'] == true ) ? true : false;

	// Base variables
	$post_id = ( isset( $_REQUEST['post_id'] ) && is_numeric( $_REQUEST['post_id'] ) ) ? $_REQUEST['post_id'] : '';
	$result = array();
	$post_users = NULL;
	// Get plugin options
	if ( $post_id != '' ) {
		if ( !already_bookmarked( $post_id ) ) { // Like the post
			if ( is_user_logged_in() ) { // user is logged in
				$user_id = get_current_user_id();
				$post_users = post_user_likes( $user_id, $post_id, $is_comment );
        // Update User & Post
        if ( $post_users ) {
          update_post_meta( $post_id, "_user_bookmarked", $post_users );
        }
			}
			$response['status'] = "liked";
			$response['icon'] = get_bookmarked_icon();
		} else { // Unlike the post
			if ( is_user_logged_in() ) { // user is logged in
				$user_id = get_current_user_id();
				$post_users = post_user_likes( $user_id, $post_id, $is_comment );
				// Update Post
				if ( $post_users ) {	
					$uid_key = array_search( $user_id, $post_users );
					unset( $post_users[$uid_key] );
					update_post_meta( $post_id, "_user_bookmarked", $post_users );
				}
			}
			$response['status'] = "unliked";
			$response['icon'] = get_bookmark_icon();
		}
    update_post_meta( $post_id, "_post_bookmark_modified", date( 'Y-m-d H:i:s' ) );

		if ( $disabled == true ) {
			wp_redirect( get_permalink( $post_id ) );
			exit();
		} else {
			wp_send_json( $response );
		}
	}
}

/**
 * Utility to test if the post is already liked
 * @since    0.5
 */
function already_bookmarked( $post_id) {
	$post_users = NULL;
	$user_id = NULL;
	if ( is_user_logged_in() ) { // user is logged in
		$user_id = get_current_user_id();
		$post_meta_users = get_post_meta( $post_id, "_user_bookmarked" );
		if ( count( $post_meta_users ) != 0 ) {
			$post_users = $post_meta_users[0];
		}
	}
	if ( is_array( $post_users ) && in_array( $user_id, $post_users ) ) {
		return true;
	} else {
		return false;
	}
} // already_bookmarked()

/**
 * Output the like button
 * @since    0.5
 */
function kanews_bookmark_button( $post_id ) {
	$output = '';
	$nonce = wp_create_nonce( 'kanews-bookmark-nonce' ); // Security

  $post_id_class = esc_attr( 'kanews-add-bookmark kanews-add-bookmark-' . $post_id );

	$icon_empty = get_bookmark_icon();
	$icon_full = get_bookmarked_icon();
	// Loader
	$loader = '<span id="kanews-bookmark-loader"></span>';
	
	// Liked/Unliked Variables
	if ( already_bookmarked( $post_id ) ) {
		$class = esc_attr( ' added' );
		$title = kanews_translate('unbookmark-text', esc_html__( 'Favorilerimden Çıkar', 'kanews' ));
		$icon = $icon_full;
	} else {
		$class = '';
		$title = kanews_translate('bookmark-text', esc_html__( 'Favorilerime Ekle', 'kanews' ));
		$icon = $icon_empty;
	}

	if(is_user_logged_in())
		$output = '<button class="' . $post_id_class . $class . '" data-nonce="' . $nonce . '" data-post-id="' . $post_id . '" title="' . $title . '">' . $icon . '</button>';
	else
		$output = '<button class="kanews-add-bookmark" data-toggle="kanews-modal-login" title="' . $title . '">'. $icon_empty .'</button>';

	return $output;
} // kanews_bookmark_button()

/**
 * Utility retrieves post meta user likes (user id array), 
 * then adds new user id to retrieved array
 * @since    0.5
 */
function post_user_bookmarks( $user_id, $post_id ) {
	$post_users = '';
	$post_meta_users = get_post_meta( $post_id, "_user_bookmarked" );
	if ( count( $post_meta_users ) != 0 ) {
		$post_users = $post_meta_users[0];
	}
	if ( !is_array( $post_users ) ) {
		$post_users = array();
	}
	if ( !in_array( $user_id, $post_users ) ) {
		$post_users['user-' . $user_id] = $user_id;
	}
	return $post_users;
} // post_user_bookmarks()

/**
 * Utility retrieves post meta ip likes (ip array), 
 * then adds new ip to retrieved array
 * @since    0.5
 */
function post_id_bookmarks( $user_ip, $post_id) {
	$post_users = '';
	$post_meta_users = get_post_meta( $post_id, "_user_IP" );
	// Retrieve post information
	if ( count( $post_meta_users ) != 0 ) {
		$post_users = $post_meta_users[0];
	}
	if ( !is_array( $post_users ) ) {
		$post_users = array();
	}
	if ( !in_array( $user_ip, $post_users ) ) {
		$post_users['ip-' . $user_ip] = $user_ip;
	}
	return $post_users;
} // post_id_bookmarks()


/**
 * Utility returns the button icon for "like" action
 * @since    0.5
 */
function get_bookmarked_icon() {
	/* If already using Font Awesome with your theme, replace svg with: <i class="fa fa-heart"></i> */
	$icon = '';
	return $icon;
} // get_bookmarked_icon()

/**
 * Utility returns the button icon for "unlike" action
 * @since    0.5
 */
function get_bookmark_icon() {
	/* If already using Font Awesome with your theme, replace svg with: <i class="fa fa-heart-o"></i> */
  $icon = '';
  return $icon;
} // get_bookmark_icon()


// User Profile List
add_action( 'show_user_profile', 'show_user_bookmarks' );
add_action( 'edit_user_profile', 'show_user_bookmarks' );
function show_user_bookmarks( $user ) { 
	if(!is_admin()) return; ?>        
	<table class="form-table">
		<tr>
			<th><label for="user_likes"><?php _e( 'Kaydettikleri', 'kanews' ); ?></label></th>
			<td>
			<?php
			$types = get_post_types( array( 'public' => true ) );
			$args = array(
			  'numberposts' => -1,
			  'post_type' => $types,
			  'meta_query' => array (
				array (
				  'key' => '_user_bookmarked',
				  'value' => $user->ID,
				  'compare' => 'LIKE'
				)
			  ) );		
			$sep = '';
			$like_query = new WP_Query( $args );
			if ( $like_query->have_posts() ) : ?>
			<p>
			<?php while ( $like_query->have_posts() ) : $like_query->the_post(); 
			echo $sep; ?><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
			<?php
			$sep = ' &middot; ';
			endwhile; 
			?>
			</p>
			<?php else : ?>
			<p><?php _e( 'Henüz herhangi bir şey kaydetmemişsin.', 'kanews' ); ?></p>
			<?php 
			endif; 
			wp_reset_postdata(); 
			?>
			</td>
		</tr>
	</table>
<?php } // show_user_likes()
function get_user_bookmark_count( $user ) { 
	$args = array(
		'numberposts' => -1,
		'post_type' => 'post',
		'meta_query' => array (
		array (
			'key' => '_user_bookmarked',
			'value' => $user,
			'compare' => 'LIKE'
		)
		) );		
	$sep = '';
	$like_query = new WP_Query( $args );
	$counter = 0;
	if ( $like_query->have_posts() )  {
		while ( $like_query->have_posts() ) : $like_query->the_post(); global $post;
		if(is_array(get_post_meta($post->ID, '_user_bookmarked', true)) && in_array($user, get_post_meta($post->ID, '_user_bookmarked', true))):
			$counter++;
		endif;
		endwhile;
	}
	wp_reset_postdata(); 
	// return $counter;
	return '-';
}