<?php

namespace App\Http\Controllers\Admin\Settings\Pages;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\PageSeoRequest;
use App\Models\Page;

class SeoController extends Controller
{
    public function index(Page $page)
    {
        adminUserHasPermission(permission: 'edit');

        $buttons = [
            [
                'label' => __('Back'),
                'icon' => 'ph ph-arrow-left',
                'type' => 'link',
                'link' => route('admin.settings.pages.edit', $page),
            ],
            [
                'label' => __('Pages'),
                'icon' => 'ph ph-list',
                'type' => 'link',
                'link' => route('admin.settings.pages.index'),
            ],
        ];

        $page = $page->load('seo');

        return view('admin.pages.settings.manage-pages.seo', compact('page', 'buttons'));
    }

    public function store(PageSeoRequest $request, Page $page)
    {
        adminUserHasPermission(permission: 'edit');

        $page->seo()->updateOrCreate([
            'model_id' => $page->id,
            'model_type' => get_class($page),
        ], [
            'title' => $request->title,
            'image' => $request->image,
            'description' => $request->description,
            'canonical_url' => $request->canonical_url,
            'keywords' => $request->keywords,
        ]);

        return response()->json(['message' => __('SEO updated successfully'), 'reload' => true]);
    }
}
