<?php

/**
 * @package BwlFaqManager
 */

namespace BwlFaqManager\Controllers\Votes;

use BwlFaqManager\Controllers\Analytics\BafAnalyticsHelper;
use BwlFaqManager\Controllers\Votes\FaqVoteStatus;

class FaqVotes {

	public function register() {
		add_action( 'wp_ajax_bwl_advanced_faq_apply_rating', [ $this, 'bafCountVotes' ] );
		add_action( 'wp_ajax_nopriv_bwl_advanced_faq_apply_rating', [ $this, 'bafCountVotes' ] );
	}

	function bafCountVotes() {

		$nonce_status = check_ajax_referer( 'baf-vote-nonce', '_baf_vote_nonce' );

		if ( ! empty( $nonce_status ) && $nonce_status === 1 ) {

			$faqVoteStatus = new FaqVoteStatus();

			$baf_thanks_msg        = esc_html__( ' Thank For Your Rating!', 'bwl-adv-faq' );
			$baf_already_voted_msg = esc_html__( ' You have already give rating!', 'bwl-adv-faq' );

			// Retrieve user IP address

			$ip = $_SERVER['REMOTE_ADDR'];

			$post_id = absint( $_POST['post_id'] );

			$meta_IP = get_post_meta( $post_id, 'baf_voted_IP' );  // Get voters'IPs for the current post

			if ( ! empty( $meta_IP ) ) {

				$baf_voted_IP = $meta_IP[0];
			} else {

				$baf_voted_IP = [];
			}

			$baf_rate_counter = absint( get_post_meta( $post_id, 'baf_votes_count', true ) );

			if ( ! $faqVoteStatus->getFaqVoteStatus( $post_id ) ) {

				$timestamp = time();

				$baf_voted_IP[ $ip ] = $timestamp;

				// Update Data of "baf_likes_data"

				$table_data = [
					'post_id'        => $post_id,
					'ip'             => $ip,
					'like_date_time' => date( 'Y-m-d H:i:s', $timestamp ),
				];

				BafAnalyticsHelper::insertLikeData( $table_data );

				// Save IP and increase votes count

				update_post_meta( $post_id, 'baf_voted_IP', $baf_voted_IP );
				update_post_meta( $post_id, 'baf_votes_count', ++$baf_rate_counter );

				$data = [
					'status'       => 1,
					'rate_counter' => $baf_rate_counter,
					'msg'          => $baf_thanks_msg,
				];
			} else {

				$data = [
					'status'       => 0,
					'rate_counter' => $baf_rate_counter,
					'msg'          => $baf_already_voted_msg,
				];
			}

			echo wp_json_encode( $data );
		}

		die();
	}
}
