<?php
/**
 * SITEMAP XML GENERATOR
 * --------------------------------------------------------
 *
 * This file is used to create a useable sitemap for SEO.
 */
require_once("inc/config.php");

require_once('php_header.php');

$cms = new WebCMS();
$simple_products = new Simple_Products();
$urls = array();
$content_ids = array();

/**
 * Setup main home page
 */
$urls[] = array(
  'loc'=>PATH_MAINSITE,
  'lastmod'=>date("Y-m-d"),
  'changefreq'=>'weekly',
  'priority'=>'1.0'
  );

$catalogue_url = PATH_MAINSITE.'gallery/';

/**
 * Setup sections of the website
 */
if($cms->getRecords(SECTION_TABLE, null, 'sortOrder')) {
  $sections = $cms->getResult();

  foreach ($sections as $section) {
  	if($section['contentID'] > 0 && $cms->getRecords(CONTENTS_TABLE, array('contentID='=>$section['contentID']))) {
      $content = $cms->getResult(0);
      $content_ids[$content['contentID']] = $content['url'];  // Used later to check that a content page hasn't already been added
      $timestamp = ($content['timestamp'] > 0) ? $content['timestamp'] : time();
      if($content['url'] !== 'home') {
        $urls[] = array(
          'loc'=>PATH_MAINSITE.$content['url'],
          'lastmod'=>date("Y-m-d", $timestamp),
          'changefreq'=>'monthly',
          'priority'=>'0.9'
          );
      }
  	}
  }
}


/**
 * SIMPLE PRODUCTS
 */


/**
 * Setup categories
 */
$categoriesList =$simple_products->getCategories();
$parents = $categoriesList[0];

foreach ($parents as $parent) {
	$pid = $parent['categoryID'];

	$lastmod = date("Y-m-d");
	if($simple_products->getProducts(array('categoryID = '=>$parent['categoryID']), '`modified` DESC', '1')) {
	  $presult = $simple_products->getResult(0);
	  $lastmod = date("Y-m-d", $presult['modified']);
	}

  $urls[] = array(
    'loc'=>$catalogue_url.site_url_friendly($parent['category']),
    'lastmod'=>$lastmod,
    'changefreq'=>'daily',
    'priority'=>'0.9'
    );


	if(array_key_exists($pid, $categoriesList)) {
  	foreach ($categoriesList[$pid] as $cat) {
  	  $url = $catalogue_url;
  	  if($cat['parentID'] == $pid) {
  	    $url .= site_url_friendly($parent['category']).'/';
  	  }
    	$lastmod = date("Y-m-d");
    	if($simple_products->getProducts(array('categoryID = '=>$cat['categoryID']), '`modified` DESC', '1')) {
    	  $presult = $simple_products->getResult(0);
    	  $lastmod = date("Y-m-d", $presult['modified']);
    	}

      $urls[] = array(
        'loc'=>$url.site_url_friendly($cat['category']),
        'lastmod'=>$lastmod,
        'changefreq'=>'daily',
        'priority'=>'0.8'
        );
  	}
	}
}


/**
 * Setup artist pages
 */
if($app->getRecords(ARTISTS_TABLE, null, '`modified` DESC')) {
  $result = $app->getResult(null, 0, true);

  foreach ($result as $a) {
	  $timestamp = ($a['modified'] > 0) ? $a['modified'] : time();
    $urls[] = array(
      'loc'=>PATH_MAINSITE.'artists/'.$a['url'],
      'lastmod'=>date("Y-m-d", $timestamp),
      'changefreq'=>'monthly',
      'priority'=>'0.8'
      );
    $urls[] = array(
      'loc'=>PATH_MAINSITE.'artists/'.$a['url'].'/artwork',
      'lastmod'=>date("Y-m-d", $timestamp),
      'changefreq'=>'monthly',
      'priority'=>'0.8'
      );
  }
}


/**
 * Setup product pages
 */
if($simple_products->getProducts(null, '`modified` DESC')) {
  $result = $simple_products->getResult();

  foreach ($result as $product) {
	  $timestamp = ($product['modified'] > 0) ? $product['modified'] : time();
    $urls[] = array(
      'loc'=>$catalogue_url.'product/'.$product['url'],
      'lastmod'=>date("Y-m-d", $timestamp),
      'changefreq'=>'monthly',
      'priority'=>'0.7'
      );
  }
}



/**
 * Setup content pages associated with website sections
 */
if($cms->getRecords(CONTENTS_TABLE, array('sectionID!='=>0, 'system='=>0))) {
  $result = $cms->getResult();

  foreach ($result as $content) {
  	if(!array_key_exists($content['contentID'], $content_ids)
      && $content['sitemap'] > 0
      && $cms->checkAccess($content['viewAccess'], ACCESS_NEWUSER)
      ) {
  	  $timestamp = ($content['timestamp'] > 0) ? $content['timestamp'] : time();
      $urls[] = array(
        'loc'=>PATH_MAINSITE.$content['url'],
        'lastmod'=>date("Y-m-d", $timestamp),
        'changefreq'=>'monthly',
        'priority'=>'0.6'
        );
  	}
  }
}


/**
 * Setup orphaned content pages
 */
if($cms->getRecords(CONTENTS_TABLE, array('sectionID='=>0, 'system='=>0))) {
  $result = $cms->getResult();

  foreach ($result as $content) {
  	if(!array_key_exists($content['contentID'], $content_ids)
      && $content['sitemap'] > 0
      && $cms->checkAccess($content['viewAccess'], ACCESS_NEWUSER)
      ) {
  	  $timestamp = ($content['timestamp'] > 0) ? $content['timestamp'] : time();
      $urls[] = array(
        'loc'=>PATH_MAINSITE.$content['url'],
        'lastmod'=>date("Y-m-d", $timestamp),
        'changefreq'=>'monthly',
        'priority'=>'0.5'
        );
  	}
  }
}

$output = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
$output .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n";
foreach ($urls as $url) {
  $output .= '    <url>'."\n";
  $output .= '      <loc>'.$url['loc'].'</loc>'."\n";
  $output .= '      <lastmod>'.$url['lastmod'].'</lastmod>'."\n";
  $output .= '      <changefreq>'.$url['changefreq'].'</changefreq>'."\n";
  $output .= '      <priority>'.$url['priority'].'</priority>'."\n";
  $output .= '    </url>'."\n";
}
$output .= '</urlset>';

$params = array(
'table'=>'sitemap_access',
'idName'=>'id',
'timestamp'=>date('Y-m-d H:i:s'),
'useragent'=>$_SERVER['HTTP_USER_AGENT'],
'remote'=>$_SERVER['REMOTE_ADDR'],
'total'=>sizeof($urls),
/*'sitemap'=>$output  Removed to reduce DB load  */
);
$app->putRecord('Custom', $params);

header('Content-Type: text/xml');
echo $output;
?>