<?php

namespace Models;

use Core\Model;

class Meta extends Model
{
    protected static $table = 'meta';

    public static function get($objectId, $objectType, $key)
    {
        $stmt = self::$pdo->prepare("SELECT meta_value FROM " . self::$table . " WHERE object_id = ? AND object_type = ? AND meta_key = ?");
        $stmt->execute([$objectId, $objectType, $key]);
        $result = $stmt->fetch();
        return $result ? $result['meta_value'] : null;
    }

    public static function getForObject($objectId, $objectType)
    {
        $stmt = self::$pdo->prepare("SELECT meta_key, meta_value FROM " . self::$table . " WHERE object_id = ? AND object_type = ?");
        $stmt->execute([$objectId, $objectType]);
        return $stmt->fetchAll(\PDO::FETCH_KEY_PAIR);
    }

    public static function set($objectId, $objectType, $key, $value)
    {
        $sql = "INSERT INTO " . self::$table . " (object_id, object_type, meta_key, meta_value) 
                VALUES (:id, :type, :key, :value) 
                ON CONFLICT(object_id, object_type, meta_key) DO UPDATE SET meta_value = :value";
        $stmt = self::$pdo->prepare($sql);
        return $stmt->execute([
            'id' => $objectId,
            'type' => $objectType,
            'key' => $key,
            'value' => $value
        ]);
    }
}
