<?

	$rootPath = '';
	
	require_once($rootPath . 'application.php');
	require_once($rootPath . 'security.php');
	require_once($rootPath . 'initialize.php');
	
	// Menus
	require_once($rootPath . 'menus.php');

	// Rubrique Recettes
	$_gTopic = setTopic('CONTACT');
	$_tpl->assign('Topic', $_gTopic);

	// Création de la balise Title de la page
	$_gTitle = $_gTopic->MetaTitle;
	$_gMetaFooter = $_gTopic->MetaFooter;
	
	$_tpl->assign_by_ref('Title', $_gTitle);
	$_tpl->assign_by_ref('MetaFooter', $_gMetaFooter);	

	//Récupération de l'id de l'itinéraire ou destination ou thème ou hotel 
	

	initVar($_REQUEST[URL_DESTINATION_ID], 0);
	initVar($_REQUEST[URL_THEME_ID], 0);
	initVar($_REQUEST[URL_HOTEL_ID], 0);
	initVar($_REQUEST[URL_ROUTE_ID], 0);
	initVar($_REQUEST[URL_CURRENT_ITEM], 0);
	initVar($_REQUEST['Street2'],'');
	initVar($_REQUEST['Campaigns'],0);
	initVar($_gUser['ID'], 0);
	
	//$_REQUEST[URL_ROUTE_ID]='19';
	
	
	// Initialisation des variables
	$_gCurrentItem = array();
	$_gLanguages = array();
	//$_gHotelClasses = array();

	// liste des style d'hotel
	
	$filters = array();
	$filters['IsActive'] = true;
	$filters['Language'] = $_gLanguage['LanguageID'];
	
	$hotel_style = fetchHotelStyle($filters);

	$_gHotelStyle = array();	

	if($hotel_style)
	{
		while($style = $db->sql_fetch_assoc($hotel_style))
		{
			$_gHotelStyle[$style['StyleID']] = $style;	
		}

	}
	
	$_tpl->assign('HotelStyle',$_gHotelStyle);

	//Filtres pour l'item actif
	$filters = array();
	$filters['Language'] = $_gLanguage['LanguageID'];
	$filters['IsActive'] = true;
	
	// Requêtes diverses
	$languages = getLanguages();
	

	//
	while ( $lang = $db->sql_fetch_assoc($languages) )
	{
		$_gLanguages[$lang['LanguageID']] = $lang;
	}
	
	// -- CAMPAIGNS
	$list = getCampaigns('FR');
	
	$_gCampaignss = array();
	
	while ( $item = $db->sql_fetch_assoc($list) )
	{
		//$item['FolderUrl'] = getTravelUrl($item);
		$_gCampaigns[] = $item;
	}
	
	$_tpl->assign_by_ref('Campaigns', $_gCampaigns);
	
	// Actions
	if (!empty($_REQUEST[URL_ROUTE_ID]))
	{
		$_gCurrentItem['Type']='Route';
		$_gCurrentItem['Id']=$_REQUEST[URL_ROUTE_ID];
		$Route = getRoute($_REQUEST[URL_ROUTE_ID], $filters);
		$_gCurrentItem['Name']=$Route['RouteName'];
		$_gCurrentItem['Image']=$Route['RouteMiniImage'];
		$_gCurrentItem['Text']=$Route['RouteShortText'];
		$_gCurrentItem['Url']=getRouteUrl($Route);
		$_gBreadcrumbs->add($_gCurrentItem['Type']." - " . $_gCurrentItem['Name']);	


	}
	else
	{
		if (!empty($_REQUEST[URL_THEME_ID]))
		{
			$_gCurrentItem['Type']='Theme';
			$_gCurrentItem['Id']=$_REQUEST[URL_THEME_ID];
			$Theme = getTheme($_REQUEST[URL_THEME_ID], $filters);
			$_gCurrentItem['Name']=$Theme['ThemeName'];
			$_gCurrentItem['Image']=$Theme['ThemeMiniImage'];
			$_gCurrentItem['Text']=$Theme['ThemeTextHTML'];
			$_gBreadcrumbs->add($_gCurrentItem['Type']." - " . $_gCurrentItem['Name']);	
			$_gCurrentItem['Url']=getThemeUrl($Theme);
		}
		else
		{
			if (!empty($_REQUEST[URL_HOTEL_ID]))
			{
				$_gCurrentItem['Type']='Hotel';
				$_gCurrentItem['Id']=$_REQUEST[URL_HOTEL_ID];
				$Hotel = getHotel($_REQUEST[URL_HOTEL_ID], $filters);
				$_gCurrentItem['Name']=$Hotel['HotelName'];
				$_gCurrentItem['Image']=$Hotel['HotelImage'];
				$_gCurrentItem['Text']=$Hotel['HotelOpinion'];
				$_gBreadcrumbs->add($_gCurrentItem['Type']." - " . $_gCurrentItem['Name']);	
				$_gCurrentItem['Url']=getDestinationHotelUrl($Hotel);
			}
			else
			{
				if (!empty($_REQUEST[URL_DESTINATION_ID]))
				{
					$_gCurrentItem['Type']='Destination';
					$_gCurrentItem['Id']= getDestinationIDByUrl($_REQUEST[URL_DESTINATION_ID]);
					$Destination = getDestination($_gCurrentItem['Id'], $filters);
					$_gCurrentItem['Name']=$Destination['DestinationName'];
					$_gCurrentItem['Image']=$Destination['DestinationMiniImage'];
					$_gCurrentItem['Text']=$Destination['DestinationText'];
					$_gBreadcrumbs->add($_gCurrentItem['Type']." - " . $_gCurrentItem['Name']);	
					$_gCurrentItem['Url']=getDestinationUrl($Destination);
				}
				else
				{
					$_gCurrentItem['Type']='None';
				}
			}
		}
	}
	
	$_tpl->assign_by_ref('CurrentItem', $_gCurrentItem);
	
	/*if ( empty($$_gCurrentItem['Type']) )
	{
		$url = $_gResources->get('ERR404');
		
		redirectTo( $url );
	}*/
	
	/*Destinations*/
	$_tpl->assign_by_ref('Destinations', $_gDestinations);
	$filters = array();
	$filters['Type'] = DT_CLASSIC;
	$filters['Language'] = $_gLanguage['LanguageID'];
	$filters['IsActive'] = true;
	$destinations = fetchDestination($filters);
		
	if ( $db->sql_num_rows($destinations) > 0 )
	{
		$_gDestinations = array();
			
		while ( $destination = $db->sql_fetch_assoc($destinations) )
		{
				
			$_gDestinations[$destination['DestinationID']] = $destination;
		}
	}
	

	$_tpl->assign('Languages', $_gLanguages);
	
	
	// Initialisation du classement
	setDefaultSort(SORT_UP);
	
	// Filtres	
	$url = $_gURL->get('contact.php');
	
	$mailsuccess = 0;
	
	$_tpl->assign_by_ref('mailsuccess', $mailsuccess);
	
	//ACTIONS DU FORMULAIRE DE DEMANDE DE CONTACT
	if (!empty($_REQUEST[URL_ACTION]) )
	{
			switch($_REQUEST[URL_ACTION]){
			
				case 'Send':

				// Validation du captcha

				$remoteIP = $_SERVER['REMOTE_ADDR'];

				$privateKey = '6LdVHqAaAAAAAJSRumcsSXan9R3_fkwEkuxSRnA7';

		        $api_url = "https://www.google.com/recaptcha/api/siteverify?secret="
		            . $privateKey
		            . "&response=" . $_POST['g-recaptcha-response']
		            . "&remoteip=" . $remoteIP;

		        $decode = json_decode(file_get_contents($api_url), true);

		        
		        if($decode['success'] !== true)
		        {
		        	// Le captcha n'est pas bon

					$mailsuccess = 2;
					$_gErrorMessages= 'Veuillez cocher la case de vérification';
					break;
		        }

		        // />


				// Validation PHP
				$validate = new Validate();
					
				$validate->check(
										'LastName',
										$_REQUEST['LastName'],
										array( 'isText' => array('required' => true) ),
										$_gLang['FormValidation']['LastName']
									);
				$validate->check(
										'FirstName',
										$_REQUEST['FirstName'],
										array( 'isText' => array('required' => true) ),
										$_gLang['FormValidation']['FirstName']
									);
				$validate->check(
										'Email',
										$_REQUEST['Email'],
										array( 'isEmail' => array('required' => true) ),
										$_gLang['FormValidation']['Email']
									);
				$validate->check(
										'Time',
										$_REQUEST['Time'],
										array( 'isInteger' => array('required' => false) ),
										$_gLang['FormValidation']['Time']
									);
				$validate->check(
										'Budget',
										$_REQUEST['Budget'],
										array( 'isInteger' => array('required' => false) ),
										$_gLang['FormValidation']['Budget']
									);
				$validate->check(
										'DateDebut1',
										$_REQUEST['DateDebut1'],
										array( 'isText' => array('required' => true) ),
										$_gLang['FormValidation']['DateDebut1']
									);

				if ( $validate->valid)
				{
					//Si une selection parmi les "produits" 
					if ( isset($_REQUEST['CurrentItem']['Type']) || (isset($_REQUEST['Destination']) && $_REQUEST['Destination']!=0) )
					{
					
						//Enregistrer la demande de contact 
						$group=getSubscriberGroupByReference('CONTACT');
						
						$filters = array();
						$filters['Email'] = $_REQUEST['Email'];

						$subscribers = fetchSubscribers($filters,6, SORT_DOWN, '0','1');
						$nb_subscribers = $db->sql_num_rows($subscribers);

						if ($nb_subscribers < 1)
						{
							//Ajout d'un client
							$id_subscriber = addSubscriber($group['GroupID'],$_REQUEST['LastName'],$_REQUEST['FirstName'],$_REQUEST['Email'],'','',$_REQUEST['Street'],$_REQUEST['Street2'],$_REQUEST['ZipCode'],$_REQUEST['City'],$_REQUEST['Country'],'',$_REQUEST['Phone'],'','','','','',$_REQUEST['Campaigns']);
						}
						else
						{
							$subscriber = $db->sql_fetch_assoc($subscribers);
							$id_subscriber = $subscriber['SubscriberID'];
						}
						
						//Type de demande
						$destination_id=0;
						$theme_id=0;
						$route_id=0;
						$hotel_id=0;
						
						if (isset($_REQUEST['CurrentItem']['Type']))
						{
						
							switch ($_REQUEST['CurrentItem']['Type'])
							{
								case 'Route':
											$route_id=$_REQUEST['CurrentItem']['Id'];
										break;
								
								case 'Hotel':
											$hotel_id=$_REQUEST['CurrentItem']['Id'];
										break;
								
								case 'Destination':
											$destination_id=$_REQUEST['CurrentItem']['Id'];
										break;
										
								case 'Theme':
											$theme_id=$_REQUEST['CurrentItem']['Id'];
										break;
							}
							
						}		
						
						if (isset($_REQUEST['Hotel']) && $_REQUEST['Hotel']!=0){
							$hotel_id=$_REQUEST['Hotel'];
							$hotel=getHotel($hotel_id);
							$_REQUEST['CurrentItem']['Name']=$hotel['HotelName']." ";
							$_REQUEST['CurrentItem']['Type']="Hotel";
						}
						if (isset($_REQUEST['Route'])&& $_REQUEST['Route']!=0){
							$route_id=$_REQUEST['Route'];
							$route=getRoute($_REQUEST['Route']);
							$_REQUEST['CurrentItem']['Name']=$route['RouteName']." ";
							$_REQUEST['CurrentItem']['Type']="Itinéraire";
						}
						if (isset($_REQUEST['Destination'])&& $_REQUEST['Destination']!=0){
							$destination_id=$_REQUEST['Destination'];
							$destination=getDestination($destination_id);
							$_REQUEST['CurrentItem']['Name']=$destination['DestinationName']." ";
							$_REQUEST['CurrentItem']['Type']="Destination";
						}
						if (isset($_REQUEST['Theme'])&& $_REQUEST['Theme']!=0){
							$theme_id=$_REQUEST['Theme'];
							$theme=getTheme($theme_id);
							$_REQUEST['CurrentItem']['Name']=$theme['ThemeName']." ";
							$_REQUEST['CurrentItem']['Type']="Theme";
						}				
						//Ajout d'une demand de contact
						$text_tpl="mails/website/demand.htm";
						
						$subject=$_REQUEST['CurrentItem']['Name'];
	
						$style = getHotelStyleInfos($_REQUEST['Classe']);

						$_tpl->assign_by_ref('Classe', $style['FR']['StyleName']);
	
						$_tpl->assign_by_ref('Values', $_REQUEST);
						
						$_tpl->assign_by_ref('DateDebut1', $_REQUEST['DateDebut1']);
						//$_tpl->assign_by_ref('DateDebut2', $_REQUEST['DateDebut2']);
						//$_tpl->assign_by_ref('DateFin1', $_REQUEST['DateFin1']);
						//$_tpl->assign_by_ref('DateFin2', $_REQUEST['DateFin2']);
						
						$_tpl->assign_by_ref('Title', $subject);
						
						$_tpl->assign_by_ref('Type', $_REQUEST['CurrentItem']['Type']);	
						
						$text="";
						if( $_tpl->template_exists($text_tpl) )
						{
								$text = strip_tags( html_entity_decode( $_tpl->fetch($text_tpl) ) );
						}
							
						//Sujet de la demande
						$id = addContact($destination_id,$theme_id,$route_id,$hotel_id,$id_subscriber,addslashes($subject),addslashes($text));
			
						//------------------------ MAIL --------------------------------------------
						//Envoyer un mail
						$flux = ( !empty($_gConfig['SendPacketSize']) ) ? $_gConfig['SendPacketSize'] : 100;
						$sleeptime = ( !empty($_gConfig['SendSleepTime']) ) ? $_gConfig['SendSleepTime'] : 10;
			
		
						// ----------
						$mail = new Mail();
						// Adresse de retour des bounces
						$fromname = $_gConfig['WebsiteName']; //Nom du site
						$from = $_gConfig['WebsiteEmail']; 
						$to = $_gConfig['WebsiteEmail'];  //Email du site
						$replyto = $_REQUEST['Email']; 
						
						// Ecriture du texte
						
						
						$ret = $mail->go($_tpl, 
											$to, 
											$from, 
											$fromname, 
											$replyto, 
											sprintf($_gConfig['WebsiteName'], $subject), 
											'', 
											$text_tpl);
						
						addUserLog('contacts', SEND);
						
						if (($ret == RET_ERROR) || ($ret == RET_E_MAIL)){
						
							$mailsuccess = 2;
							$_gErrorMessages = $_gLang['Error']['Mail'];
						}
						else
						{
							$mailsuccess = 1;
							$_gValidMessages = $_gLang['Valid']['Mail'];					
						}
					
					}
					//si aucun produit selectionné alors message
					else
					{
						$mailsuccess = 2;
						$_gErrorMessages= $_gLang['Error']['Contact'];
					}
	
				}
				else
				{
					$mailsuccess = 2;
					$_gErrorMessages = $validate->errors;

				}
						
			break;
		}

	}
	
	//redirectTo($url);
	

	$_tpl->display('contact.htm');

?>