<?php

namespace WordpressModels;

class Meta
{
    /**
     * @return array{array{meta_key: string, meta_value: string}}
     */
    public static function getAllMetaKeysAndValuesLike(string $likeKey, string $likeValue, int $postId, string $relation = 'OR', ?string $postType = null): array
    {
        global $wpdb;

        if (!$likeKey && !$likeValue) {
            return [];
        }
        // force correct relation
        $relation = in_array(strtoupper($relation), ['AND', 'OR']) ? $relation : 'OR';

        $q = "SELECT pm.meta_key, pm.meta_value FROM `$wpdb->postmeta` pm
            JOIN `$wpdb->posts` p ON p.ID = pm.post_id
            WHERE p.ID = %d";

        $clauses = [];
        $params = [$postId];
        if ($likeKey) {
            $clauses[] = "pm.meta_key LIKE %s";
            $params[] = $likeKey;
        }
        if ($likeValue) {
            $clauses[] = "pm.meta_value LIKE %s";
            $params[] = $likeValue;
        }
        if ($postType) {
            $clauses[] = "p.post_type = %s";
            $params[] = $postType;
        }
        if ($clauses) {
            $q .= ' AND ' . join(" $relation ", $clauses);
        }

        return $wpdb->get_results($wpdb->prepare("$q;", ...$params), ARRAY_N);
    }

}
