<?php
namespace App\Models;

use Core\Db;
use Core\Model;

/**
 * 逐页 SEO 设置模型
 * 表 page_seo 以 page_key（home/products/product_category/news/cases/about/contact）为主键，
 * 后台可逐页维护 标题/描述/关键词/Open Graph/规范链接/收录开关。
 */
class PageSeo extends Model
{
    protected $table = 'page_seo';
    protected $primaryKey = 'id';

    /** 按 page_key 取单条 */
    public function getByKey(string $key): ?array
    {
        $row = Db::query("SELECT * FROM {$this->table} WHERE page_key = ?", [$key])->fetch();
        return $row ?: null;
    }

    /** 全部以 page_key 为索引返回 */
    public function allIndexed(): array
    {
        $rows = Db::query("SELECT * FROM {$this->table} ORDER BY sort ASC, id ASC")->fetchAll();
        $out = [];
        foreach ($rows as $r) {
            $out[$r['page_key']] = $r;
        }
        return $out;
    }

    /** 存在则更新，不存在则插入 */
    public function saveRow(string $key, array $data): void
    {
        $exists = Db::query("SELECT 1 FROM {$this->table} WHERE page_key = ?", [$key])->fetch();
        if ($exists) {
            $sets = [];
            $params = [];
            foreach ($data as $k => $v) {
                $sets[] = "`{$k}` = ?";
                $params[] = $v;
            }
            $params[] = $key;
            Db::query("UPDATE {$this->table} SET " . implode(', ', $sets) . " WHERE page_key = ?", $params);
        } else {
            $cols = array_keys($data);
            $ph = array_fill(0, count($cols), '?');
            Db::query(
                "INSERT INTO {$this->table} (`page_key`, `" . implode('`,`', $cols) . "`) VALUES (?, " . implode(',', $ph) . ")",
                array_merge([$key], array_values($data))
            );
        }
    }
}
