<?php
class SitemapItem extends SeoAppModel {

	var $useTable = 'seo_sitemap_items';

# ~ Get all sitemap items- - - - - - - - - - - - - - - - - - - - - - - - - - - #
	public function getAll($additionalOptions = array()) {
		#!!TODO: Implement caching!!!
		$options = array(
			'fields' => array('loc', 'changefreq', 'priority', 'lastmod', 'modtime'),
		);

		$options = array_merge($options, $additionalOptions);

		# Get from database and store in cache
		$items = $this->find('all', $options);
		return $items;
	}

# ~ Store items- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	public function storeItems($items) {
		$this->begin();

		try {
			# Delete all from database
			$this->deleteAll(array('1 = 1'));

			# Update autoincrement column
			$this->query('ALTER TABLE `' . $this->useTable . '` AUTO_INCREMENT=1');

			# Save all
			$this->saveMany($items, array(
				'callbacks' => false,
				'validate' => false
			));

			# Commit
			$this->commit();

			# Clear cache
			$this->clearCache();

			return true;
		} catch(Exception $e) {
			CakeLog::write('error', $e->getMessage());
			$this->rollback();
			return false;
		}
		return false;
	}

# ~ Invalidate current sitemap items - - - - - - - - - - - - - - - - - - - - - #
	public function invalidateSitemap() {
		# Delete all from database
		$this->deleteAll(array('1 = 1'));
		$this->clearCache();
		return true;
	}


# ~ Clear cache- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	public function clearCache($cache = null) {
		Cache::delete('Seo.Sitemap.Items');
		Cache::delete('Seo.Sitemap.XML');
	}

}
