<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Spatie\Sitemap\SitemapIndex;

class GenerateSitemap extends Command
{
    protected $signature = 'sitemap:generate';

    protected $description = 'Generate main sitemap index that links to all sub-sitemaps';

    public function handle(): int
    {
        $this->info('Starting main sitemap generation...');

        $sitemapIndex = SitemapIndex::create();

        // Get the base URL from config
        $baseUrl = config('app.url');

        // List of sub-sitemaps to include in the main sitemap
        $subSitemaps = [
            [
                'url' => $baseUrl.'/sitemap_static.xml',
                'lastModified' => $this->getSitemapLastModified('sitemap_static.xml'),
            ],
            [
                'url' => $baseUrl.'/sitemap_memes.xml',
                'lastModified' => $this->getSitemapLastModified('sitemap_memes.xml'),
            ],
            // Future sitemaps can be added here:
            // [
            //     'url' => $baseUrl . '/sitemap_pages.xml',
            //     'lastModified' => now(),
            // ],
        ];

        // Add each sub-sitemap to the index
        foreach ($subSitemaps as $sitemap) {
            $sitemapIndex->add($sitemap['url'], $sitemap['lastModified']);
            $this->info("Added sub-sitemap: {$sitemap['url']}");
        }

        // Save the main sitemap index
        $sitemapPath = public_path('sitemap.xml');
        $sitemapIndex->writeToFile($sitemapPath);

        $this->info('Main sitemap index generated successfully!');
        $this->info("Sitemap saved to: {$sitemapPath}");
        $this->info('Total sub-sitemaps: '.count($subSitemaps));

        return Command::SUCCESS;
    }

    /**
     * Get the last modification date of a sitemap file
     */
    private function getSitemapLastModified(string $filename): \DateTime
    {
        $filepath = public_path($filename);

        if (file_exists($filepath)) {
            return new \DateTime('@'.filemtime($filepath));
        }

        // If file doesn't exist, return current time
        return new \DateTime;
    }
}
