<?php

namespace App\Modules\Pilkades\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Modules\Pilkades\Models\Desa;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;

class SitemapController extends Controller
{
    public function index(): Response
    {
        $xml = Cache::remember('sitemap.xml', now()->addHours(6), function () {
            $desaList = Desa::with('kecamatan.kabupaten')
                ->where('status', 'published')
                ->get();

            $urls = $desaList->map(function (Desa $desa) {
                $loc = url("/{$desa->kecamatan->kabupaten->slug}/{$desa->kecamatan->slug}/{$desa->slug}");

                return "<url><loc>{$loc}</loc><lastmod>{$desa->updated_at->toAtomString()}</lastmod></url>";
            })->implode('');

            return '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'.$urls.'</urlset>';
        });

        return response($xml)->header('Content-Type', 'application/xml');
    }
}
