<?php
define('SABLE_SITE_DEBUGGING', false);
include(__DIR__.'/../includes/sysinit.php');
$addresses = $sableDB->getRows('select * from address');
foreach($addresses as $add)
{
	//find a postal code:
	$qry = "";
	$arr = explode(',', $add['address']);
	$found = false;
	$reg = "";
	$sub = "";
	$whr = "";
	$orc	= 0;
	$or		= "";
	$cnt	= 0;
	foreach ($arr as $pc)
	{
		$or = $orc ? ' or ' : '';
		$sb = trim($pc);
		if (!empty($sb)) $reg .= $or.'(region_name = "'.$sb.'")';
		if (!empty($sb)) $sub .= $or.'(suburb_name = "'.$sb.'")';
		if (is_numeric($pc))
		{
			$cd = sprintf('%04d', $pc);
			$qry = 'select post_id 
					from postal_data 
					where ((str_code = "'.$cd.'") and (box_code = "'.$cd.'")) ';
			$cnt++;
		}
		$orc++;
		if ($cnt)
		{
			$whr .= "and (".$reg.") or (".$sub.")";
			$qry .= $whr.' order by post_id desc limit 0,1';
			if (SABLE_SITE_DEBUGGING) SableDebug::debug($qry);
			$postid = $sableDB->getValue($qry);
			if (SABLE_SITE_DEBUGGING) SableDebug::debug($postid);
			if ($postid)
			{
				$sql = "update address set post_id = ".$postid." where address_id = ".$add['address_id'];
				if (SABLE_SITE_DEBUGGING)
				{
					SableDebug::debug($sql);
				}
				else
				{
					$res = $sableDB->updateQuery($sql);
				//if ($res) $addressId = self::getAddressIdFromCoords($lat, $lng);
				}
			}
			else
			{
				return 0;
			}
		}
	}
}