<?php

namespace App\Console\Commands;

use App\Models\Episode;
use App\Models\Hentai;

use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;

class GenerateSitemap extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sitemap:generate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate the sitemap.';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $latestEpisode = Episode::latest()->first();
        $latestUpdate = Carbon::create($latestEpisode->created_at);

        $sitemap = Sitemap::create()
            ->add(Url::create('/')
                ->setLastModificationDate($latestUpdate))
            ->add(Url::create('/stats')
                ->setLastModificationDate(Carbon::now()))
            ->add(Url::create('/search')
                ->setLastModificationDate(Carbon::now()))
            ->add(Url::create('/contact')
                ->setLastModificationDate(Carbon::create('2023', '8', '1')))
            ->add(Episode::all())
            ->add(Hentai::all());
        
        $sitemap->writeToFile(public_path('sitemap.xml'));
    }
}
