<?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
            LEFT JOIN `$wpdb->posts` p ON p.ID = pm.post_id
            WHERE ";

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

        if ($postType) {
            $q .= "AND p.post_type = %s";
            $params[] = $postType;
        }

        if ($postId) {
            $q .= "AND p.ID = %s";
            $params[] = $postId;
        }

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

}
