<?

if (!isset($beenHereBefore)) {
	$beenHereBefore = true;
	include('core/process-request.inc');
} else {

	$siteMap = new SiteMap();

	$excludeTemplates[99]   = TRUE; // page redirects
	$excludeTemplates[100]  = TRUE; // page folder (collection) not for display
	$excludeTemplates[101]  = TRUE; // page not found
	$excludeTemplates[102]  = TRUE; // transactional
	$siteMap->setExcludeTemplates($excludeTemplates);

	//$excludePages[193]   = TRUE;
	//$excludePages[608]   = TRUE;
	//$excludePages[610]   = TRUE;
	//$siteMap->setExcludePages($excludePages);

	//$siteMap->setExcludeSecure(TRUE);
	$siteMap->setExcludeExternalRedirects(TRUE);
	//$siteMap->setExcludeIfNotOnMenu(TRUE);

	//$excludeAuthentication[1]   = TRUE; // need to be signed in to see this page
	//$siteMap->setExcludeAuthentication($excludeAuthentication);

	// include even if excluded by above values (does not override autoexcludechildren
	$includePages[26]	= TRUE; // my account
	$includePages[9]	= TRUE; // customer services
	$includePages[10]	= TRUE; // policies
	$includePages[11]	= TRUE; // our website
	$includePages[12]	= TRUE; // about rnli
	$siteMap->setIgnoreExcludePages($includePages);

	// additional pages to be included at the root level
	$extraRootPages[] = 25; // basket
	$siteMap->setExtraRootPages($extraRootPages);

	$siteMap->setAutoExcludeChildren(true); // auto exclude children of excluded pages
	//$siteMap->setIgnoreSitemapValue(TRUE);

	////////////////////////
	// get data
	////////////////////////
	$siteMapData = $siteMap->getSiteMapData();

	// debug
	//print '<pre>';
	//foreach($siteMapData as $page){
	//	print $page['formatted_url'] . "\n";
	//}
	//print_r($siteMapData);
	//print '</pre>';

	header('Content-type: text/xml');

	$http ='<?xml version="1.0" encoding="UTF-8"?>' . "\n";
	$http.='<urlset xmlns="http://www.google.com/schemas/sitemap/0.84">' . "\n\n";
	$frequency = array(1=>"always",2=>"hourly",3=>"daily",4=>"weekly",5=>"monthly",6=>"yearly",7=>"never");

	foreach($siteMapData as $page){

		if (isset($excludeTemplates[$page['template_id']]) && isset($ignoreExcludeTemplates[$page['page_id']])) {
			// exclude this option from the sitemap - should only occur when a parent page is required so
			// that child pages can be pulled into the array but when the parent page is not really a page e.g. collection templates
		} else {

			if ($page['template_id'] == 100) {
				// ignore these because they are not real pages for visiting
			} elseif ($page['template_id'] == 99) {
				// a redirection to another page on the site - which already be included else where
			} else {
				$http .="\t<url>\n";
				$http .="\t\t<loc>".$page['formatted_url']."</loc>\n";
				$http .="\t\t<lastmod>".date('Y-m-d',strtotime($page['modified']))."</lastmod>\n";
				$http .="\t\t<changefreq>".$frequency[$page['google_change_freq']]."</changefreq>\n";
				$http .="\t\t<priority>".$page['google_priority']."</priority>\n";
				$http .="\t</url>\n";
			}

			if ($page['template_id'] == 5 || $page['template_id'] == 6) {

				//////////////////////////////////////////////////////////////////////////////////////////////////////
				/// START OF PRODUCT INFO PAGES WITHIN PRODUCT PAGE  /////////////////////////////////////////////////
				//////////////////////////////////////////////////////////////////////////////////////////////////////
				$TempTemplate = new Template($page['id'], $page['version'], $page['template_id']);
				$_tCMSContent = $TempTemplate->getData();
				//////////////////////////////////////////////////////////////////////////////////////////////////////

				$_tCMSPage = new Page('',$page['id']);
				$basic_more_info = buildProdDirectory($_tCMSPage);

				$onPage = 1;
				$totalPerPage = $memoVars->get('defaultPerPage');

				$sortOrder = -1;

				if (isset($_tCMSContent['group_2']) && $_tCMSContent['group_2']!='') {
					$prodGroup = decodeProdGroup($_tCMSContent['group_2']);
				} else {
					$prodGroup[0] = 0; // nothing
					$prodGroup[1] = ''; // default
				}

				if (true) {

					$productGroup = new ProductGroupByPage($page['id'],$prodGroup[0]);
					$prodGroupArray = $productGroup->getChildChainFlatArray();
					$prodGroupArrayCount = count($prodGroupArray);

					if ($prodGroupArrayCount) {
						$totalForGroup = 0;

						$products = "select
								products.ID,
								products.FPRODNO,
								products.CONSOLID,
								proddata.WEBORDER,
								proddata.SCOST AS SCOST,
								IF(proddata.SCOST < proddata.OLDSCOST AND proddata.SCOST > 0 AND proddata.OLDSCOST > 0,1,0) as DISC,
								IF(proddata.OLDSCOST>0,proddata.OLDSCOST,proddata.SCOST) AS OLDSCOST,
								MIN(proddata.SCOST) as MINSCOST,
								MAX(proddata.SCOST) as MAXSCOST,
								MAX(IF(proddata.OLDSCOST>0,proddata.OLDSCOST,proddata.SCOST)) AS MAXOSCOST,
								MIN(IF(proddata.OLDSCOST>0,proddata.OLDSCOST,proddata.SCOST)) AS MINOSCOST,
								SUM(1) AS OPTIONS,
								IF(products.backorders=0,0,1) AS BACKORDERS,
								COUNT(DISTINCT proddata.color) AS COLOURS,
								COUNT(DISTINCT proddata.prodno) AS STYLES,
								SUM(IF(proddata.STKSTAT='P',1,0)) AS POSOPTIONS,
								IF(consolid_info.IMAGE_1LIST > 0, consolid_info.IMAGE_1LIST, IF(consolid_info.IMAGE_1 > 0, consolid_info.IMAGE_1 , IF(products.IMAGE_1 > 0, products.IMAGE_1 , 0))) AS IMAGE_1LIST,
								consolid_info.SHORTDESC,
								consolid_info.GRPDESCRIP,
								SUM(IF(IF(duedates.qtydue IS NULL,0,duedates.qtydue - duedates.qtyalloc),1,0)) AS INSTOCKOPTIONS,
								IF(duedates.qtydue IS NULL,0,duedates.qtydue - duedates.qtyalloc) AS QTYAVAIL
							FROM $mysql_database.webcat
							LEFT JOIN $mysql_database.products ON products.ID = webcat.PRODUCTID
							LEFT JOIN $mysql_database.consolid_info on products.CONSOLID = consolid_info.CONSOLID
							LEFT JOIN $mysql_database.proddata ON proddata.ID = products.ID
							LEFT JOIN $mysql_database.duedates ON proddata.desphse=duedates.desphse AND proddata.fprodno=duedates.prodno AND duedates.SKEY='0'
							";

						if ($prodGroupArrayCount>1) {
							$products .= " WHERE webcat.category IN (" . implode(",", $prodGroupArray) . ")";
						} else {
							$products .= " WHERE webcat.category = {$prodGroupArray[0]}";
	   					}

						$products .= " AND (products.enabled=1" . ($_SESSION['magicEnable']?" OR products.magic_enable=1":'') . ") AND (products.NOSEARCH=0 OR products.NOSEARCH IS NULL) AND consolid_info.CONSOLID IS NOT NULL AND proddata.ID>0";

						//$products .= " AND proddata.STKSTAT<>'P'"; // prevent POS items from being included in the extract

						$products .= " GROUP BY products.CONSOLID";

						$useField = 'numeric_2';
						if ($sortOrder == -1) {
							// determine default sort order
							$sortOrder = $sortOrder == -1 ? (isset($_tCMSContent[$useField]) ? $_tCMSContent[$useField] : $sortOrder ): $sortOrder; // default sort order
						}
						$sortOrder = $sortOrder > -1 ? $sortOrder : 0;

						$thisSortOrder = $sortOrder;
						switch ($sortOrder) {
						case 1:
							// best sellers sales rank (lower the sales rank the better i.e. 1 is highest)
							if (isset($_tCMSContent[$useField]) && $_tCMSContent[$useField]==6) {
								// sales rank becomes prodgroup order
								$products .= " ORDER BY webcat.PRIORITY";
							} else {
								$products .= " ORDER BY proddata.WEBORDER,webcat.PRIORITY";
							}
							break;
						case 2:
							// price ascending
							$products .= " ORDER BY MINSCOST ASC,webcat.PRIORITY";
							break;
						case 3:
							// price descending
							$products .= " ORDER BY MINSCOST DESC,webcat.PRIORITY";
							break;
						case 4:
							// name
							$products .= " ORDER BY consolid_info.GRPDESCRIP,webcat.PRIORITY";
							break;
						case 6:
						default:
							// prod group sort order
							$thisSortOrder = 1;
							$products .= " ORDER BY webcat.PRIORITY";
							break;
						}

						//print $products . '<br>';;
						if (!($productsResult = mysql_query($products))) {
							DisplayErrMsg(sprintf("Error getting product list (1) sitemap " . $products . " Error:%d %s",mysql_errno(), mysql_error()));
						} else {
							if (mysql_num_rows($productsResult)) {
								$childCount = mysql_num_rows($productsResult);
								if ($totalForGroup==0) {
									$totalForGroup = $childCount;
									if ($totalForGroup < ($totalPerPage+1)) {
										$totalPages = 1;
									} else {
										$totalPages = 1 + ceil(($totalForGroup-$totalPerPage) / $totalPerPage);
									}
									if ($totalForGroup>$totalPerPage) {
										for ($thisPage=2;$thisPage<=$totalPages;$thisPage++) {
											$http .="\t<url>\n";
											$http .="\t\t<loc>".getURL($_tCMSPage->getBaseUrl().($thisPage==1?'':'_'.strval($thisPage)).'.'.$_tCMSPage->getExtension())."</loc>\n";
											$http .="\t\t<lastmod>".date('Y-m-d',strtotime($page['modified']))."</lastmod>\n";
											$http .="\t\t<changefreq>".$frequency[$page['google_change_freq']]."</changefreq>\n";
											$http .="\t\t<priority>".$page['google_priority']."</priority>\n";
											$http .="\t</url>\n";
										}
									}

									while ($thisProduct = mysql_fetch_assoc($productsResult)) {
										$productURL = getURL($basic_more_info . 'info/' . prepareUrl($thisProduct['GRPDESCRIP']) . '/' . prepareUrl(str_replace('/','__',$thisProduct['CONSOLID'])) . '.html');
										$http .="\t<url>\n";
										$http .="\t\t<loc>".$productURL."</loc>\n";
										$http .="\t\t<lastmod>".date('Y-m-d',strtotime($page['modified']))."</lastmod>\n";
										$http .="\t\t<changefreq>".$frequency[$page['google_change_freq']]."</changefreq>\n";
										$http .="\t\t<priority>".$page['google_priority']."</priority>\n";
										$http .="\t</url>\n";
									}
								}
							}
						}
					}
				}
				//////////////////////////////////////////////////////////////////////////////////////////////////////
				/// END OF PRODUCT INFO PAGES WITHIN PRODUCT PAGE  ///////////////////////////////////////////////////
				//////////////////////////////////////////////////////////////////////////////////////////////////////
			}
		}
	}
	$http .="</urlset>";
	echo $http;
}
?>