<?php
///////////////////////////////////////////////////////////////////////////////////////////
///Script PHP/MYSQL of management of classifieds ads developed by Script PAG
///Script PAG all rights reserved. Use under license. http://www.script-pag.com
///////////////////////////////////////////////////////////////////////////////////////////

############################################################

require_once __DIR__.'/includes/all_fns.php';
require_once __DIR__.'/includes/calendar/fns_calendar.php';
require_once __DIR__.'/includes/functions/uploader/uploadManager.php';

///////////////////////////////////
//Validation of the ad ID
//////////////////////////////////

if(isset($_GET['id_ad']))
{
	$id_ad = (int) $_GET['id_ad'];
	
	if($id_ad <= 0)
	redirect('index.php');
	
	$row = get_ad($id_ad, 2);
	$id_acc = $row['id_acc'];
	$password = $row['password'];
	$video_payed = $row['video_num'];
	
	if(empty($row))
	redirect('index.php');
}
else redirect('index.php');

///////////////////////////////////
//Initialisation de la variable $error
//////////////////////////////////

$error = array();

///////////////////////////////////
//Validation of password
//////////////////////////////////

if(isset($_POST['password']))
{
	if(verify_ad($id_ad, $_POST['password']))
	{
		$_SESSION['token_update'] = md5($id_ad .'JsickJSQINzLQ'. $password);
		$error = 0;
	}
	
	else $error = 1;
}

///////////////////////////////////
//Get field values
//////////////////////////////////

$infos = get_ad($_GET['id_ad'], 2);
$opts_digital = get_opts_ad_digital($_GET['id_ad']);
$opts_data = get_opts_ad_data($_GET['id_ad']);
$opts_check = get_opts_ad_check($_GET['id_ad']);
$fields = get_ad_fields($_GET['id_ad']);
$calendar = 0;
$files = 0;
$images = get_ad_pictures($_GET['id_ad']);

//Files
if(!empty($files)) {
	$new_files = array();
	foreach($files as $file) $new_files[] = isset($file['name']) ? $file['name'] : str_replace('/upload/files/', '', $file);
	$files = $new_files;
}

//Images
if(!empty($images)) {
	$new_images = array();
	foreach($images as $img) $new_images[] = isset($img['name']) ? $img['name'] : str_replace('/upload/photos/', '', $img);
	$images = $new_images;
}

//Digital options

if(is_array($opts_digital))
{
	foreach($opts_digital as $v)
	{
		if($v['id_ad'] == $_GET['id_ad'])
		$infos['digital_'. $v['id_cat_opt']] = $v['val_digital'];
	}
}

//Data options

if(is_array($opts_data))
{
	foreach($opts_data as $v)
	{
		if($v['id_ad'] == $_GET['id_ad'])
		$infos['data_'. $v['id_cat_opt']] = $v['id_val_data'];
	}
}

//Checkbox options

if(is_array($opts_check))
{
	foreach($opts_check as $v)
	{
		if($v['id_ad'] == $_GET['id_ad'])
		$infos['check_'. $v['id_val_check']] = $v['id_val_check'];
	}
}

//Fields

if(is_array($fields))
{
	foreach($fields as $v)
	{
		$id_field = $v['id_field'];			
		$infos['field_'. $id_field] = $v['value'];
	}
}

//Calendar

if(count($_POST) <= 0 && isset($_SESSION['cal_period']))
unset($_SESSION['cal_period']);

if(count($_POST) <= 0)
{
	if(is_array($calendar) && !isset($_SESSION['cal_period']))
	{
		foreach($calendar as $v)
		{
			$start_end = date('d/m/Y', $v['start_date']);
			$end_date = date('d/m/Y', $v['end_date']);
			$cal_price = $v['price'];
			
			$_SESSION['cal_period'][] = array($start_end, $end_date, $cal_price);
		}
	}
}

///////////////////////////////////
//Validation of the region
//////////////////////////////////

if(!empty($_POST['reg']))
$infos['id_reg'] = (int) $_POST['reg'];

///////////////////////////////////
//Validation of the county
//////////////////////////////////

if(!empty($_POST['county']))
$infos['id_county'] = (int) $_POST['county'];

///////////////////////////////////
//Get price of the update
///////////////////////////////////

$price_ad = 0;

foreach($cache_cat as $v)
{
	if($v['id_cat'] == $infos['id_cat'])
	{
		if($infos['status'] == 1)
		$price_ad = (float) $v['price_par_mod'];
		
		else $price_ad = (float) $v['price_pro_mod'];
	}
}

$price_ad = number_format($price_ad, 2, '.', '');

///////////////////////////////////
//Check if there is a discount code
//////////////////////////////////
	
$display_discount_code = 0;
		
foreach($cache_discount_code as $v)
{
	if($v['val2'] == 1)
	{
		$display_discount_code = 1;
	}
}

///////////////////////////////////
//Validation of datas
//////////////////////////////////

if(isset($_POST['name']))
{
	if (empty($_POST['name']))
	$error['name'] = 1;
	
	if($cache_param_fields['act_phone'] == 1)
	{
		if (empty($_POST['phone']))
		$error['phone'] = 1;
	}
	
	if($infos['id_cat'] != 0)
	{
		foreach($cache_search_digital as $row)
		{
			$id_cat = (int) $row['id_cat'];
			$id_cat_opt_digital = (int) $row['id_cat_opt'];
			$optional = 0;
			
			foreach($cache_cat_opts as $opt)
			{
				$id_cat_opt = (int) $opt['id_cat_opt'];
				$type_cat_opt = (int) $opt['type_cat_opt'];
				
				if($type_cat_opt != 1)
				continue;
				
				if($id_cat_opt_digital == $id_cat_opt)
				{
					$optional = (int) $opt['optional'];
					break;
				}
			}
		 
			if($optional == 0 && $id_cat == $infos['id_cat'])
			{
				if(empty($_POST['digital_'. $id_cat_opt_digital]) || !is_numeric($_POST['digital_'. $id_cat_opt_digital]))
				$error['digital_'. $id_cat_opt_digital] = 1;
			}
			elseif(!empty($_POST['digital_'. $id_cat_opt_digital]) && !is_numeric($_POST['digital_'. $id_cat_opt_digital]))
			$error['digital_'. $id_cat_opt_digital] = 1;
		}
	}

	if($infos['id_cat'] != 0)
	{
		foreach($cache_val_data as $row)
		{
			$id_cat_opt_data = (int) $row['id_cat_opt'];
			$optional = 0;
			
			foreach($cache_cat_opts as $opt)
			{
				$id_cat_opt = (int) $opt['id_cat_opt'];
				$type_cat_opt = (int) $opt['type_cat_opt'];
				
				if($type_cat_opt != 2)
				continue;
				
				if($id_cat_opt_data == $id_cat_opt)
				{
					$optional = (int) $opt['optional'];
					break;
				} 
			}
		 
			if($optional == 0)
			{
				if(isset($_POST['data_'. $id_cat_opt_data]) && empty($_POST['data_'. $id_cat_opt_data]))
				$error['data_'. $id_cat_opt_data] = 1;
			}
		}
	}
	
	foreach($cache_fields as $row)
	{
		$id_field = (int) $row['id_field'];
		$id_cat = (int) $row['id_cat'];
		$type = (int) $row['type'];
		$optional = $row['optional'];
	 
		if($optional == 1)
		{
			if($type == 1 && empty($_POST['field_'. $id_field]) && ($id_cat == 0 || $id_cat == $infos['id_cat']))
			$error['field_'. $id_field] = 1;
			
			elseif($type == 2 && (empty($_POST['field_'. $id_field]) || preg_match("#^[0-9]+$#", $_POST['field_'. $id_field]) != true) && ($id_cat == 0 || $id_cat == $infos['id_cat']))
			$error['field_'. $id_field] = 1;
			
			elseif($type == 3 && (empty($_POST['field_'. $id_field]) || preg_match("#^https?://#", $_POST['field_'. $id_field]) != true) && ($id_cat == 0 || $id_cat == $infos['id_cat']))
			$error['field_'. $id_field] = 1;
		}
		else
		{
			if($type == 2 && !empty($_POST['field_'. $id_field]) && preg_match("#^[0-9]+$#", $_POST['field_'. $id_field]) != true)
			$error['field_'. $id_field] = 1;
			
			elseif($type == 3 && !empty($_POST['field_'. $id_field]) && preg_match("#^https?://#", $_POST['field_'. $id_field]) != true)
			$error['field_'. $id_field] = 1;
		}
	}
	
	if((!isset($_SESSION['connect_id']) || $_SESSION['connect_id'] != $infos['id_acc']) && $infos['status'] == 2)
	{
		if(empty($_POST['comp_name']))
		$error['comp_name'] = 1;
		
		if($cache_param_fields['act_comp_num'] == 1)
		{
			if (empty($_POST['comp_num']))
			$error['comp_num'] = 1;
		}
	}
	
	if (empty($_POST['title']))
	$error['title'] = 1;
	
	elseif(preg_match('/([0-9#][\x{20E3}])|[\x{00ae}\x{00a9}\x{203C}\x{2047}\x{2048}\x{2049}\x{3030}\x{303D}\x{2139}\x{2122}\x{3297}\x{3299}][\x{FE00}-\x{FEFF}]?|[\x{2190}-\x{21FF}][\x{FE00}-\x{FEFF}]?|[\x{2300}-\x{23FF}][\x{FE00}-\x{FEFF}]?|[\x{2460}-\x{24FF}][\x{FE00}-\x{FEFF}]?|[\x{25A0}-\x{25FF}][\x{FE00}-\x{FEFF}]?|[\x{2600}-\x{27BF}][\x{FE00}-\x{FEFF}]?|[\x{2900}-\x{297F}][\x{FE00}-\x{FEFF}]?|[\x{2B00}-\x{2BF0}][\x{FE00}-\x{FEFF}]?|[\x{1F000}-\x{1F6FF}][\x{FE00}-\x{FEFF}]?/u', $_POST['title']))
	$error['title'] = 2;
	
	if (empty($_POST['text']))
	$error['text'] = 1;
	
	elseif(preg_match('/([0-9#][\x{20E3}])|[\x{00ae}\x{00a9}\x{203C}\x{2047}\x{2048}\x{2049}\x{3030}\x{303D}\x{2139}\x{2122}\x{3297}\x{3299}][\x{FE00}-\x{FEFF}]?|[\x{2190}-\x{21FF}][\x{FE00}-\x{FEFF}]?|[\x{2300}-\x{23FF}][\x{FE00}-\x{FEFF}]?|[\x{2460}-\x{24FF}][\x{FE00}-\x{FEFF}]?|[\x{25A0}-\x{25FF}][\x{FE00}-\x{FEFF}]?|[\x{2600}-\x{27BF}][\x{FE00}-\x{FEFF}]?|[\x{2900}-\x{297F}][\x{FE00}-\x{FEFF}]?|[\x{2B00}-\x{2BF0}][\x{FE00}-\x{FEFF}]?|[\x{1F000}-\x{1F6FF}][\x{FE00}-\x{FEFF}]?/u', $_POST['text']))
	$error['text'] = 2;
	
	if(!empty($_POST['video']) && !preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $_POST['video']) && !preg_match('%(?:dailymotion\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|video/|.*[?&]v=)|dai\.ly/)([^"&?/ ]*)%i', $_POST['video'], $matches) && !preg_match('%(?:vimeo\.com/(?:[^/]+/.+/|(?:video/)?|.*[?&]v=))([^"&?/ ]*)%i', $_POST['video'], $matches) && !preg_match("%(?:yahoo\.com/video/)%i", $_POST['video']))
	$error['video'] = 1;
	
	if($cache_param_fields['act_price'] == 1)
	{
		if(!empty($_POST['price']) && (preg_match("#^[0-9]+?[,.]?([0-9]+)?$#", $_POST['price']) != true))
		$error['price'] = 1;
	}
	
	if(!empty($_POST['discount_code']))
	{
		$error_code = 0;
		$code = htmlspecialchars($_POST['discount_code']);
		
		foreach($cache_discount_code as $v)
		{
			if($v['code'] == $code && $v['val2'] == 1)
			{
				$error_code = 1;
			}
		}
		
		if($error_code == 0)
		$error['code'] = 1;
	}
	
	if(empty($_POST['reg']))
	$error['reg'] = 1;
	
	if(isset($_POST['county']) && empty($_POST['county']))
	$error['county'] = 1;
	
	if($cache_param_fields['act_postcode'] == 1)
	{
		if (empty($_POST['postcode']))
		$error['postcode'] = 1;
	}
	
	if($cache_param_fields['act_city'] == 1)
	{
		if (empty($_POST['city']))
		$error['city'] = 1;
	}
	
	if($param_api_gg['activ_gg_map'] == 1 && (empty($_POST['lat']) || empty($_POST['lng'])) && is_allowed_cookie('googlemap'))
	$error['geolocation'] = 1;
	
	if(strlen($blacklist_keywords['keywords']) > 0)
	{
		$keywords = explode(',', str_replace(' ', '', $blacklist_keywords['keywords']));
		
		foreach($keywords as $v) {
			if(preg_match('#^'. rewriting($v) .' #', str_replace('-', ' ', rewriting($_POST['text']))) || preg_match('# '. rewriting($v) .'$#', str_replace('-', ' ', rewriting($_POST['text']))) || preg_match('# '. rewriting($v) .' #', str_replace('-', ' ', rewriting($_POST['text']))))
			$error['keywords'] = 1;
		}
	}
	
	if(isset($_POST['photo']) || isset($_POST['remove_photo'])) {
		$images = isset($_POST['photo']) ? $_POST['photo'] : array();
		$new_images = array();
		foreach($images as $key => $img) $new_images[$key] = is_array($img) ? $img : (empty($error) ? str_replace('/upload/photos/', '', $img) : $img);
		$images = $new_images;	
	}
	if(isset($_POST['file']) || isset($_POST['remove_file'])) {
		$files = isset($_POST['file']) ? $_POST['file'] : array();
		$new_files = array();
		$keys = array();
		foreach($files as $key => $file) $new_files[$key] = is_array($file) ? $file : str_replace('/upload/files/', '', $file);
		$files = $new_files;

	}
}

///////////////////////////////////
//Variables of elements
//////////////////////////////////

$index = 0;
$account = 0;

///////////////////////////////////
//Update ad
//////////////////////////////////

if(isset($_POST['name']) && empty($error))
{
	$price = 0;
	$pack_photo = $infos['pictures_pack'];
	
	if($cache_global_pay['valid'] == 1)
	{
		//Price of the update
		
		$price_ad = 0;
		
		foreach($cache_cat as $v)
		{
			if($v['id_cat'] == $infos['id_cat'])
			{
				if($infos['status'] == 1)
				$price_ad = (float) $v['price_par_mod'];
				
				else $price_ad = (float) $v['price_pro_mod'];
			}
		}
		
		//Price of the photo pack
		
		$price_photo = 0;
		
		if(!empty($_POST['photo']))
		{
			if(sizeof($_POST['photo']) > $cache_photo_opt['nb_photo_free'] && $pack_photo == 0)
			{
				$price_photo = $cache_photo_opt['price_pack'];
				$pack_photo = 1;
			}
		}
		
		//Price of the vidéo
		
		$price_video = 0;
		
		if(empty($video_payed))
		{
			if(!empty($_POST['video']))
			$price_video = (float) $cache_video_opt['price_video'];
		}
		
		//Price total
		
		$price = $price_ad + $price_photo + $price_video;
	}
	
	//Discount
	
	if(!empty($_POST['discount_code']))
	{
		$code = htmlspecialchars($_POST['discount_code']);
		
		$price_code = '';
		$type_code = '';
		
		foreach($cache_discount_code as $v)
		{
			if($v['code'] == $code)
			{
				$price_code = (float) $v['price'];
				$type_code = (int) $v['type'];
			}
		}
		
		if($type_code == 1)
		$price = $price - $price_code;
		
		else
		{
			$price_red = $price * $price_code / 100;
			$price = $price - $price_red;
		}
		
		$str_type_code = ($type_code == 1) ? $param_gen['currency'] : '%';
		
		$_SESSION['discount_code'] = '-'. $price_code .' '. $str_type_code;
	}
	else $_SESSION['discount_code'] = '';
	
	if($price > 0)
	$state = 5;
	
	elseif($param_gen['auto_ads'] == 1)
	$state = 2;
	
	else $state = 1;
	
	//Format file and photo
	if(isset($_POST['photo']) || isset($_POST['remove_photo'])) {
		$images = isset($_POST['photo']) ? $_POST['photo'] : array();
		if(empty($error) && isset($_POST['photo']) && !empty($_POST['photo'])) {
			$upload = new uploadManager();
			$images = $upload->moveFile(array('move_file' => $_POST['photo'], 'context' => 'ad_photo'));
		}
		if(empty($error) && isset($_POST['remove_photo']) && !empty($_POST['remove_photo'])) {
			@unlink(__DIR__.'/..'.str_replace(URL, '', $_POST['remove_photo']));
		}
		$new_images = array();
		foreach($images as $img) {
			if(strpos($img, '/upload/photos/') > -1) $new_images[] = !preg_match('#^(https|http)?://#', $img) ? str_replace('/upload/photos/', '', $img) : $img;
			else continue;
		}
		$images = $new_images;
	}

	if(isset($_POST['file']) || isset($_POST['remove_file'])) {
		$files = isset($_POST['file']) ? $_POST['file'] : array();
		if(empty($error) && isset($_POST['file']) && !empty($_POST['file'])) {
			$upload = new uploadManager();
			$files = $upload->moveFile(array('move_file' => $_POST['file'], 'context' => 'ad_file'));
		}
		if(empty($error) && isset($_POST['remove_file']) && !empty($_POST['remove_file'])) {
			@unlink(__DIR__.'/..'.str_replace(URL, '', $_POST['remove_file']));
		}
		$new_files = array();
		foreach($files as $file) $new_files[] = str_replace('/upload/files/', '', $file);
		$files = $new_files;
	}
	
	update_ad($_POST, $_GET['id_ad'], $state, $pack_photo, $video_payed, $images, $files);
	get_nb_ads();
	
	if($price > 0)
	{
		$_SESSION['item'] = $language['item12_page_payment'];
		
		if($param_invoice['excl_vat'] == 1)
		$price_vat = (!empty($param_invoice['vat_rate'])) ? $price * $param_invoice['vat_rate'] / 100 : 0;
		
		else
		{
			$price_vat = $price / (1 + ($param_invoice['vat_rate'] / 100));
			$price_vat = $price - round($price_vat, 2);
			
			$price =  $price - $price_vat;
		}
		
		$_SESSION['price'] = $price;
		$_SESSION['price_vat'] = $price_vat;
		
		$id_pursh = register_purchase(1, $infos['id_ad'], 0, 0, 0, 0, 0, 0, time(), $price, $price_vat);
		$conn = null;
		
		$_SESSION['id_purch'] = $id_pursh;
		
		redirect('payment.php');
	}
	
	///////////////////////////////////
	//Sending the notification email
	//////////////////////////////////

	if($param_gen['notif'] == 1)
	{
		$nb_ads = count_ad_mail();

		if($nb_ads == 1)
		send_notif_ad();
	}
	
	$conn = null;
	
	redirect('ad_update.php?action=SuccesUpdate&id_ad='. $id_ad);
}

///////////////////////////////////
//Form update
//////////////////////////////////

elseif(((isset($_SESSION['connect_id']) && $_SESSION['connect_id'] == $id_acc) || (isset($_SESSION['token_update']) && $_SESSION['token_update'] == md5($id_ad .'JsickJSQINzLQ'. $password))) && (!isset($_GET['action']) || $_GET['action'] != 'SuccesUpdate'))
{
	///////////////////////////////////
	//Title and Meta
	//////////////////////////////////
	
	$title = $language['title_form_update_ad'];
	$description = $language['description_form_update_ad'];
	$words = $language['keywords_form_update_ad'];
	$info_page = $language['info_form_update_ad'];
		
	///////////////////////////////////
	//Display view
	//////////////////////////////////
	
	pool::execute('beforestart');
	
	$view = array();
	$view[] = 'template/tpl_form_update.php';
	
	require_once __DIR__.'/template/tpl_layout.php';
}

///////////////////////////////////
//Update confirmation
//////////////////////////////////

elseif(isset($_GET['action']) && $_GET['action'] == 'SuccesUpdate')
{
	///////////////////////////////////
	//Title and Meta 
	//////////////////////////////////

	$title = $language['title_page_update_ad_conf'];
	$description = $language['description_page_update_ad_conf'];
	$words = $language['keywords_page_update_ad_conf'];
	$info_page = $language['info_page_update_ad_conf'];

	///////////////////////////////////
	//Text of the page
	//////////////////////////////////
	
	if($param_gen['auto_ads'] == 1)
	$text = $language['page_update_ad_conf_auto'];
	
	else $text = $language['page_update_ad_conf'];

	///////////////////////////////////
	//Display view
	//////////////////////////////////
	
	pool::execute('beforestart');

	$view = array();
	$view[] = 'template/tpl_txt.php';
	
	require_once __DIR__.'/template/tpl_layout.php';
}
else
{
	///////////////////////////////////
	//Title and Meta
	//////////////////////////////////
	
	$title = $language['title_page_enter_password'];
	$description = $language['description_page_enter_password'];
	$words = $language['keywords_page_enter_password'];
	$info_page = $language['info_page_enter_password'];
		
	///////////////////////////////////
	//Display view
	//////////////////////////////////
	
	pool::execute('beforestart');
	
	$view = array();
	$view[] = 'template/tpl_form_ad_check_psw.php';
	
	require_once __DIR__.'/template/tpl_layout.php';
}