<?php
// Check if we have done any kind of webservices requests for records
$yp_cache_folder = $modules_path . "yp_middle/cache";
$yp_cache_file = $yp_cache_folder . "/last_ws_get_" . $domain_id . ".log";
$have_yp_cache_file = false;
$need_yp_get = false;

if(file_exists($yp_cache_file)) {
	$yp_time_now = time();
	if($yp_time_now - filemtime($yp_cache_file) > 30 * 24 * 60 * 60) {
		$need_yp_get = true;
	}
}
else {
	$need_yp_get = true;
}

if(isset($_REQUEST['yp_renew'])) {
	$need_yp_get = true;
	
}


if($need_yp_get) {
	if(isset($_REQUEST['debug'])) echo "<br/>MUST RENEW YP Categories";
	if(!function_exists("makeFriendlyName")) {
		function makeFriendlyName($string, $lang='en') {
			mb_internal_encoding('UTF-8');
			$friendly_url = trim(preg_replace('#[^\p{L}\p{N}]+#u', ' ', trim($string)));
			$frp = preg_split('/[\s]+/u', $friendly_url);
			if(count($frp)) {
				$glue = array();
				foreach ($frp as $fpart) {
					if(trim($fpart) != "") $glue[] = trim($fpart);
				}
				
				$friendly_url = implode("-", $glue);
			}
		
			return mb_strtolower($friendly_url, 'UTF-8');
		}
	}
	
	if(!function_exists("mysql_insert")) {
		function mysql_insert($table, $inserts) {
		    $values = array_map('mysql_real_escape_string', array_values($inserts));
		    $keys = array_keys($inserts);
			$q = 'REPLACE INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')';
		    $r = @mysql_query($q);
		    if($r && mysql_affected_rows() != -1) {
		    	return true;
		    }
		    else {
		    	echo "<br/><strong>$q</strong>" . mysql_error();
		    	return false;
		    }
		}
	}
	
	if(!isset($module_params) || !is_array($module_params) || count($module_params) == 0) {
		$dir_module_id = $req_modules['yp_middle']['module_id'];
		$q = "select * from left_content where catdom_id='$domain_id' and module_id='$dir_module_id' and type='module' and location='middle';";
		if(isset($_REQUEST['debug'])) echo "<br/>$q";
		$r = mysql_query($q) or die("<strong>$q</strong>".mysql_error());
		if($r && mysql_num_rows($r) > 0) {
			$row = mysql_fetch_assoc($r);
			$module_params = trim($row['module_params']) != "" ? unserialize(base64_decode($row['module_params'])) : false;
			if(isset($_REQUEST['debug'])) {
				echo "<br/>We found the following in module_params: ";
				echo '<pre>', var_export($module_params, true), '</pre>';
			}
			
		}
		
	}
	
	
	
	if(isset($module_params['module_yp_categs']) && is_array($module_params['module_yp_categs']) && count($module_params['module_yp_categs']) > 0) {
		if(isset($_REQUEST['debug'])) {
			echo '<pre>', var_export($module_params, true), '</pre>';
		}
		$module_yp_categs = $module_params['module_yp_categs'];
		$categs_uids = array_keys($module_yp_categs);
	
		$qupd = "ALTER TABLE `yp_categories_links` ADD `district` VARCHAR( 64 ) NOT NULL , ADD `location` VARCHAR( 64 ) NOT NULL ";
		$rupd = @mysql_query($qupd);		
		
		$categs_uids_str = implode(",", $categs_uids);
		$categs_uids_str = "'" . str_replace(",", "','", $categs_uids_str) . "'";
		// We must clear old records
		// Delete Businesses
		
		$buids = array();
		$q = "select business_uid from yp_businesses_categories where category_uid in ($categs_uids_str);";
		$r = mysql_query($q) or die("<strong>$q</strong>".mysql_error());
		if($r && mysql_num_rows($r) > 0) {
			while ($row = mysql_fetch_assoc($r)) {
				$business_uid = $row['business_uid'];
				$buids [] = "delete from yp_businesses where uid='$business_uid';";
				$buids [] = "delete from yp_businesses_locations where business_uid='$business_uid';";
			}
		}
		
		if(count($buids) > 0) {
			foreach ($buids as $i=>$qdelb) {
				$r = mysql_query($qdelb) or die("<strong>$qdelb</strong>".mysql_error());
				if(isset($_REQUEST['debug_yp'])) {
					echo "<br/>$qdelb";
				}
			}
		}
		
		//$qdb = "delete from yp_businesses b where b.uid in (select c.business_uid from yp_businesses_categories c where c.category_uid in ($categs_uids_str));";
		//$rdb = mysql_query($qdb) or die("<strong>$qdb</strong>".mysql_error());
		
		//if(isset($_REQUEST['debug_yp'])) {
		//	echo "<br/>$qdb";
		//}
		
		// Delete Business-Category Relations
		$qdbc = "delete from yp_businesses_categories where category_uid in ($categs_uids_str);";
		$rdbc = @mysql_query($qdbc);
		
		// Delete Category Aliases
		$qda = "delete from yp_categories_links where uid in ($categs_uids_str);";
		//echo "<br/><strong>$qda</strong>";
		$rda = @mysql_query($qda);
		
		// Delete Categories
		$qdc = "delete from yp_categories where uid in ($categs_uids_str);";
		$rdc = @mysql_query($qdc);
		
		
		require_once(dirname(__FILE__) . "/../wsbin/lib/nusoap.php");
		require_once(dirname(__FILE__) . "/../wsbin/ws_functions.php");
		
		$ret = array(
			"result"	=> 0,
			"categs"	=> array()
		);
		$yp_categs = array();
		
		$_request = array(
			"categs" 			=> $categs_uids
		);
		
		$ws_request = array(
			'server_name' 		=> 'yellowpages',
			'function_name'		=> 'updateRemoteTables',
			'function_params'	=> base64_encode(serialize($_request))
		);
		
		$time_start = microtime(true);
		
		$webservices_url = "https://www.apps24.com/srvdispatcher.php?wsdl";
		$yp_update_data = send_WS_Request($webservices_url, $ws_request);
		if(is_array($yp_update_data) && count($yp_update_data)>0) {
			//echo '<pre>', print_r($yp_update_data), '</pre>';
			$data = $yp_update_data['data'];
			@mysql_query("SET NAMES 'utf8';") or die(mysql_error());
			foreach ($data as $table_name => $table_rows) {
				foreach ($table_rows as $i=>$table_values) {
					if($table_name == "yp_businesses") {
						$table_values['friendly_name'] = makeFriendlyName($table_values['name']);
					}
					mysql_insert($table_name, $table_values);
				}
			}
			
		}
		$time_end = microtime(true);
		$time = $time_end - $time_start;
		
		if(isset($_REQUEST['debug'])) echo "<br/>Webservices update took: <strong>$time seconds</strong>";
		
		$log = array(
				"categories" 		=> $module_yp_categs,
				"time_spent"		=> "$time seconds",
				"last_updated"		=> date("Y-m-d H:i:s")
			);
			
		$f = fopen($yp_cache_file, "w");
		if($f) {
			$log_data = serialize($log);
			fwrite($f, $log_data, strlen($log_data));
			fclose($f);
		}
		
	}
	else {
		if(isset($_REQUEST['debug'])) {
			echo "<br/>No module params";
		}
	}
}
else {
	if(isset($_REQUEST['debug'])) {
		echo "<br/>The data is new";
		$log = unserialize(file_get_contents($yp_cache_file));
		echo '<pre>', print_r($log), '</pre>';
	}
}
?>