<?php
// includes/functions/resolvers/field-resolver.php
if (!defined('ABSPATH')) exit;

/**
 * Cache project custom fields briefly to reduce API calls.
 */
function afb_get_project_fields_cached(string $project_id, string $pat, int $ttl = 300) : array {
    $key = 'afb_cf_' . md5($project_id);
    $cached = get_transient($key);
    if (is_array($cached)) return $cached;

    $settings = afb_get_project_fields($project_id, $pat); // [ ['custom_field'=>[...]], ... ]
    if (is_array($settings)) {
        set_transient($key, $settings, $ttl);
        return $settings;
    }
    return [];
}

/**
 * Detect /pattern/flags and split it.
 */
function afb_try_parse_regex(string $raw) : array {
    $raw = trim($raw);
    if ($raw === '' || $raw[0] !== '/') return ['ok' => false];
    $last = strrpos($raw, '/');
    if ($last === 0) return ['ok' => false];
    $pattern = substr($raw, 0, $last + 1); // includes trailing slash
    $flags   = substr($raw, $last + 1);
    if ($pattern === '/' || $pattern === '') return ['ok' => false];
    return ['ok' => true, 'pattern' => $pattern, 'flags' => $flags];
}

/**
 * Generic resolver: accepts GID, Name, or /regex/flags.
 * Returns '' (or $fallback) when not found.
 */
function afb_resolve_cf_gid(string $project_id, string $pat, string $setting, string $fallback = '') : string {
    $setting = trim($setting);
    if ($setting === '') return $fallback;

    // Direct GID
    if (ctype_digit($setting)) return $setting;

    $settings = afb_get_project_fields_cached($project_id, $pat);
    if (!$settings) return $fallback;

    // Regex name match
    $rx = afb_try_parse_regex($setting);
    if ($rx['ok']) {
        $regex = $rx['pattern'] . $rx['flags']; // e.g. /job\s*number/i
        foreach ($settings as $s) {
            $f = $s['custom_field'] ?? null; if (!$f) continue;
            $name = (string) ($f['name'] ?? '');
            if (@preg_match($regex, $name) && preg_match($regex, $name)) {
                return (string) $f['gid'];
            }
        }
        return $fallback;
    }

    // Exact case-insensitive name
    $needle = mb_strtolower($setting);
    foreach ($settings as $s) {
        $f = $s['custom_field'] ?? null; if (!$f) continue;
        if (mb_strtolower((string)$f['name']) === $needle) {
            return (string) $f['gid'];
        }
    }

    // Contains (case-insensitive)
    foreach ($settings as $s) {
        $f = $s['custom_field'] ?? null; if (!$f) continue;
        $name = (string) ($f['name'] ?? '');
        if (mb_stripos($name, $setting) !== false) {
            return (string) $f['gid'];
        }
    }

    return $fallback;
}

/* Specific helpers wired to your option names.
   All accept GID / Name / Regex values. */

function afb_resolve_job_number_field_gid(string $project_id, string $pat, string $fallback = '') : string {
    $opt = (string) get_option('afb_job_number_field_gid', '');
    return afb_resolve_cf_gid($project_id, $pat, $opt, $fallback);
}

function afb_resolve_client_gateway_field_gid(string $project_id, string $pat, string $fallback = '') : string {
    $opt = (string) get_option('afb_gateway_cf', '');
    return afb_resolve_cf_gid($project_id, $pat, $opt, $fallback);
}

function afb_resolve_create_client_gateway_field_gid(string $project_id, string $pat, string $fallback = '') : string {
    $opt = (string) get_option('afb_gateway_create_cf', '');
    return afb_resolve_cf_gid($project_id, $pat, $opt, $fallback);
}
