<?php
/// file: app/Models/SeoMeta.php

declare(strict_types=1);

namespace App\Models;

use App\Core\Database;
use PDO;

final class SeoMeta
{
    /** @return array<string, mixed>|null */
    public static function forPage(string $pageKey): ?array
    {
        $st = Database::pdo()->prepare('SELECT * FROM seo_meta WHERE page_key = ? LIMIT 1');
        $st->execute([$pageKey]);
        $row = $st->fetch(PDO::FETCH_ASSOC);
        return $row ?: null;
    }

    /** @return list<array<string, mixed>> */
    public static function allRows(): array
    {
        $st = Database::pdo()->query('SELECT * FROM seo_meta ORDER BY page_key ASC');
        return $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }

    public static function upsert(string $pageKey, array $data): void
    {
        $st = Database::pdo()->prepare(
            'INSERT INTO seo_meta (page_key, title, description, og_title, og_description, og_image, robots, structured_json)
             VALUES (?,?,?,?,?,?,?,?)
             ON DUPLICATE KEY UPDATE
             title=VALUES(title), description=VALUES(description), og_title=VALUES(og_title),
             og_description=VALUES(og_description), og_image=VALUES(og_image), robots=VALUES(robots), structured_json=VALUES(structured_json)'
        );
        $st->execute([
            $pageKey,
            $data['title'] ?? '',
            $data['description'] ?? '',
            $data['og_title'] ?? '',
            $data['og_description'] ?? '',
            $data['og_image'] ?? '',
            $data['robots'] ?? 'index,follow',
            $data['structured_json'] ?? null,
        ]);
    }
}
