<?php
ini_set('memory_limit', '512M');
// Check if we have done any kind of webservices requests for records
$yp_cache_folder = dirname(__FILE__) . "/cache";
$yp_cache_file = $yp_cache_folder . "/last_ws_get_bl_" . $domain_id . ".log";
$have_yp_cache_file = false;
$need_yp_get = false;

if(!is_dir($yp_cache_folder)) {
    @mkdir($yp_cache_folder, 0755, true);
}

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;
        @unlink($yp_cache_file);
	}
}
else {
	$need_yp_get = true;
}

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


if($need_yp_get) {
	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).'\')';
			
			if(isset($_REQUEST['debugbl'])) {
				echo "<br/>$q";
			}
			
		    $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)) {
		$dir_module_id = $req_modules['bl_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);
		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_bl_categs']) && is_array($module_params['module_bl_categs']) && count($module_params['module_bl_categs']) > 0) {
		$module_bl_categs = $module_params['module_bl_categs'];
		$categs_uids = array_keys($module_bl_categs);
	
		$categs_uids_str = implode(",", $categs_uids);
		$categs_uids_str = "'" . str_replace(",", "','", $categs_uids_str) . "'";
		// We must clear old records
		
		$del_buids = array();
		$del_buids_str = "";
		$qbus = "select c.business_uid from bl_businesses_categories c where c.category_uid in ($categs_uids_str);";
		$rbus = @mysql_query($qbus);
		if($rbus && mysql_num_rows($rbus) > 0) {
			while ($row = mysql_fetch_assoc($rbus)) {
				$del_buids[] = "'" . $row['business_uid'] . "'";
			}
		}
		$del_buids_str = implode(", ", $del_buids);
		
		
		if($del_buids_str != "") {
			// Delete Locations
			$qdb = "delete from bl_businesses_locations where business_uid in ($del_buids_str);";
			$rdb = @mysql_query($qdb);
			if(isset($_REQUEST['debug'])) {
				echo "<br/>$qdb";
				if(!$rdb || mysql_affected_rows() == -1) {
					echo "<br/>ERR: " . mysql_error();
				}
			}
			
			
			$qdb = "delete from bl_businesses_locations_tr where business_uid in ($del_buids_str);";
			$rdb = @mysql_query($qdb);
			if(isset($_REQUEST['debug'])) {
				echo "<br/>$qdb";
			}
			
			// Delete Businesses
			$qdb = "delete from bl_businesses where `uid` in ($del_buids_str);";
			$rdb = @mysql_query($qdb);
			if(isset($_REQUEST['debug'])) {
				echo "<br/>$qdb";
			}
			
			$qdb = "delete from bl_businesses_tr where `uid` in ($del_buids_str);";
			$rdb = @mysql_query($qdb);
			if(isset($_REQUEST['debug'])) {
				echo "<br/>$qdb";
			}
		
		}
		
		
		
		// Delete Business-Category Relations
		$qdbc = "delete from bl_businesses_categories  where category_uid in ($categs_uids_str);";
		$rdbc = @mysql_query($qdbc);
		
		// Delete Category Aliases
		$qda = "delete from bl_categories_links where uid in ($categs_uids_str);";
		//echo "<br/><strong>$qda</strong>";
		$rda = @mysql_query($qda);
		
		$qda = "delete from bl_categories_links_tr where uid in ($categs_uids_str);";
		//echo "<br/><strong>$qda</strong>";
		$rda = @mysql_query($qda);
		
		// Delete Categories
		$qdc = "delete from bl_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'		=> 'updateRemoteBLTables',
			'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 == "bl_businesses") {
						$table_values['friendly_name'] = makeFriendlyName($table_values['name']);
					}

					if($table_name == "bl_businesses_tr") {
						$table_values['friendly_name'] = makeFriendlyName($table_values['name']);
					}

					mysql_insert($table_name, $table_values);
				}
			}

		}
		$time_end = microtime(true);
		$time = $time_end - $time_start;

		//echo "<br/>Webservices update took: <strong>$time seconds</strong>";
		
		$log = array(
				"categories" 		=> $module_bl_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);
		}
		
		//require_once(dirname(__FILE__) . "/update_ws.php");
		
		
	}
}
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>';
	}
}
?>