<?php
/**
 * Create Cookie Notice.
 *
 * @class Class_DateBook_Cookies
 * @author Pagick Themes
 * @since 3.3
 */
	 


/**
 * Cookie Notice class.
 */
class Class_DateBook_Cookies {

	/**
	 * @var $defaults
	 */
	private $defaults = array(
		'general' => array(
			'position'						=> 'bottom',
			'message_text'					=> '',
			'button_size'					=> 'btn-sm',
			'button_position'				=> 'bottom',
			'accept_text'					=> '',
			'refuse_text'					=> '',
			'refuse_opt'					=> 'no',
			'refuse_code'					=> '',
			'refuse_code_head'				=> '',
			'redirection'					=> false,
			'see_more'						=> 'no',
			'link_target'					=> '_blank',
			'time'							=> 'month',
			'hide_effect'					=> 'fade',
			'on_scroll'						=> false,
			'on_scroll_offset'				=> 100,
			'colors' => array(
				'text'						=> '#fff',
				'bar'						=> '#000'
			),
			'button_colors' => array(
				'text'						=> '#000',
				'bar'						=> '#fff'
			),
			'see_more_opt' => array(
				'text'						=> '',
				'link_type'					=> 'page',
				'id'						=> 'empty',
				'link'						=> '',
				'sync'						=> false
			),
			'script_placement'				=> 'header',
			'translate'						=> true
		)
	);

	private $positions 			= array();
	private $styles 			= array();
	private $choices 			= array();
	private $links 				= array();
	private $link_target 		= array();
	private $colors 			= array();
	private $button_colors		= array();
	private $options 			= array();
	private $effects 			= array();
	private $times 				= array();


    /*
     * Constructor function
     *
     */
    public function __construct() {

		if (of_get_option('enable_cookies') == 1) {

			// settings
			$this->options = array(
				'general' => array_merge( $this->defaults['general'], get_option( 'datebook_cookies_options', $this->defaults['general'] ) )
			);

			if ( ! isset( $this->options['general']['see_more_opt']['sync'] ) ){
				$this->options['general']['see_more_opt']['sync'] = $this->defaults['general']['see_more_opt']['sync'];
			}

			// actions
			add_action( 'after_setup_theme', array( $this, 'load_defaults' ) );
			add_action( 'wp_enqueue_scripts', array( $this, 'wp_enqueue_scripts' ) );
			add_action( 'wp_head', array( $this, 'wp_print_header_scripts' ) );
			add_action( 'wp_print_footer_scripts', array( $this, 'wp_print_footer_scripts' ) );
			add_action( 'wp_footer', array( $this, 'add_cookie_notice' ), 1000 );

			// filters
			add_filter( 'body_class', array( $this, 'change_body_class' ) );

		}

		add_action( 'init', array( $this, 'process_cookies_referral') );

	}


	/**
	 * Load plugin defaults
	 */
	public function load_defaults() {
		$this->positions = array(
			'top'	 			=> esc_html__( 'Top', 'datebook' ),
			'bottom' 			=> esc_html__( 'Bottom', 'datebook' )
		);

		$this->styles = array(
			'btn-sm' => esc_html__( 'Small', 'datebook' ),
			'btn-md' => esc_html__( 'Medium', 'datebook' ),
			'btn-lg' => esc_html__( 'Large', 'datebook' )
		);
		
		$this->revoke_opts = array(
			'automatic'	 		=> esc_html__( 'Automatic', 'datebook' ),
			'manual' 			=> esc_html__( 'Manual', 'datebook' )
		);

		$this->links = array(
			'page'	 			=> esc_html__( 'Page link', 'datebook' ),
			'custom' 			=> esc_html__( 'Custom link', 'datebook' )
		);

		$this->link_target = array(
			'_blank',
			'_self'
		);

		$this->colors = array(
			'text'	 			=> esc_html__( 'Text color', 'datebook' ),
			'bar'	 			=> esc_html__( 'Bar color', 'datebook' ),
		);

		$this->button_colors = array(
			'text'	 			=> esc_html__( 'Text color', 'datebook' ),
			'bar'	 			=> esc_html__( 'Bar color', 'datebook' ),
		);

		$this->times = array(
			'hour'				=> array( esc_html__( 'An hour', 'datebook' ), 3600 ),
			'day'		 		=> array( esc_html__( '1 day', 'datebook' ), 86400 ),
			'week'		 		=> array( esc_html__( '1 week', 'datebook' ), 604800 ),
			'month'		 		=> array( esc_html__( '1 month', 'datebook' ), 2592000 ),
			'3months'	 		=> array( esc_html__( '3 months', 'datebook' ), 7862400 ),
			'6months'	 		=> array( esc_html__( '6 months', 'datebook' ), 15811200 ),
			'year'		 		=> array( esc_html__( '1 year', 'datebook' ), 31536000 ),
			'infinity'	 		=> array( esc_html__( 'infinity', 'datebook' ), 2147483647 )
		);

		$this->effects = array(
			'none'	 			=> esc_html__( 'None', 'datebook' ),
			'fade'	 			=> esc_html__( 'Fade', 'datebook' ),
			'slide'	 			=> esc_html__( 'Slide', 'datebook' )
		);

		$this->script_placements = array(
			'header' 			=> esc_html__( 'Header', 'datebook' ),
			'footer' 			=> esc_html__( 'Footer', 'datebook' ),
		);

	}


		/**
		 * Check if cookies are accepted
		 */
		function datebook_cookies_cookies_accepted() {
			return (bool) Class_DateBook_Cookies::cookies_accepted();
		}

		/**
		 * Check if cookies are set
		 */
		function datebook_cookies_cookies_set() {
			return (bool) Class_DateBook_Cookies::cookies_set();
		}


	/**
	 * Add new body classes.
	 */
	public function change_body_class( $classes ) {

		if ( is_admin() ){
			return $classes;
		}

		if ( $this->cookies_set() ) {
			$classes[] = 'cookies-set';

			if ( $this->cookies_accepted() ){
				$classes[] = 'cookies-accepted';
			} else {
				$classes[] = 'cookies-refused';
			}
		} else {
			$classes[] = 'cookies-not-set';
		}

		return $classes;

	}


	/**
	 * Cookie notice output.
	 */
	public function add_cookie_notice() {

		if ( ! $this->cookies_set() || $this->options['general']['refuse_opt'] === 'yes' && isset($this->options['general']['message_text']) && strlen($this->options['general']['message_text']) > 10 ) {

			// get cookie container args
			$options = apply_filters( 'datebook_cookies_args', array(
				'position'			=> $this->options['general']['position'],
				'button_size'		=> $this->options['general']['button_size'],
				'button_position'	=> $this->options['general']['button_position'],
				'colors'			=> $this->options['general']['colors'],
				'button_colors'		=> $this->options['general']['button_colors'],
				'message_text'		=> $this->options['general']['message_text'],
				'accept_text'		=> $this->options['general']['accept_text'],
				'refuse_text'		=> $this->options['general']['refuse_text'],
				'refuse_opt'		=> $this->options['general']['refuse_opt'],
				'see_more'			=> $this->options['general']['see_more'],
				'see_more_opt'		=> $this->options['general']['see_more_opt'],
				'link_target'		=> $this->options['general']['link_target'],
			) );

			$button_position = $options['button_position'] !== '' ? $options['button_position'] : 'bottom';
			
			
			$message_output = '<span id="datebook-cookies-notice-text">'. $options['message_text'] .'</span>';
			
			$button_output = '<a href="#" id="datebook-cookies-accept-cookie" data-cookie-set="accept" class="datebook-cookies-set-cookie btn ' . ( $options['button_size'] !== '' ? ' ' . $options['button_size'] : 'btn-sm' ) . ' datebook-button" style="color: ' . $options['button_colors']['text'] . '; background-color: ' . $options['button_colors']['bar'] . ';">' . $options['accept_text'] . '</a>';
			$button_output .= ( $options['refuse_opt'] === 'yes' ? '<a href="#" id="datebook-cookies-refuse-cookie" data-cookie-set="refuse" class="datebook-cookies-set-cookie btn ' . ( $options['button_size'] !== '' ? ' ' . $options['button_size'] : 'btn-sm' ) . ' datebook-button" style="color: ' . $options['button_colors']['text'] . '; background-color: ' . $options['button_colors']['bar'] . ';">' . $options['refuse_text'] . '</a>' : '' );
			$button_output .= ( $options['see_more'] === 'yes' ? '<a href="' . ( $options['see_more_opt']['link_type'] === 'custom' ? $options['see_more_opt']['link'] : get_permalink( $options['see_more_opt']['id'] ) ) . '" target="' . $options['link_target'] . '" id="datebook-cookies-more-info" class="datebook-cookies-more-info btn ' . ( $options['button_size'] !== '' ? ' ' . $options['button_size'] : 'btn-sm' ) . ' datebook-button" style="color: ' . $options['button_colors']['text'] . '; background-color: ' . $options['button_colors']['bar'] . ';">' . $options['see_more_opt']['text'] . '</a>' : '' );

			// message output
			$output = '<div id="datebook-cookies" role="banner" class="datebook-cookies datebook-cookies-' . ( $options['position'] ) . '" style="color: ' . $options['colors']['text'] . '; background-color: ' . $options['colors']['bar'] . ';"><div class="datebook-cookies-container">';
			

			if($button_position == 'bottom'){
				$output .= $message_output . '<div class="datebook-clear10"></div>' . $button_output;
			} else if($button_position == 'above'){
				$output .= $button_output . '<div class="datebook-clear10"></div>' .$message_output;
			} else if($button_position == 'right'){
				$output .= $message_output . ' ' . $button_output;
			} else if($button_position == 'left'){
				$output .= $button_output . ' ' . $message_output;
			} else {
				$output .= $message_output . '<div class="datebook-clear10"></div>' . $button_output;
			}


			$output .= '</div></div>';

			echo apply_filters( 'datebook_cookies_output', $output, $options );
		}
	}

	/**
	 * Check if cookies are accepted.
	 * 
	 * @return bool
	 */
	public function cookies_accepted() {
		return apply_filters( 'datebook_cookies_is_cookie_accepted', isset( $_COOKIE['datebook_cookies_accepted'] ) && $_COOKIE['datebook_cookies_accepted'] === 'true' );
	}

	/**
	 * Check if cookies are set.
	 *
	 * @return boolean Whether cookies are set
	 */
	public function cookies_set() {
		return apply_filters( 'datebook_cookies_is_cookie_set', isset( $_COOKIE['datebook_cookies_accepted'] ) );
	}


	/**
	 * Get allowed script blocking HTML.
	 *
	 * @return array
	 */
	public function get_allowed_html() {
		return apply_filters(
			'datebook_refuse_code_allowed_html',
			array_merge(
				wp_kses_allowed_html( 'post' ),
				array(
					'script' => array(
						'type' => array(),
						'src' => array(),
						'charset' => array(),
						'async' => array()
					),
					'noscript' => array(),
					'style' => array(
						'type' => array()
					),
					'iframe' => array(
						'src' => array(),
						'height' => array(),
						'width' => array(),
						'frameborder' => array(),
						'allowfullscreen' => array()
					)
				)
			)
		);
	}

	
	/**
	 * Load scripts and styles - frontend.
	 */
	public function wp_enqueue_scripts() {

		wp_enqueue_script('datebook-cookies-front', DATEBOOK_URL . 'assets/js/datebook-cookies.js', array( 'jquery' ), '', true );

		wp_localize_script(
			'datebook-cookies-front',
			'DateBookCookiesArgs',
			array(
				'ajaxurl'				=> admin_url( 'admin-ajax.php' ),
				'hideEffect'			=> $this->options['general']['hide_effect'],
				'onScroll'				=> $this->options['general']['on_scroll'],
				'onScrollOffset'		=> $this->options['general']['on_scroll_offset'],
				'cookieName'			=> 'datebook_cookies_accepted',
				'cookieValue'			=> 'true',
				'cookieTime'			=> $this->times[$this->options['general']['time']][1],
				'cookiePath'			=> ( defined( 'COOKIEPATH' ) ? COOKIEPATH : '' ),
				'cookieDomain'			=> ( defined( 'COOKIE_DOMAIN' ) ? COOKIE_DOMAIN : '' ),
				'redirection'			=> $this->options['general']['redirection'],
				'refuse'				=> $this->options['general']['refuse_opt'],
				'secure'				=> (int)is_ssl()
			)
		);

		wp_enqueue_style( 'datebook-cookies-front', DATEBOOK_URL . 'assets/css/datebook-cookies.css' );
		
	}


	/**
	 * Print non functional JavaScript in header.
	 *
	 * @return mixed
	 */
	public function wp_print_header_scripts() {
		if ( $this->cookies_accepted() ) {
			$scripts = apply_filters( 'datebook_cookies_refuse_code_scripts_html', html_entity_decode( trim( wp_kses( $this->options['general']['refuse_code_head'], $this->get_allowed_html() ) ) ) );

			if ( ! empty( $scripts ) )
				echo $scripts;
		}
	}


	/**
	 * Print non functional JavaScript in body.
	 *
	 * @return mixed
	 */
	public function wp_print_footer_scripts() {
		if ( $this->cookies_accepted() ) {
			$scripts = apply_filters( 'datebook_cookies_refuse_code_scripts_html', html_entity_decode( trim( wp_kses( $this->options['general']['refuse_code'], $this->get_allowed_html() ) ) ) );

			if ( ! empty( $scripts ) )
				echo $scripts;
		}
	}


	/**
	 * Retrieve data from online provider
	 *
	 * @access private
	 * @return void
	 */
	private static function send_get_request_to_referrer($url_referrer) {

		$response = '';

		if(in_array ('curl', get_loaded_extensions()) || function_exists('curl_init') !== false) {

			$ch = curl_init();
			curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_URL, $url_referrer);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
			$response = curl_exec($ch);
			curl_close($ch);

		} else if(ini_get('allow_url_fopen')){

			$response = file_get_contents($url_referrer);

		}

		$data = json_decode($response,true);

		return $data;
			
	}

	/**
	 * Get saved referral cookie
	 */
	public static function get_cookie_referral($profile_id, $profile_get_permalink) {

		$catch_cookies = isset($_COOKIE['datebook_cookies_referrer']) ? $_COOKIE['datebook_cookies_referrer'] : '';

		$cookie_detected = ($catch_cookies !== '') ? 1 : 0;

		if($cookie_detected == 1){

			$cookies_array = explode('|', $catch_cookies);

			$catch_cookies = isset($cookies_array[0]) ? $cookies_array[0] : '';
			$date_referred = isset($cookies_array[1]) ? $cookies_array[1] : '';
			$url_referer = isset($cookies_array[2]) ? $cookies_array[2] : '';
			$get_variables = isset($cookies_array[3]) ? $cookies_array[3] : '';

			//Get all referral options
			$get_referreral_options = get_option('datebook_referral_options');

			if (isset($get_referreral_options[$catch_cookies]['active']) && $get_referreral_options[$catch_cookies]['active'] == 1 && isset($get_referreral_options[$catch_cookies]['referrercode']) && $get_referreral_options[$catch_cookies]['referrercode'] == $catch_cookies) {

				$all_referrer_fields = array('referrercode' => $get_referreral_options[$catch_cookies]['referrercode'], 'name' => $get_referreral_options[$catch_cookies]['name'], 'detect_url_referer' => $url_referer, 'slug' => $get_referreral_options[$catch_cookies]['slug'], 'sendtoreferrerurl' => $get_referreral_options[$catch_cookies]['sendtoreferrerurl'], 'profile_id' => $profile_id, 'date_referred' => $date_referred, 'date_registered' => date("Y-m-d H:i"));

				update_post_meta($profile_id, 'referrer', $all_referrer_fields);

				// Send email notification to referrer
				if(isset($get_referreral_options[$catch_cookies]['sendemail']) && $get_referreral_options[$catch_cookies]['sendemail'] == 1){
					
					$cookie_emailaddress = isset($get_referreral_options[$catch_cookies]['emailaddress']) ? $get_referreral_options[$catch_cookies]['emailaddress'] : '';
					
					if(is_email($cookie_emailaddress)){

						// Send a notification
						$permalink_url = '<a href="' . $profile_get_permalink . '">' . $profile_get_permalink . '</a>';

						// Subject
						$subject_in_email = isset($get_referreral_options[$catch_cookies]['emailsubject']) ? $get_referreral_options[$catch_cookies]['emailsubject'] : '';

						// Message
						$body = isset($get_referreral_options[$catch_cookies]['emailtext']) ? $get_referreral_options[$catch_cookies]['emailtext'] : '';

						$body = str_replace('[profile_permalink]', $permalink_url, $body);

						$body = nl2br($body);

						// Send email to admin
						$datebook_mail = DateBook_Utilities::datebook_email_send(NULL, NULL, $cookie_emailaddress, $subject_in_email, $body);

					}
				}

				// Send a pingback (notification) to referrer website
				$url_referrer = $get_referreral_options[$catch_cookies]['sendtoreferrerurl'];
				if(!empty($url_referrer)){

					// Add all parameters back
					parse_str($get_variables, $get_variables_array);
					
					$add_parameters_back = isset($get_referreral_options[$catch_cookies]['parameters_back']) && $get_referreral_options[$catch_cookies]['parameters_back'] == 1 ? $get_variables_array : array();

					// Add Profile ID
					$add_profile_id = isset($get_referreral_options[$catch_cookies]['profile_id']) && $get_referreral_options[$catch_cookies]['profile_id'] == 1 ? $profile_id : 0;

					// Add additional parameters
					$add_field_items = array();
					if(isset($get_referreral_options[$catch_cookies]['field_items']) && !empty($get_referreral_options[$catch_cookies]['field_items'])){
						$field_items_array = explode('<br />', strtr($get_referreral_options[$catch_cookies]['field_items'], array("\r\n" => '<br />', "\r" => '<br />', "\n" => '<br />')));
						if(isset($field_items_array) && is_array($field_items_array)){
							foreach($field_items_array as $key => $value){
								$field_item_arr = explode('=', $value);
								$add_field_items[$field_item_arr[0]] = $field_item_arr[1];
							}
						}
					}

					// Prepare all arrays
					$add_arrays = array_merge(array_merge($add_parameters_back, $add_field_items), array('profile_id' => $add_profile_id));

					$send_link_to_referrer = add_query_arg(
						$add_arrays,
					$url_referrer );

					$data = self::send_get_request_to_referrer($send_link_to_referrer);
				}
			}
		}
	}


	/**
	 * Sets the cookies for referral system
	 * Sets the cookie and period for 1 year expiry
	 */
	private static function set_cookie_referral($create_cookie, $cookie_period) {

		setcookie( 'datebook_cookies_referrer', $create_cookie, $cookie_period, '/' );

	}

	/**
	 * Create a cookie for referral system
	 */
	public static function process_cookies_referral() {

		$catch_cookies = isset($_GET['ref']) ? $_GET['ref'] : '';

		if($catch_cookies != ''){

			//Get entire array
			$get_referreral_options = get_option('datebook_referral_options');

			if (isset($get_referreral_options[$catch_cookies]['active']) && $get_referreral_options[$catch_cookies]['active'] == 1 && isset($get_referreral_options[$catch_cookies]['referrercode']) && $get_referreral_options[$catch_cookies]['referrercode'] == $catch_cookies) {

				if(isset($_SERVER['QUERY_STRING'])){
					$add_get_variables = $_SERVER['QUERY_STRING'];
				} else {
					$add_get_variables = '';
				}

				$url_referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

				$create_cookie = $catch_cookies . '|' . date("Y-m-d H:i") . '|' . $url_referer . '|' . $add_get_variables;

				$cookie_period = isset($get_referreral_options[$catch_cookies]['period']) && $get_referreral_options[$catch_cookies]['period'] > 0 ? strtotime("+" . $get_referreral_options[$catch_cookies]['period'] . " days") : strtotime("+1 year");

				//Set cookie
				self::set_cookie_referral($create_cookie, $cookie_period);

			}
		}
	}

}


$Class_DateBook_Cookies = new Class_DateBook_Cookies;