<?php

include '../app/site.php';


class PopupFront {

	private $cookies=array();
	private $widget_id;
	private $iframe=false;
	private $widget_config;

	function updateStat($widget_id)
	{
		// get data from request
		// check sessions
		// check cookies
		
		$user_id=Db::selectScalar("select user_id from popup_widgets where id=?",$widget_id);
		
		$sestimeout = 30*60;
		Db::Execute("update stat_sessions set online='no', ses_end=ses_access where (UNIX_TIMESTAMP(now())-UNIX_TIMESTAMP(ses_begin))>? and online='yes'",$sestimeout);
		
		//print_r(getallheaders());
		//print_r($_COOKIE);
		
		if (!isset($_COOKIE['wcb_stat_u']))
		{ //create unique user cookie
			Db::execute("insert into stat_users set last_access=now()");
			$stat_user_id = Db::getLastID();
			setcookie('wcb_stat_u',$stat_user_id,['expires'=>time()+60*60*24*365*3,'secure' => true,'samesite' => 'None', 'path'=>'/']); //expires in three years
			
			$this->cookies['wcb_stat_u']=array(
				'name'=>'wcb_stat_u',
				'value'=>$stat_user_id,
				'exp'=>time()+60*60*24*365*3,
				'op'=>'set',
				'path'=>'/'
			);
			
			//print_r($this->cookies);
			
		}
		else 
		{
			$stat_user_id = $_COOKIE['wcb_stat_u'];
		}
		
		if (isset($_COOKIE['PHPSESSID']))
			$phpses_id=$_COOKIE['PHPSESSID'];
		else
			$phpses_id='';
		
		
		if (!isset($_COOKIE['wcb_stat_s']))
		{ //create session user cookie
		
			$screen=$_GET['screen'];
			
			$w = $screen['w'];
			$h = $screen['h'];

			//$ip=$_SERVER['REMOTE_ADDR'];
			$ip=Util::getClientIp();

			
			$entry_point=$_SERVER['HTTP_REFERER'];
			
			if (isset($_GET['ref']))
			{
				$page_ref=urldecode($_GET['ref']);
			}
			else 
			{
				$page_ref='';
			}

			/*
			$r 	= Db::Execute("select country_id from stat_country_ips where ip_from<=inet_aton('$ip') AND ip_to>=inet_aton('$ip')");
			if (!$r->eof){
					$country_id 	= $r->fields[0];
			}
			else {
					$country_id		= 0;
			}
			$r 	= Db::Execute("select city_id, (ip_to-ip_from) as weight from stat_city_ips where ip_from<=inet_aton('$ip') AND ip_to>=inet_aton('$ip') order by weight");
			if (!$r->eof){
					$city_id		= $r->fields[0];
			}
			else {
					$city_id		= 0;
			}
			*/
			
			$country_id		= 0;
			$city_id		= 0;
			
			$user_agent=isset($_SERVER["HTTP_USER_AGENT"])?$_SERVER["HTTP_USER_AGENT"]:"";
			$accept_lang=isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])?$_SERVER['HTTP_ACCEPT_LANGUAGE']:"";
				
			Db::Execute("insert into stat_sessions set ses_begin=now(), ses_access=now(), phpses_id=?, ip=?, user_id=?, widget_id=?, online='yes', browser=?, language=?, entry_point=?, page_referer=?, s_width=?, s_height=?, country=?, city=?, stat_user_id=?",
							 array($phpses_id,$ip,$user_id,$widget_id,$user_agent,$accept_lang,$entry_point,$page_ref,$w,$h,$country_id,$city_id,$stat_user_id));
			
			$session_id = Db::getLastID();
			setcookie('wcb_stat_s',$session_id,['secure' => true,'samesite' => 'None','path'=>'/']); //expires with end of session
			
			$this->cookies['wcb_stat_s']=array(
				'name'=>'wcb_stat_s',
				'value'=>$session_id,
				'exp'=>0,
				'op'=>'set',
				'path'=>'/'
			);		
			
			Db::execute("update stat_users set sessions = sessions + 1 where id=?",$stat_user_id);
		 }
		 else 
		 {
			$session_id = $_COOKIE['wcb_stat_s'];
			Db::execute("update stat_sessions set pages=pages+1, ses_access=now(), phpses_id=? where id=?",array($phpses_id,$session_id));
		 }	

		 Db::execute("update stat_users set hits = hits + 1, last_access=now() where id=?",$stat_user_id);

	}	
	
	/*
	function getTZOffset($timezone)
	{
		$userTimeZone = new DateTimeZone($timezone);
		$offset = $userTimeZone->getOffset(new DateTime("now",new DateTimeZone('GMT'))); // Offset in seconds
		return $offset/60;
	}
	*/
	
	
	function getAvailableCallDateTime($bh_id, $vizitor_tz='Europe/Paris')
	{
		//$vizitor_tz='Europe/London';
	
		if (!empty($bh_id))
		{
			// 2024 - check if all days of week is off
			$sql="select * from business_hours_hours where bh_id=?";
			$res=Db::execute($sql,array($bh_id));
			if ($res->total==0)
			{
				return array();
			}
	
			$tz=Db::selectScalar("select tz from business_hours where id=?",$bh_id);
			
			$days_off=array();
			$sql="select date_off from business_hours_days_off where bh_id=? and to_days(date_off)>=to_days(now()) order by date_off limit 60";
			$days_off_res=Db::execute($sql,$bh_id);
			while($r=$days_off_res->next(1))
			{
				$days_off[]=$r['date_off'];
			}
			
			$d = new DateTime("now", new DateTimeZone($tz));
			$today_now = new DateTime("now", new DateTimeZone($tz));
			
			//print_r($d);
			//print_r($today_now);
			
			$dates=array();
			
			// sch_rolling_days
			//print_r($this->widget_config['panel_phone']['sch_rolling_days']);
			
			$sch_rolling_days=$this->widget_config['panel_phone']['sch_rolling_days'];
			$sch_slot_duration=$this->widget_config['panel_phone']['sch_slot_duration'];
			$sch_calendar_weeks=$this->widget_config['panel_phone']['sch_calendar_weeks'];
			$date_mode=$this->widget_config['panel_phone']['sch_dates_options'];
			
			if ($date_mode=='calendar')
			{
				$sch_rolling_days=7*$sch_calendar_weeks;
			}
			
			$max_iteration=$sch_rolling_days*7;
			$iteration=0;
			
			while ((count($dates)<$sch_rolling_days) && ($iteration<$max_iteration))
			{
				//$d->add(new DateInterval("P1D"));
				$d_of_week=$d->format("w");
				$d_f=$d->format("Y-m-d");
				
				$sql="select day_of_week, from_time, to_time from business_hours_hours where bh_id=? and day_of_week=? and from_time!=to_time order by from_time";
				$hours=Db::execute($sql,array($bh_id,$d_of_week))->getArray(1);
				
				// check for holiday and 
				if (!in_array($d_f,$days_off) && !empty($hours))
				{
					$dates[$d_f]=$hours;
				}
				$d->add(new DateInterval("P1D"));
				$iteration++;
			}
			
			$dates2=array();
			$dates3=array();
			
			$di_format_string="PT".$sch_slot_duration."M";
			
			$bh_tz_dtz=new DateTimeZone($tz);
			$vizitor_tz_dtz=new DateTimeZone($vizitor_tz);
			
			//print_r($dates);
			$hours_dtz=array();
			
			foreach ($dates as $k=>$d)
			{
				// we should use start of time 
				
				//$d_tmp=new DateTime($k, $bh_tz_dtz);
				
				$d_tmp=new DateTime($k." ".$d[0]['from_time'], $bh_tz_dtz);
				
				$d_tmp->setTimezone($vizitor_tz_dtz);
				
				$hours=array();
				
				foreach($d as $dh)
				{
					$dh_start=new DateTime($k." ".$dh['from_time'], $bh_tz_dtz);
					$dh_start->setTimezone($vizitor_tz_dtz);
					$dh_end=new DateTime($k." ".$dh['to_time'], $bh_tz_dtz);
					$dh_end->setTimezone($vizitor_tz_dtz);
					while($dh_start<$dh_end)
					{
						$st=$dh_start->format('H:i');
						$dh_tmp= clone $dh_start;
						$dh_tmp->add(new DateInterval($di_format_string));
						$et=$dh_tmp->format('H:i');
						
						if ($dh_start>$today_now)
						{
							$hours[]=$st." - ".$et;
							$hours_dtz[]=array(
								'from'=>$dh_start->format('Y-m-d H:i'),
								'to'=>$dh_tmp->format('Y-m-d H:i'),
							);
						}
						
						$dh_start->add(new DateInterval($di_format_string));
					}
				}
				
				if(!empty($hours))
				{
					$dates2[$k]=array(
						'text0'=>$d_tmp->format("Y-m-d"),
						'text'=>l($d_tmp->format("l")).", ".$d_tmp->format("j/n"),
						'hours'=>$hours
					);
				}
			}
			

			
			// re-array dates/time in visitor timezone
			$hours3=array();
			$dates4=array();
			
			foreach($hours_dtz as $hdtz)
			{
				$dt_from=new DateTime($hdtz['from']);
				$dt_to=new DateTime($hdtz['to']);
			
				$d=$dt_from->format("Y-m-d");
				
				$dates3[$d]=array(
					'text'=>l($dt_from->format("l")).", ".$dt_from->format("j/n"),
				);
				
				$hours3[$d][]=$dt_from->format("H:i")." - ".$dt_to->format("H:i");
			}
			
			foreach ($dates3 as $d=>$d3v)
			{
				$dates4[$d]=array(
					'text'=>$d3v['text'],
					'hours'=>$hours3[$d]
				);
			}
			
			return $dates4;
		
		}

	}
		
	
	function getBhSettings($bh_id,$offline_action)
	{
		if (!empty($bh_id))
		{
			$day_off=false;
	
			$sql="select message, tz from business_hours where id=?";
			list($bh_message,$tz)=Db::execute($sql,$bh_id)->fields;

			$curdate = new DateTime("now", new DateTimeZone($tz));
			
			// get holidays (by date)
			$curdate_f=$curdate->format('Y-m-d');
			$sql="select date_off from business_hours_days_off where bh_id=? and date_off=?";
			$res3=Db::execute($sql,array($bh_id,$curdate_f));
			if ($res3->total>0)
			{
				$day_off=true;
			}
			else
			{
				$day_off=false;
				// check for day of week off
				$curdate_wd=$curdate->format('w');
				$curdate_t=$curdate->format('H:i:s');
				$sql="select day_of_week, from_time, to_time from business_hours_hours where bh_id=? and day_of_week=?";
				$res4=Db::execute($sql,array($bh_id,$curdate_wd));
				
				if ($res4->total>0)
				{ // there is time settings - check for time off
					
					$dt_cur =strtotime('2011-01-01 '.$curdate_t);
					$day_off=true;
					
					while($r4=$res4->next(1))
					{
						$dt_from=strtotime('2011-01-01 '.$r4['from_time']);
						$dt_to  =strtotime('2011-01-01 '.$r4['to_time']);
						
						if (($dt_from <= $dt_cur) && ($dt_cur<=$dt_to))
							$day_off=false;
					}
				}
				else
				{ // day off by week
					$day_off=true;
				}
				
			}
			/*
			$sql="select day_of_week, from_time, to_time from business_hours_hours where bh_id=?";
			$res2=Db::execute($sql,$bh_id)->getArray(1);
			$bh_data2=array();
			for($di=0;$di<7;$di++)
			{
				$temp_arr=array();
				foreach($res2 as $r)
				{
					if ($r['day_of_week']==$di)
					{
						$temp_arr[]=$r;
					}
				}
				$bh_data2[$di]=$temp_arr;
			}
			*/
			
			$bh=array(
				'message'=>$bh_message,
				//'tz'=>$tz,
				//'tz_offset'=>$this->getTZOffset($tz),
				//'bh'=>$bh_data2,
				'day_off'=>$day_off,
				'offline_action'=>$offline_action
			);
		}
		else
		{ // default values
			/*
			$bh_data2=array();
			$bh_data2[]=array();
			for($di=1;$di<6;$di++)
			{
				$bh_data2[]=array(
					'day_of_week' => $di,
					'from_time'=>'09:00:00',
					'to_time'=>'18:00:00'
				);
			}
			$bh_data2[]=array();
			
			$tz='Europe/Paris';
			*/
			
			$bh=array(
				'message'=>'',
				//'tz'=>$tz,
				//'tz_offset'=>$this->getTZOffset($tz),
				//'bh'=>$bh_data2,
				'day_ff'=>false,
				'offline_action'=>$offline_action
			);
		}	
	
		return $bh;
	}
	
	
	function translateSomeConfigItems(&$current_style)
	{
		$current_style['buttons']['email-text']=l($current_style['buttons']['email-text']);
		$current_style['buttons']['phone-text']=l($current_style['buttons']['phone-text']);
		
		$current_style['panel_phone']['title-text']=l($current_style['panel_phone']['title-text']);
		$current_style['panel_phone']['button-text']=l($current_style['panel_phone']['button-text']);
		$current_style['panel_phone']['success-message']=l($current_style['panel_phone']['success-message']);
		$current_style['panel_phone']['error-message']=l($current_style['panel_phone']['error-message']);
		
		$current_style['panel_email']['title-text']=l($current_style['panel_email']['title-text']);
		$current_style['panel_email']['button-text']=l($current_style['panel_email']['button-text']);
		$current_style['panel_email']['success-message']=l($current_style['panel_email']['success-message']);
		$current_style['panel_email']['error-message']=l($current_style['panel_email']['error-message']);
		
		$current_style['clicktocall']['title-text']=l($current_style['clicktocall']['title-text']);
		$current_style['clicktocall']['button-text']=l($current_style['clicktocall']['button-text']);
		$current_style['clicktocall']['success-message']=l($current_style['clicktocall']['success-message']);
		$current_style['clicktocall']['error-message']=l($current_style['clicktocall']['error-message']);
		$current_style['clicktocall']['welcome-text']=l($current_style['clicktocall']['welcome-text']);
		
		$current_style['common']['pd_checkbox_text']=l('pd_checkbox_text');
	}
	
	
	
	function checkIframe():bool
	{
		if (strpos($_SERVER['HTTP_REFERER'],'iframe.php')!==false)
		{
			return true;
		}
		else
		{
			$url_a=parse_url($_SERVER['HTTP_REFERER']);
			if ((in_array($url_a['host'],conf('popup.allow_hosts'))) && $_GET['iframe']=='true')
				return true;
		}
		
		return false;
	}
	
	
	function __construct()
	{
	
		Logger::log(print_r($_GET,true),'main_');
		//Logger::log(print_r($_SERVER['HTTP_REFERER'],true),'main_');
	
		if (isset($_GET['wid']))
		{
			$widget_uid=$_GET['wid'];
			
			$ip=Util::getClientIp();
			
			if (!isset($_SERVER['HTTP_REFERER'])) 
			{
				header('Content-Type: text/javascript');
				print json_encode(l("Error: something wrong with referrer"));
				die;
			}
			//elseif ((strpos($_SERVER['HTTP_REFERER'],'iframe.php')!==false) || ((in_array($_SERVER['HTTP_REFERER'],conf('popup.allow_hosts'))) && $_GET['iframe']=='true'))
			elseif ($this->checkIframe())
			{
				$this->iframe=true;
				$ref=$_GET['ref'];
			}
			else
				$ref=$_SERVER['HTTP_REFERER'];
			
			$vizitor_tz=$_GET['tz'];
			
			$res=Db::execute("select id, site_url, bh_id, offline_action, user_id, lang from popup_widgets where uid=? and status='A'",$widget_uid)->getArray();
			
			if (isset($res[0]) && !empty($res[0]))
			{
				list($widget_id,$site_url,$bh_id,$offline_action, $user_id, $lang)=$res[0];
				// check for site url
				
				$site_url_arr=explode(",",$site_url);
				
				// load lang
				Lang::load('popup',$lang);
				$lang_data=Lang::$data;
				Lang::load('common2',$lang);
				
				if (!$this->iframe)
				{
					$domain_ok=false;
					
					foreach($site_url_arr as $surl)
					{
						// delete last slash
						$surl=rtrim($surl,"/");
					
						if (strpos($surl,'*.')!==false) // all subdomains
						{
							// get parth without *. and strpos
							$surl2=substr($surl,2);
							if (strpos($ref,$surl2)!==false)
								$domain_ok=true;
							
							// with protocol
							$host_arr=parse_url($ref);
							$surl3=substr($surl,strlen($host_arr['scheme']."://")+2);
							
							if (strpos($ref,$surl3)!==false)
								$domain_ok=true;
							
						}
						else
						{
							// remove scheme and last slashe and compare
							$host_arr=parse_url($ref);
							
							if ($host_arr['host']==$surl)
								$domain_ok=true;
							 
							if ($host_arr['scheme']."://".$host_arr['host']==$surl)
								$domain_ok=true;
						
						}
					}
					
					if (!$domain_ok)
					{
						header('Content-Type: text/javascript');
						print json_encode(l("Error: wrong domain"));
						die;
					}
				}

			}
			else
			{
				header('Content-Type: text/javascript');
				print json_encode(l("Error: widget not found or not active"));
				die;
			}
			
			// get the business hours
			$bh=$this->getBhSettings($bh_id,$offline_action);
			
			$sections=conf('popups.sections');
			$current_style=conf('popups.default_styles');
			
			$this->translateSomeConfigItems($current_style);
			
			foreach($sections as $section)
			{
				$sql="select * from popup_config where widget_id=? and section=?";
				$res=Db::execute($sql,array($widget_id,$section));
				while($r=$res->next())
				{
					$current_style[$section][$r['name']]=$r['value'];
				}
				
				// fields section | field_id
				
				$sql="select wf.field_id, f.name, f.label, f.type, f.required, f.field_values
					from widget_fields as wf
					left join fields as f on f.id=wf.field_id
					where wf.widget_id=? and wf.panel=?
					order by wf.weight
				";
				
				$fields=Db::execute($sql,array($widget_id,$section))->getArray();
				
				$current_style[$section]['fields']=$fields;
			}

			$this->widget_config=$current_style;
			
			// get available calls date/time
			if (($this->widget_config['panel_phone']['sch_use_separate_bh']=='true') && isset($this->widget_config['panel_phone']['sch_bh_id']))
			{
				$sch_bh_id=$this->widget_config['panel_phone']['sch_bh_id'];
				$calls_available_dt=$this->getAvailableCallDateTime($sch_bh_id, $vizitor_tz);
			}
			else
			{
				$calls_available_dt=$this->getAvailableCallDateTime($bh_id, $vizitor_tz);
			}
			
			
			// add countries to additional
			$countries=array();
			$countries_intlTel=array();
			
			if (isset($current_style['clicktocall']['authorized-countries']) && !empty($current_style['clicktocall']['authorized-countries']))
			{
				$contries_ids=json_decode($current_style['clicktocall']['authorized-countries']);
				foreach($contries_ids as $cid)
				{
					$sql="select id, name, iso2, phone_code, type, pattern from countries where id=? and status='A'";
					$country=Db::execute($sql,$cid)->getArray(1);
					$countries[]=$country[0];
					
					$code=strtolower($country[0]['iso2']);
					$type=$country[0]['type'];
					// we need collect types from all country records
					if (!isset($countries_intlTel[$code]))
						$countries_intlTel[$code]=$type;
					else
						$countries_intlTel[$code].=",".$type;
				}
			}
			
			// prepare countrues2 array for intlTelInput
			
			
			/*
			$countries_intlTel=array();
			
			foreach($countries as $c)
			{
				$code=strtolower($c['iso2']);
				if (isset($countries_intlTel[$code]))
				{
					$countries_intlTel[$code].=$c['type'];
				}
				else
				{
					$countries_intlTel[$code]=$c['type'];
				}
			}
			if (empty($countries_intlTel)) 
			{
				$countries_intlTel['fr']='fixedmobile'; //any
			}
			*/
			
			// countries for email panel
			$user_countries_ids=json_decode(Db::selectScalar("select countries from user_additional where user_id={$user_id}"),true);
			$sql="select distinct iso2 from countries where id in (".implode(",",$user_countries_ids).")";
			$user_countries_res=Db::execute($sql);
			while($r=$user_countries_res->next())
				$user_countries[]=$r['iso2'];
			if (empty($user_countries))
				$user_countries[]="fr";
			
			
			// offline mode
			$offline_mode="tel";
			if (isset($current_style['clicktocall']['display-email-request']) && $current_style['clicktocall']['display-email-request']=="true")
				$offline_mode="mail";
			
			
			$additional=array(
				'ip'=>$ip,
				'country'=>Util::getCountryByIP($ip),
				'countries'=>$countries,
				'countries_intl_tel'=>$countries_intlTel,
				'user_countries'=>$user_countries,
				'offline_mode'=>$offline_mode,
				'lang'=>$lang,
				'lang_data'=>$lang_data
			);
			
			$sql="select scheduled_callback_enabled, wcb_enabled, wcb_account_id, wcb_secret_key, business_rules_enabled, dynamic_destination_enabled, pwlogo_display, pwlogo_text, pwlogo_link, pwlogo_position, pwlogo_suffix from user_additional where user_id=?";
			$wcb_res=Db::execute($sql,$user_id)->getArray(1);
			$wcb_res=$wcb_res[0];
			
			if ($wcb_res['wcb_enabled']=='Y')
				$wcb=true;
			else
				$wcb=false;
			
			$scheduled_callback_enabled=false;
			if ($wcb_res['scheduled_callback_enabled']=='Y')
				$scheduled_callback_enabled=true;
				
			$business_rules_enabled=false;
			if ($wcb_res['business_rules_enabled']=='Y')
				$business_rules_enabled=true;

			$dynamic_destination_enabled=false;
			
			//$departments=[];
			$dd_set=$dd_set_items=[];
			
			if ($wcb_res['dynamic_destination_enabled']=='Y')
			{
				$dynamic_destination_enabled=true;
				
				/*
				// get departments list
				$csvFile = file(_INC_ROOT.'libs/departements-france.csv');
				foreach ($csvFile as $nl=>$line) 
				{
					if ($nl==0)
						continue;
					$departments[] = str_getcsv($line);
				}
				// get dd for this 
				*/
				
				// load set and set_items from database
				$selected_set=$current_style['clicktocall']['dd_set'];
				
				$sql="select * from dd_sets where id=?";
				$dd_set_res=Db::execute($sql,$selected_set)->getArray(1);
				
				if (empty($dd_set_res))
				{
					$dd_set=0;
					$dd_set_items=array();
				}
				else
				{
					$dd_set=$dd_set_res[0];
					$sql="select * from dd_sets_items where set_id=? order by weight,id";
					$dd_set_items=Db::execute($sql,$selected_set)->getArray(1);
				}
			}
			

			// setup pwlogo_text && pwlogo_img
			if (!empty($wcb_res['pwlogo_text']))
				$pwlogo_text=$wcb_res['pwlogo_text'];
			else
				$pwlogo_text=conf('popups.pwlogo_text');
			
			if (!empty($wcb_res['pwlogo_link']))
				$pwlogo_link=$wcb_res['pwlogo_link'];
			else
				$pwlogo_link=conf('popups.pwlogo_link');
			
			
			if (file_exists(Util::getClientFolder($user_id,true)."/pwlogo".$wcb_res['pwlogo_suffix'].".png"))
				$pwlogo_img="https://".$_SERVER['HTTP_HOST'].Util::getClientFolder($user_id,false)."/pwlogo".$wcb_res['pwlogo_suffix'].".png";
			else // get image of current theme
				$pwlogo_img="https://".$_SERVER['HTTP_HOST']."/themes/voxolib/img/logo-light.png";
				
			// get the fonts
			$sql="select * from fonts where status='A'";
			$res=Db::execute($sql);
			$fonts=array();
			while($r=$res->next(1))
			{
				$r['font_items']=Db::execute("select * from fonts_items where owner_id=? order by weight",$r['id'])->getArray(1);
				$fonts[]=$r;
			}
				
			
			$config=array(
				'style'=>$current_style,
				'common'=>$current_style['common'],
				'bh'=>$bh,
				'call_available_dt'=>$calls_available_dt,
				'captcha_sitekey'=>conf('popups.v2_re_captcha_client_key'),
				'additional'=>$additional,
				'wcb'=>$wcb,
				'scheduled_callback_enabled'=>$scheduled_callback_enabled,
				'business_rules_enabled'=>$business_rules_enabled,
				'dynamic_destination_enabled'=>$dynamic_destination_enabled,
				'dd_set'=>$dd_set,
				'dd_set_items'=>$dd_set_items,
				'pwlogo_display'=>$wcb_res['pwlogo_display'],
				'pwlogo_text'=>$pwlogo_text,
				'pwlogo_img'=>$pwlogo_img,
				'pwlogo_link'=>$pwlogo_link,
				'pwlogo_position'=>$wcb_res['pwlogo_position'],
				'fonts'=>$fonts
			);
			
			// remove unnecesary 
			$current_style2 = $current_style;
			$common2=$current_style['common'];
			$bh2=$bh;
			
			unset($current_style2['panels']);
			unset($current_style2['panel_phone']);
			unset($current_style2['clicktocall']);
			unset($current_style2['left-panel']);
			unset($current_style2['common']);
			
			// widget_id
			unset($current_style2['buttons']['widget_id']);
			unset($current_style2['panel_email']['widget_id']);
			unset($current_style2['extanal']['widget_id']);
			unset($current_style2['css']['widget_id']);
			unset($current_style2['rules']['widget_id']);
			unset($current_style2['rules_behaviour']['widget_id']);
			unset($current_style2['tags']['widget_id']);
			
			unset($common2['widget_id']);
			unset($bh2['widget_id']);
			
			
			$config2=array( // return to js
				'style'=>$current_style2,
				'common'=>$common2,
				'bh'=>$bh2,
				'call_available_dt'=>$calls_available_dt,
				'additional'=>$additional,
				'wcb'=>$wcb,
				'scheduled_callback_enabled'=>$scheduled_callback_enabled,
				'business_rules_enabled'=>$business_rules_enabled,
			);
			
			

			ob_start();
			include("b.tpl.php");
			$content = ob_get_contents();
			ob_end_clean();
			
			$this->updateStat($widget_id);

			$res=array(
				'config'=>$config2,
				'content'=>$content,
				//'cookies'=>$this->cookies
			);

			header('Content-Type: text/javascript');
			print "wc_client_init_callback_function(".json_encode($res).")";
			
		}	
	
	}


}


$pf=new PopupFront();



