<?php
namespace BLR\Backline\Core;

if (!defined('ABSPATH')) {
    exit;
}

final class PostQueries {
    public static function count_posts(string $post_type, array $statuses = ['publish', 'draft']): int {
        $counts = wp_count_posts($post_type);
        $total = 0;

        foreach ($statuses as $status) {
            $status = sanitize_key((string) $status);
            $total += (int) ($counts->{$status} ?? 0);
        }

        return $total;
    }

    public static function count_by_meta(string $post_type, array $meta_query, array $statuses = ['publish', 'draft']): int {
        $query = new \WP_Query([
            'post_type'      => $post_type,
            'post_status'    => $statuses,
            'fields'         => 'ids',
            'posts_per_page' => 1,
            'no_found_rows'  => false,
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Dashboard aggregate count intentionally uses indexed postmeta filters where available.
            'meta_query'     => $meta_query,
        ]);

        return (int) $query->found_posts;
    }

    public static function and_meta_query(array $clauses): array {
        $clauses = array_values(array_filter($clauses, 'is_array'));
        if (count($clauses) > 1) {
            return array_merge(['relation' => 'AND'], $clauses);
        }

        return $clauses;
    }

    public static function and_tax_query(array $clauses): array {
        $clauses = array_values(array_filter($clauses, 'is_array'));
        if (count($clauses) > 1) {
            return array_merge(['relation' => 'AND'], $clauses);
        }

        return $clauses;
    }
}
