<?php
if (!class_exists('uwac_useraccount')){
	class uwac_useraccount{
		private $account_data;
		private $settings;

		public function __construct($account_data){
			$this->account_data 	= $account_data;
			$this->settings 		= $this->set_settings();
		}

		public function is_visible(){
			$settings 	= $this->settings;
			
			/**
			 * Temporarily Disabled Status
			 */
			if ($settings['is_disabled']){
				return false;
			}

			/**
			 * Visibility based on specific criteria
			 */
			// $visibility_criteria 	= $settings['visibility']['criteria'];
			$visibility_criteria 	= 'include';
			$visibility_type 		= $settings['visibility']['type'];
			$visibility_content 	= $settings['visibility']['content'];
			$is_on_criteria			= false;

			if ($visibility_type == 'all'){
				$is_on_criteria = true;
			} else if ($visibility_type == 'products'){
				global $post;
				$product_id = $post->ID;
				
				if ($visibility_criteria == 'include'){
					$is_on_criteria = (is_singular('product') && in_array($product_id,$visibility_content)) ? true : false;
				} else {
					$is_on_criteria = (is_singular('product') && !in_array($product_id,$visibility_content)) ? true : false;
				}
			} else if ($visibility_type == 'product_cat'){
				global $post;

				if ($visibility_criteria == 'include'){
					$is_on_criteria = (is_singular('product') && Uwac_Common::in_product_category($visibility_content,$post)) ? true : false;
				} else {
					$is_on_criteria = (is_singular('product') && !Uwac_Common::in_product_category($visibility_content,$post)) ? true : false;
				}
			}

			return $is_on_criteria;
		}

		public function get_settings(){
			return $this->settings;
		}
		
		private function set_settings(){
			$account = $this->account_data;
		
			global $wp;
			$_pageTitle 	= wp_title('',false);
			$_pageUrl		= home_url( $wp->request );
			$_postTitle		= get_the_title();
			
			// Sections
			$general 	= cs_uwac_get_settings('general_settings');
			$sections 	= $account['useraccount_sections'];
			$messages 	= $sections['ua_messages'];
			$schedule 	= $sections['ua_schedule'];
			$visibility = $sections['ua_visibility'];
			$themes 	= $sections['ua_theme'];

			// Status
			$is_disabled 			= (isset($account['user_account_status'])) ? true : false;
			$hide_on_widgets 		= (isset($visibility['user_account_visibility'])) ? true : false;

			// Visibility
			$visibility_content_type = (isset($sections['ua_visibility']['user_account_visibility_content_type'])) ? $sections['ua_visibility']['user_account_visibility_content_type'] : 'all';
			$visibility_content = false;
			if ($visibility_content_type == 'products'){
				$visibility_content = (isset($sections['ua_visibility']['user_account_products'])) ? $sections['ua_visibility']['user_account_products'] : false;
			} else if ($visibility_content_type == 'product_cat'){
				$visibility_content = (isset($sections['ua_visibility']['user_account_product_cat'])) ? $sections['ua_visibility']['user_account_product_cat'] : false;
			}

			// Account General Data
			$account_id 			= $account['user_account_id'];
			$account_name			= $account['user_account_name'];
			$account_name 			= ucwords($account_name);
			$account_number 		= $account['user_account_number'];
			$account_label			= $account['user_account_label'];
			$account_placeholder 	= implode('',preg_split("/[\sa-z]+/", $account_name));

			// Default Messages
			$default_welcome_text 		= (isset($general['general_messages']['default_welcome_text'])) ? $general['general_messages']['default_welcome_text'] : false;
			$default_button_text 		= (isset($general['general_messages']['default_button_text'])) ? $general['general_messages']['default_button_text'] : false;
			$default_online_text 		= (isset($general['general_messages']['default_online_text'])) ? $general['general_messages']['default_online_text'] : false;
			$default_unavailable_text 	= (isset($general['general_messages']['default_unavailable_text'])) ? $general['general_messages']['default_unavailable_text'] : false;
			$default_offline_text 		= (isset($general['general_messages']['default_offline_text'])) ? $general['general_messages']['default_offline_text'] : false;

			// Account Messages
			$account_welcome_text 	= (!empty($messages['user_account_welcome_text'])) ? $messages['user_account_welcome_text'] : $default_welcome_text;
			$button_text 			= (!empty($messages['user_account_button_text'])) ? $messages['user_account_button_text'] : $default_button_text;
			$online_text 			= (!empty($messages['user_account_online_text'])) ? $messages['user_account_online_text'] : $default_online_text;
			$offline_text 			= (!empty($messages['user_account_offline_text'])) ? $messages['user_account_offline_text'] : $default_offline_text;
			$unavailable_text 		= (!empty($messages['user_account_unavailable_text'])) ? $messages['user_account_unavailable_text'] : $default_unavailable_text;

			// Schedule Settings
			$always_online 			= (isset($schedule['user_account_always_available'])) ? true : false;
			$account_schedule 		= (isset($schedule['user_account_custom_schedule_fs'])) ? $schedule['user_account_custom_schedule_fs'] : false;
			$custom_schedule 		= (isset($account_schedule['user_account_custom_schedule'])) ? $account_schedule['user_account_custom_schedule'] : false;

			$is_now_active 			= ($always_online) ? 'online' : $this->is_account_online($custom_schedule);
			

			// Status Text
			if ($always_online){
				$status_text = $online_text;
			} else {
				if ($is_now_active === 'online'){
					$status_text = $online_text;
				} else if ($is_now_active === 'unavailable'){
					$status_text = $unavailable_text;
				} else if ($is_now_active === 'offline'){
					$status_text = $offline_text;
				}
			}

			// Status Text >> Replace Variable Tags
			$ttb = $this->get_today_time_block($custom_schedule);
			$status_text = str_replace('%status%', $is_now_active, $status_text);
			$status_text = str_replace('%online_from%', $ttb[0], $status_text);
			$status_text = str_replace('%online_to%', $ttb[1], $status_text);

			$status_display = ($status_text) ? false : 'display: none;';

			// Chat URL
			// Initial Chat Message Text - Replace Variable Tags
			$account_welcome_text 	= str_replace('%agent_name%', $account_name, $account_welcome_text);
			$account_welcome_text 	= str_replace('%page_title%', $_pageTitle, $account_welcome_text);
			$account_welcome_text 	= str_replace('%page_url%', $_pageUrl, $account_welcome_text);
			$account_welcome_text 	= str_replace('%product_name%', $_postTitle, $account_welcome_text);

			// Chat URL
			$maybe_phone_number = $this->clean($account_number);
			if (is_numeric($maybe_phone_number)){
				$account_number = $maybe_phone_number;
				$is_phone_number = true;
			} else if (filter_var($account_number, FILTER_VALIDATE_URL)){
				// Not a phone number... maybe group url
				$account_number = substr(strrchr($account_number,'/'),1);
				$is_phone_number = false;
			} else {
				$account_number = false;
				$is_phone_number = false;
			}
			$chat_base_url_group 	= "https://chat.whatsapp.com/";
			$chat_base_url_single	= "https://wa.me/";
			$chat_group_url 		= "{$chat_base_url_group}{$account_number}";
			$chat_single_url 		= "{$chat_base_url_single}{$account_number}?text={$account_welcome_text}";

			if ($is_phone_number){
				$chat_url = ($is_now_active == 'online') ? $chat_single_url : '#';
			} else {
				if ($account_number){
					$chat_url = ($is_now_active == 'online') ? $chat_group_url : '#';
				} else {
					$chat_url = "#";
				}
			}

			// User Account Avatar
			if (!empty($account['user_account_avatar'])) {
				$_id 	= $account['user_account_avatar'];
				$_url 	= wp_get_attachment_image_src($_id)[0];
				$_st 	= ucwords($is_now_active);
				$avatar_type 	= 'img-avatar';
				$account_avatar = "<img src='{$_url}' title='{$account_name} {$_st}' onerror='this.style.display=\"none\"'/>";
			} else {
				$avatar_type 	= 'no-avatar';
				$account_avatar = $this->get_wazap_icon();
			}

			// WhatsApp SVG Icon
			$wazap_icon = $this->get_wazap_icon();

			// Active Theme
			$theme_name 	= (isset($themes['button_theme'])) ? $themes['button_theme'] : false;
			$theme_settings = (isset($themes['button_theme_settings']["uwac_theme-{$theme_name}"])) ? $themes['button_theme_settings']["uwac_theme-{$theme_name}"] : false;



			// Output Account Settings
			$output = array(
				'is_disabled'		=> $is_disabled,
				'hide_on_widgets'	=> $hide_on_widgets,
				'always_online'		=> $always_online,
				'status'			=> $is_now_active,
				'status_text'		=> $status_text,
				'status_display'	=> $status_display,
				'visibility'		=> array(
					'type'		=> $visibility_content_type,
					'content'	=> $visibility_content,
				),
				'id' 				=> $account_id,
				'name'				=> $account_name,
				'number'			=> $account_number,
				'label'				=> $account_label,
				'placeholder'		=> $account_placeholder,
				'avatar_type'		=> $avatar_type,
				'avatar'			=> $account_avatar,
				'button_text'		=> $button_text,
				'online_text'		=> $online_text,
				'offline_text'		=> $offline_text,
				'unavailable_text'	=> $unavailable_text,
				'welcome_text'		=> $account_welcome_text,
				'url'				=> $chat_url,
				'wazap_icon'		=> $wazap_icon,
				'theme'				=> array(
					'theme'		=> $theme_name,
					'settings'	=> $theme_settings,
				),
			);

			return $output;
		}
		private function get_today_time_block($schedule = false){
			if ($schedule){
				$nowDate 		= date("Y-m-d H:i");
				$nameOfDay 		= strtolower(date('l', strtotime($nowDate)));
				$time_blocks 	= cs_search_array_for_ids($schedule,'day_name',$nameOfDay);
				
				if (is_array($time_blocks)){
					foreach($time_blocks as $id){
						$time_block = $schedule[$id];
						$start 		= $time_block['day_time_start'];
						$end 		= $time_block['day_time_end'];
						
						return array($start,$end);
					}
				}
			}
		}
		private function is_account_online($schedule = false){
			if ($schedule){
				$nowDate 		= date("Y-m-d H:i");
				$nameOfDay 		= strtolower(date('l', strtotime($nowDate)));
				$time_blocks 	= cs_search_array_for_ids($schedule,'day_name',$nameOfDay);
				
				if (is_array($time_blocks)){
					foreach($time_blocks as $id){
						$time_block = $schedule[$id];
						$start 		= $time_block['day_time_start'];
						$end 		= $time_block['day_time_end'];
						
						$is_within_time = $this->is_within_time($start,$end);
						if ($is_within_time){
							return 'online';
						}
					}
					return 'unavailable';
				} else {
					return "offline";
				}
			} else {
				return 'offline';
			}
		}
		private function is_within_time($start,$end){
			$nowDate 	= date("Y-m-d H:i");
			$start 		= strtotime(date($start));
			$end 		= strtotime(date($end));
			$time 		= strtotime(date("H:i", strtotime($nowDate)));
			
			if (($time >= $start) && ($time <= $end)){
				return true;
			} else {
				return false;
			}
		}
		private function get_wazap_icon(){
			$_svg 	= CS_UWAC_PLUGIN_PATH . '/common/img/whatsapp-logo-outline-black.svg';
			$_svg2 	= file_get_contents($_svg);
			$output = "<span>{$_svg2}</span>";

			return $output;
		}
		private function clean($string){
			return preg_replace("/[^a-zA-Z0-9]+/", "", $string);
		}
	}
}