<?php
namespace MMP\Sitemap\Provider;

use MMP\Maps_Marker_Pro as MMP;

class Yoast implements \WPSEO_Sitemap_Provider {
	public function handles_type($type) {
		return ($type === 'maps-marker-pro');
	}

	public function get_index_links($max_entries) {
		$db = MMP::get_instance('MMP\DB');

		if (!$this->handles_type('maps-marker-pro')) {
			return array();
		}

		$maps = $db->get_all_maps(false, array(
			'columns' => array('modified')
		));
		if (!count($maps)) {
			return array();
		}

		$index = array();
		$pages = array_chunk($maps, $max_entries);
		foreach ($pages as $key => $page) {
			$current_page = ($key === 0) ? '' : $key + 1;
			$last_mod = 0;
			foreach ($page as $map) {
				$timestamp = (new \DateTime($map->modified, new \DateTimeZone('UTC')))->getTimestamp();
				$last_mod = max($last_mod, $timestamp);
			}
			$index[] = array(
				'loc'     => \WPSEO_Sitemaps_Router::get_base_url('maps-marker-pro-sitemap' . $current_page . '.xml'),
				'lastmod' => (new \DateTime('@' . $last_mod, new \DateTimeZone('UTC')))->format(DATE_W3C)
			);
		}

		return $index;
	}

	public function get_sitemap_links($type, $max_entries, $current_page) {
		$db = MMP::get_instance('MMP\DB');
		$api = MMP::get_instance('MMP\API');

		if (!$this->handles_type('maps-marker-pro')) {
			return array();
		}

		$maps = $db->get_all_maps(false, array(
			'columns' => array('id', 'modified'),
			'limit'   => $max_entries,
			'offset'  => ($current_page - 1) * $max_entries
		));
		if (!count($maps)) {
			throw new \OutOfBoundsException('Invalid sitemap page requested');
		}

		$links = array();
		foreach ($maps as $map) {
			$links[] = array(
				'loc' => $api->link("/fullscreen/{$map->id}/"),
				'mod' => (new \DateTime($map->modified, new \DateTimeZone('UTC')))->format(DATE_W3C)
			);
		}

		return $links;
	}
}
