<?php

namespace Main\Controllers;

use Main\Core\Controller;
use Main\Services\SitemapService;

class SitemapController extends Controller
{
    public function index()
    {
				if (settings('lastSitemapGeneration') < date("Y-m-d H:i:s", strtotime("-1 day"))) {
					SitemapService::generate();
					
					$update = db()->prepare("UPDATE Settings SET value = ? WHERE name = ?");
					$update->execute(array(datetime(), 'lastSitemapGeneration'));
				}
				
        header("Content-type: text/xml");
	      die(file_get_contents('sitemaps/sitemap-index.xml'));
    }
	
		public function show($index)
		{
			// Check if the index is a positive integer
			if (!is_numeric($index) || $index < 0 || intval($index) != $index) abort_404();
			
			$filepath = "sitemaps/sitemap-$index.xml";
			
			// Ensure the file exists to avoid errors
			if (!file_exists($filepath)) abort_404();
			
			header("Content-type: text/xml");
			die(file_get_contents($filepath));
		}
}