<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Setting;
use Illuminate\Support\Facades\Artisan;

class SitemapController extends Controller
{
    /**
     * Get the sitemap generation status
     */
    public function status()
    {
        $lastGenerated = Setting::where('key', 'sitemap_last_generated')->value('value');
        $totalLinks = Setting::where('key', 'sitemap_count')->value('value');

        // Based on where the frontend usually runs, provide the URL
        $sitemapUrl = rtrim(config('app.url') ?? 'http://127.0.0.1:8000', '/') . '/sitemap.xml';

        return response()->json([
            'last_generated' => $lastGenerated ?: 'Never',
            'total_links' => $totalLinks ?: 0,
            'sitemap_url' => $sitemapUrl
        ]);
    }

    /**
     * Generate the sitemap immediately
     */
    public function generate(Request $request)
    {
        // Call the artisan command directly
        Artisan::call('sitemap:generate');

        // Fetch updated data
        $lastGenerated = Setting::where('key', 'sitemap_last_generated')->value('value');
        $totalLinks = Setting::where('key', 'sitemap_count')->value('value');
        $sitemapUrl = rtrim(config('app.url') ?? 'http://127.0.0.1:8000', '/') . '/sitemap.xml';

        return response()->json([
            'message' => 'Sitemap generated successfully.',
            'last_generated' => $lastGenerated,
            'total_links' => $totalLinks,
            'sitemap_url' => $sitemapUrl
        ]);
    }
}
