<?php

/**
 * @package BwlFaqManager
 */

namespace BwlFaqManager\Controllers\Votes;

use BwlFaqManager\Controllers\Analytics\BafAnalyticsHelper;

class FaqVoteStatus {

	public function __construct() {
	}

	function getFaqVoteStatus( $post_id ) {

		$bwl_advanced_faq_options = get_option( 'bwl_advanced_faq_options' );
		$timebeforerevote         = ( isset( $bwl_advanced_faq_options['baf_repeat_vote_interval'] ) &&
		is_numeric( $bwl_advanced_faq_options['baf_repeat_vote_interval'] ) &&
		$bwl_advanced_faq_options['baf_repeat_vote_interval'] > 0 ) ? $bwl_advanced_faq_options['baf_repeat_vote_interval'] : 120; // = 2 hours

		// Retrieve post votes IPs
		$meta_IP = get_post_meta( $post_id, 'baf_voted_IP' );

		$baf_vote_count = get_post_meta( $post_id, 'baf_votes_count', true );

		if ( $baf_vote_count == '' || $baf_vote_count == 0 ) {
			return false;
		}

		if ( ! empty( $meta_IP ) ) {

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

			$baf_voted_IP = [];
		}

		// Retrieve current user IP
		$ip = $_SERVER['REMOTE_ADDR'];

		// If user has already voted
		if ( in_array( $ip, array_keys( $baf_voted_IP ) ) ) {

			$time = $baf_voted_IP[ $ip ];

			$now = time();

			// Compare between current time and vote time

			if ( round( ( $now - $time ) / 60 ) > $timebeforerevote ) {

				return false;
			}

			return true;
		}

		return false;
	}
}
