<?php
if (!defined('ABSPATH')) exit;

function asana_automator_task_passes_filters(array $task, array $filters): bool {
    $pass = true;

    // 1. Unassigned only
    if (!empty($filters['unassigned_only']) && !empty($task['assignee'])) {
        return false;
    }

    // 2. Due in X days or less
    if (!empty($filters['due_in_days'])) {
        $due_date = strtotime($task['due_on'] ?? '');
        $now = strtotime(date('Y-m-d'));
        $max_days = intval($filters['due_in_days']);
        if (!$due_date || ($due_date - $now) / 86400 > $max_days) {
            return false;
        }
    }

    // 3. Must include tag
    if (!empty($filters['required_tag'])) {
        $tags = $task['tags'] ?? [];
        $tag_gids = array_column($tags, 'gid');
        if (!in_array($filters['required_tag'], $tag_gids)) {
            return false;
        }
    }

    // 4. Custom field match
    if (!empty($filters['field_match_gid']) && isset($filters['field_match_value'])) {
        foreach ($task['custom_fields'] ?? [] as $field) {
            if ($field['gid'] === $filters['field_match_gid']) {
                $value = $field['enum_value']['gid'] ?? $field['text_value'] ?? null;
                if ($value != $filters['field_match_value']) {
                    return false;
                }
            }
        }
    }

    return $pass;
}
