<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class DateBook_Profile_Views
 *
 * @class DateBook_Profile_Views
 * @package DateBook/Classes
 * @author Pagick Themes
 */
class DateBook_Profile_Views {


	/**
	 * Hook actions and filters.
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function init() {

		add_filter('manage_posts_columns', array( __CLASS__, 'datebook_posts_column_views' ) );
		add_action('manage_posts_custom_column', array( __CLASS__, 'datebook_posts_custom_column_views' ) );

		add_action( 'datebook_profile_views', array( __CLASS__, 'datebook_process_edit_views' ) );

	}


	/**
	 * Add "Views" column to posts in Admin panel
	 * 
	 * @access public
	 */
	public static function datebook_posts_column_views($defaults) {

		$defaults['post_views'] = esc_html__( 'Views', 'datebook' );

		return $defaults;

	}


	/**
	 * Count hours ago
	 * 
	 * @access private
	 */
	private static function count_hours($hours, $quantity) {

		$sums = $count = 0;
		
		if(isset($hours) && is_array($hours) && !empty($hours)){

			foreach ($hours as $date => $views) {

				$count++;

				$day_off = date('Y-m-d H', strtotime("-".$count." hour"));

				if(isset($hours[$day_off])){
					$sums += $hours[$day_off];
				}

				if ($quantity == $count) { 
    		        break;  // this will break both foreach loops
        		}
			}
		}
	
		return $sums;

	}


	/**
	 * Count days ago
	 * 
	 * @access private
	 */
	private static function count_days($days, $quantity) {

		$sums = $count = 0;

		if(isset($days) && is_array($days) && !empty($days)){

			foreach ($days as $date => $views) {

				$count++;

				$day_off = date('Y-m-d', strtotime("-".$count." day"));

				if(isset($days[$day_off])){
					$sums += $days[$day_off];
				}

				if ($quantity == $count) { 
    		        break;  // this will break both foreach loops
        		}
			}
		}
	
		return $sums;

	}


	/**
	 * Count days of last week
	 * 
	 * @access private
	 */
	private static function last_week_days($days) {

		$sums = 0;

		if(isset($days) && is_array($days) && !empty($days)){

			for($i=0;$i<7;$i++) {

				$day_off = date('Y-m-d', strtotime('last sunday-'. $i . ' day'));

				if(isset($days[$day_off])){
					$sums += $days[$day_off];
				}
			}
		}

		return $sums;

	}


	/**
	 * Set and show profile views
	 *
	 * @access public
	 */
	public static function datebook_get_post_views($postID, $datebook_get_data, $simulation_views_quantity = 0, $currentauth_ID = 0, $current_user_id = 0) {

		if(isset($datebook_get_data) && is_array($datebook_get_data)){

			if ($currentauth_ID > 0 && $currentauth_ID != $current_user_id) {

				// Display number of profile views
				$postID = absint($postID);

				$count_one = $simulation_views_quantity > 0 ? $simulation_views_quantity : 1;

				// Get IP of all visitors
				$get_ip_address = $simulation_views_quantity == 0 ? Class_DateBook_IP::get_ip_address() : '127.0.0.1';

				$get_new_views_count = array(
					'ip' => array($get_ip_address => date('Y-m-d H')),
					'all' => array('foralltime' => $count_one),
					'hour' => array(date('Y-m-d H') => $count_one),
					'day' => array(date('Y-m-d') => $count_one),
					'month' => array(date('Y-m') => $count_one),
					'year' => array(date('Y') => $count_one)
				);

				$get_old_views_count = isset($datebook_get_data['post_views_count']) && is_array($datebook_get_data['post_views_count']) ? $datebook_get_data['post_views_count'] : array();

				if(isset($get_old_views_count) && !empty($get_old_views_count)){

					$sums = array();
					foreach (array_keys($get_old_views_count + $get_new_views_count) as $key) {
						$subsums = array();
						foreach ($get_old_views_count[$key] as $subkey => $subvalue) {
							if(isset($get_new_views_count[$key][$subkey]) && $key != 'ip'){
								$subsums[$subkey] = $subvalue + $count_one;
							} else {
								$subsums[$subkey] = $get_old_views_count[$key][$subkey];
								foreach ($get_new_views_count[$key] as $key_new => $value_new) {
									$subsums[$key_new] = $value_new;
								}
							}
						}
						$sums[$key] = $subsums;
					}

					$datebook_get_data['post_views_count'] = $sums;

				} else {

					$datebook_get_data['post_views_count'] = $get_new_views_count;

				}

				$already_visited_user = $simulation_views_quantity == 0 && isset($get_old_views_count['ip'][$get_ip_address]) && $get_old_views_count['ip'][$get_ip_address] == date('Y-m-d H') ? 1 : 0;

				if($already_visited_user == 0){

					// Update the post meta
					update_post_meta($postID, 'profile_personal_data', $datebook_get_data);

				}
			}


			if($simulation_views_quantity == 0){
				
				$statistics_kind_on_profile = of_get_option('statistics_kind_on_profile');
				
				if($statistics_kind_on_profile > 0){

					switch ($statistics_kind_on_profile) {
						case '1' : 
							$count_out = isset($datebook_get_data['post_views_count']['day'][date('Y-m-d', strtotime('-1 day'))]) ? $datebook_get_data['post_views_count']['day'][date('Y-m-d', strtotime('-1 day'))] : 0; // Yesterday
							$count_title = esc_html__('yesterday', 'datebook');
							break;
						case '2' : 
							$count_out = isset($datebook_get_data['post_views_count']['day'][date('Y-m-d')]) ? $datebook_get_data['post_views_count']['day'][date('Y-m-d')] : 0; // Today
							$count_title = esc_html__('today', 'datebook');
							break;
						case '3' : 
							$count_out = isset($datebook_get_data['post_views_count']['hour']) ? self::count_hours($datebook_get_data['post_views_count']['hour'], 24) : 0; // Last 24 hours
							$count_title = esc_html__('last 24 hours', 'datebook');
							break;
						case '4' : 
							$count_out = isset($datebook_get_data['post_views_count']['day']) ? self::last_week_days($datebook_get_data['post_views_count']['day']) : 0; // Last week
							$count_title = esc_html__('last week', 'datebook');
							break;
						case '5' : 
							$count_out = isset($datebook_get_data['post_views_count']['day']) ? self::count_days($datebook_get_data['post_views_count']['day'], 7) : 0; // Last 7 days
							$count_title = esc_html__('last 7 days', 'datebook');
							break;
						case '6' : 
							$count_out = isset($datebook_get_data['post_views_count']['day']) ? self::count_days($datebook_get_data['post_views_count']['day'], 10) : 0; // Last 10 days
							$count_title = esc_html__('last 10 days', 'datebook');
							break;
						case '7' : 
							$count_out = isset($datebook_get_data['post_views_count']['day']) ? self::count_days($datebook_get_data['post_views_count']['day'], 14) : 0; // Last 14 days
							$count_title = esc_html__('last 14 days', 'datebook');
							break;
						case '8' : 
							$count_out = isset($datebook_get_data['post_views_count']['day']) ? self::count_days($datebook_get_data['post_views_count']['day'], 10) : 0; // Last 20 days
							$count_title = esc_html__('last 20 days', 'datebook');
							break;
						case '9' : 
							$count_out = isset($datebook_get_data['post_views_count']['day']) ? self::count_days($datebook_get_data['post_views_count']['day'], 30) : 0; // Last 30 days
							$count_title = esc_html__('last 30 days', 'datebook');
							break;
						case '10' : 
							$count_out = isset($datebook_get_data['post_views_count']['month'][date('Y-m', strtotime('-1 month'))]) ? $datebook_get_data['post_views_count']['month'][date('Y-m', strtotime('-1 month'))] : 0; // Last month
							$count_title = esc_html__('last month', 'datebook');
							break;
						case '11' : 
							$count_out = isset($datebook_get_data['post_views_count']['year'][date('Y', strtotime('-1 year'))]) ? $datebook_get_data['post_views_count']['year'][date('Y', strtotime('-1 year'))] : 0; // Last year
							$count_title = esc_html__( 'last year', 'datebook');
							break;
						case '12' : 
							$count_out = isset($datebook_get_data['post_views_count']['year'][date('Y')]) ? $datebook_get_data['post_views_count']['year'][date('Y')] : 0; // This year
							$count_title = esc_html__('this year', 'datebook');
							break;

						default: $count_out = isset($datebook_get_data['post_views_count']['day'][date('Y-m-d')]) ? $datebook_get_data['post_views_count']['day'][date('Y-m-d')] : 0; // Today
						$count_title = esc_html__('today', 'datebook');
						break; 

					}

					$count_out = esc_html__( 'Views', 'datebook' ) . ': ' . absint($count_out) . ' <span class="badge badge-pill badge-info" data-toggle="tooltip" data-placement="top" data-original-title="' . esc_html__( 'The quantity of profile views', 'datebook' ) . ' ' . esc_html__( 'for', 'datebook' ) . ' ' . esc_attr($count_title) . '">?</span>';;
					return $count_out;

				}
			}

			return;

		}
	}


	/**
	 * Set views on Who Viewed Me page
	 *
	 * @access public
	 */
	public static function datebook_set_who_viewed_me($user_id, $current_user_id) {

		// Set profile visits by other users
		global $wpdb;

		$set_visits = 0;
		if (is_user_logged_in()) {

			$table_profile_views = strtolower($wpdb->prefix) . 'datebook_profile_views';

			$user_id = absint($user_id);
			$current_user_id = absint($current_user_id);

			$already_visited = $wpdb->get_var($wpdb->prepare("SELECT `profile_id` FROM " . $table_profile_views . " WHERE `profile_id` = '%d' AND `visitor_id` = '%d' AND `viewdate` > DATE_SUB(NOW(), INTERVAL 1 DAY) ", $user_id, $current_user_id));

			if ($already_visited == '') {

				$today = date("Y-m-d H:i:s");

				$set_visits = $wpdb->query($wpdb->prepare("INSERT INTO " . $table_profile_views . " (profile_id, visitor_id, status, viewdate) VALUES ( '%d', '%d', '0', '%s' )", $user_id, $current_user_id, $today));

			}

		}

		return $set_visits;

	}


	/**
	 * Show post views in Administrator dashboard
	 * 
	 * @access public
	 */
	public static function datebook_posts_custom_column_views($column_name) {

		if ($column_name === 'post_views') {
			
			$profile_id = get_the_ID();
			
			$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
			$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();
			
			$get_views_count = isset($datebook_get_data['post_views_count']['all']['foralltime']) ? $datebook_get_data['post_views_count']['all']['foralltime'] : 0;

			echo absint($get_views_count);

		}
	}


	/**
	 * Count views on Who Viewed Me page
	 *
	 * @access public
	 */
	public static function datebook_count_who_viewed_me($current_user_id) {

		global $wpdb;
		$current_user_id = absint($current_user_id);

		$table_profile_views = strtolower($wpdb->prefix) . 'datebook_profile_views';
		$check_profile_views = $wpdb->get_var($wpdb->prepare("show tables like %s", $table_profile_views));

		$showicon = (of_get_option('display_title_icon_usermenu') == 1 || of_get_option('display_title_icon_usermenu') == 3) ? 1 : 0; // 0, 1
		
		$count_visits = ($showicon == 1) ? '<i class="far fa-eye mr-1"></i>' : '';

		// Count profile visits by other users
		if ($check_profile_views == $table_profile_views) {

			$countvisits = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM " . $table_profile_views . " WHERE `profile_id` = %d AND status = 0", $current_user_id));

			if ($countvisits > 0) {
				$count_visits = '<sup><span class="badge badge-pill badge-warning">' . $countvisits . '</span></sup>' . $count_visits;
			}
		}

		return $count_visits;

	}


	/**
	 * Check for new views on Who Viewed Me page
	 *
	 * @access private
	 * @return void
	 */
	private static function datebook_check_who_viewed_me($current_user_id) {

		global $wpdb;
		// Check profile visits by other users
		$current_user_id = absint($current_user_id);

		$table_profile_views = strtolower($wpdb->prefix) . 'datebook_profile_views';

		$wpdb->query($wpdb->prepare("UPDATE " . $table_profile_views . " SET status = 1 WHERE `profile_id` = '%d'", $current_user_id));

	}


	/**
	 * Cron job: delete old visitors from Who Viewed Me page
	 *
	 * @access private
	 */
	private static function datebook_delete_old_visitors($current_user_id) {

		if (is_user_logged_in()) {

			// Count profile visits by other users
			global $wpdb;

			$table_profile_views = strtolower($wpdb->prefix) . 'datebook_profile_views';
			$check_profile_views = $wpdb->get_var($wpdb->prepare("show tables like %s", $table_profile_views));

			if ($check_profile_views == $table_profile_views) {

				$period_delete_old_visitors = of_get_option('period_delete_old_visitors') > 0 ? of_get_option('period_delete_old_visitors') : 365; // 365 days by default

				$wpdb->get_var($wpdb->prepare("DELETE FROM " . $table_profile_views . " WHERE `profile_id` = %d AND status = 0 AND DATE(viewdate) < DATE(CURRENT_DATE - INTERVAL %d DAY)", $current_user_id, $period_delete_old_visitors));

			}
		}
	}


	/**
	 * Show Who Viewed Me page
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_process_edit_views() {

		if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
			$current_user_id = DATEBOOK_CURRENT_USER_ID;
		} else {
			global $current_user;
			wp_get_current_user();
			$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
		}

		if (!is_super_admin()) {

			// Delete visitiors from the Who viewed me page
			self::datebook_delete_old_visitors($current_user_id);

			// Set the Who viewed me status to 1. Now in the header there will not be yellow number of visitors
			self::datebook_check_who_viewed_me($current_user_id);
			
		}

	    // display the Edit Profile form
		echo DateBook_Template_Loader::load( 'profile/profile-views' );

	}


}

DateBook_Profile_Views::init();