<?php
/// file: app/Controllers/Admin/SeoAdminController.php

declare(strict_types=1);

namespace App\Controllers\Admin;

use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Request;
use App\Core\Response;
use App\Models\SeoMeta;

final class SeoAdminController extends Controller
{
    public function index(Request $request): Response
    {
        $rows = SeoMeta::allRows();
        $editKey = $request->input('edit');
        $editRow = null;
        if (is_string($editKey) && $editKey !== '') {
            $editRow = SeoMeta::forPage($editKey);
        }
        $html = $this->adminView('admin/seo/index', ['rows' => $rows, 'editRow' => $editRow]);
        return Response::html($html);
    }

    public function save(Request $request): Response
    {
        if (! Csrf::verify($request->input('_csrf'))) {
            return $this->redirect(url('/admin/seo'));
        }
        $pageKey = trim((string) $request->input('page_key', ''));
        if ($pageKey === '') {
            return $this->redirect(url('/admin/seo'));
        }
        SeoMeta::upsert($pageKey, [
            'title' => trim((string) $request->input('title', '')),
            'description' => trim((string) $request->input('description', '')),
            'og_title' => trim((string) $request->input('og_title', '')),
            'og_description' => trim((string) $request->input('og_description', '')),
            'og_image' => trim((string) $request->input('og_image', '')),
            'robots' => trim((string) $request->input('robots', 'index,follow')),
            'structured_json' => trim((string) $request->input('structured_json', '')) ?: null,
        ]);
        return $this->redirect(url('/admin/seo'));
    }
}
