<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SeoMeta;
use App\Models\AuditLog;
use Illuminate\Http\Request;

class SEOAdminController extends Controller
{
    public function index()
    {
        $seoPages = SeoMeta::orderBy('sitemap_priority', 'desc')->get();
        return view('admin.seo.index', compact('seoPages'));
    }

    public function update(Request $request, string $id)
    {
        $seo = SeoMeta::findOrFail($id);

        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string|max:500',
            'keywords' => 'nullable|string|max:500',
            'og_title' => 'nullable|string|max:255',
            'og_description' => 'nullable|string|max:500',
            'og_image' => 'nullable|url',
            'sitemap_priority' => 'required|numeric|min:0.1|max:1.0',
            'robots_index' => 'nullable|boolean',
        ]);

        $seo->update(array_merge($validated, [
            'robots_index' => $request->boolean('robots_index'),
        ]));

        AuditLog::record('admin_updated_seo_meta', $seo);

        return back()->with('success', "SEO settings for {$seo->url_path} updated.");
    }

    public function sitemapXml()
    {
        $pages = SeoMeta::where('robots_index', true)->orderBy('sitemap_priority', 'desc')->get();
        
        return response()->view('public.sitemap', compact('pages'))
            ->header('Content-Type', 'application/xml');
    }

    public function robotsTxt()
    {
        $content = "User-agent: *\nAllow: /\nDisallow: /admin/\nDisallow: /customer/\nDisallow: /login\nDisallow: /register\n\nSitemap: " . url('/sitemap.xml') . "\n";
        return response($content)->header('Content-Type', 'text/plain');
    }
}
