<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SeoPage;
use Illuminate\Http\Request;

class SeoPageController extends Controller
{
    public function index()
    {
        $seoPages = SeoPage::orderBy('page_url')->paginate(20);
        return view('admin.seo-pages.index', compact('seoPages'));
    }

    public function create()
    {
        return view('admin.seo-pages.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'page_url'        => 'required|string|max:255|unique:seo_pages',
            'title'           => 'nullable|string|max:255',
            'meta_title'      => 'nullable|string|max:255',
            'meta_description'=> 'nullable|string',
            'meta_keywords'   => 'nullable|string',
            'og_title'        => 'nullable|string|max:255',
            'og_description'  => 'nullable|string',
            'og_image'        => 'nullable|string|max:255',
            'canonical_url'   => 'nullable|string|max:255',
            'is_active'       => 'nullable|boolean',
        ]);

        $data['is_active'] = $request->boolean('is_active', true);

        SeoPage::create($data);
        return redirect()->route('admin.seo-pages.index')->with('success', 'SEO page created successfully.');
    }

    public function edit(SeoPage $seoPage)
    {
        return view('admin.seo-pages.edit', compact('seoPage'));
    }

    public function update(Request $request, SeoPage $seoPage)
    {
        $data = $request->validate([
            'page_url'        => 'required|string|max:255|unique:seo_pages,page_url,' . $seoPage->id,
            'title'           => 'nullable|string|max:255',
            'meta_title'      => 'nullable|string|max:255',
            'meta_description'=> 'nullable|string',
            'meta_keywords'   => 'nullable|string',
            'og_title'        => 'nullable|string|max:255',
            'og_description'  => 'nullable|string',
            'og_image'        => 'nullable|string|max:255',
            'canonical_url'   => 'nullable|string|max:255',
            'is_active'       => 'nullable|boolean',
        ]);

        $data['is_active'] = $request->boolean('is_active', true);

        $seoPage->update($data);
        return redirect()->route('admin.seo-pages.index')->with('success', 'SEO page updated successfully.');
    }

    public function destroy(SeoPage $seoPage)
    {
        $seoPage->delete();
        return redirect()->route('admin.seo-pages.index')->with('success', 'SEO page deleted successfully.');
    }
}
