<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SeoData;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class SeoController extends Controller
{
    public function index()
    {
        $seoItems = SeoData::all();
        return view('admin.seo.index', compact('seoItems'));
    }

    public function edit(SeoData $seo)
    {
        return view('admin.seo.form', compact('seo'));
    }

    public function update(Request $request, SeoData $seo)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'required|string|max:500',
            'keywords' => 'nullable|string|max:255',
            'og_image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:2048',
            'og_image_path' => 'nullable|string|max:255',
        ]);

        $seo->title = $validated['title'];
        $seo->description = $validated['description'];
        $seo->keywords = $validated['keywords'];

        if ($request->hasFile('og_image')) {
            // Delete old image only if it was a direct upload
            if ($seo->og_image_path && Str::startsWith($seo->og_image_path, 'uploads/seo/') && file_exists(public_path($seo->og_image_path))) {
                @unlink(public_path($seo->og_image_path));
            }

            $file = $request->file('og_image');
            $filename = 'og_' . $seo->page_identifier . '_' . time() . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('uploads/seo'), $filename);
            $seo->og_image_path = 'uploads/seo/' . $filename;
        } elseif ($request->filled('og_image_path')) {
            $seo->og_image_path = $request->og_image_path;
        }

        $seo->save();

        return redirect()->route('admin.seo.index')->with('success', "SEO for " . ucfirst($seo->page_identifier) . " updated successfully!");
    }
}
