<?php
namespace Tiamr\Utils;

use Tiamr\Meta;

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

final class Sanitizer {
    public static function sanitize_condition(string $condition): string {
        $condition = sanitize_key($condition);
        $allowed   = Meta::get_allowed_conditions();

        return in_array($condition, $allowed, true) ? $condition : Meta::CONDITION_NO_RULE;
    }

    public static function sanitize_audience_condition(string $condition): string {
        $condition = sanitize_key($condition);
        $allowed   = Meta::get_allowed_audience_conditions();

        return in_array($condition, $allowed, true) ? $condition : Meta::AUDIENCE_EVERYONE;
    }

    public static function sanitize_location_condition(string $condition): string {
        $condition = sanitize_key($condition);
        $allowed   = Meta::get_allowed_location_conditions();

        return in_array($condition, $allowed, true) ? $condition : Meta::LOCATION_EVERYWHERE;
    }

    public static function sanitize_action(string $action): string {
        $action  = sanitize_key($action);
        $allowed = array_keys(Meta::get_actions());

        return in_array($action, $allowed, true) ? $action : Meta::ACTION_SHOW;
    }

    public static function sanitize_roles($roles): array {
        if (!is_array($roles)) {
            return [];
        }

        $available_roles = wp_roles()->roles;
        $allowed_slugs   = array_keys($available_roles);
        $sanitized       = [];

        foreach ($roles as $role) {
            $role = sanitize_key((string) $role);

            if ($role && in_array($role, $allowed_slugs, true)) {
                $sanitized[] = $role;
            }
        }

        return array_values(array_unique($sanitized));
    }

    public static function sanitize_post_ids($ids, string $post_type): array {
        if (!is_array($ids)) {
            return [];
        }

        $post_type = sanitize_key($post_type);

        if (!in_array($post_type, ['page', 'post'], true)) {
            return [];
        }

        $sanitized = [];

        foreach ($ids as $id) {
            $id = absint($id);

            if (!$id) {
                continue;
            }

            $post = get_post($id);

            if (!$post || $post_type !== $post->post_type || 'trash' === $post->post_status) {
                continue;
            }

            $sanitized[] = $id;
        }

        return array_values(array_unique($sanitized));
    }
}
