<?php
// includes/functions/globalfields/global-fields.php
if (!defined('ABSPATH')) exit;

/**
 * OPTION KEYS
 * afb_global_field_map shape:
 * [
 *   'workspaces' => [
 *     '<workspace_gid>' => [
 *       'default'   => ['first_name'=>'<gid>','last_name'=>'<gid>','email'=>'<gid>','updated'=>ts],
 *       'portfolios'=> [
 *         '<portfolio_gid>' => [
 *           'first_name'=>'<gid>','last_name'=>'<gid>','email'=>'<gid>','updated'=>ts,
 *           'projects'   => ['<project_gid>', ...]  // stored for runtime lookups
 *         ]
 *       ],
 *       'source_meta' => ['pat_id'=> (int) or null]
 *     ]
 *   ]
 * ]
 */
const AFB_GLOBAL_FIELD_MAP_OPT   = 'afb_global_field_map';
const AFB_GLOBAL_FIELD_FLAGS_OPT = 'afb_global_field_flags';

function afb_get_global_field_map(): array {
    $val = get_option(AFB_GLOBAL_FIELD_MAP_OPT, []);
    if (!is_array($val)) $val = [];
    if (!isset($val['workspaces']) || !is_array($val['workspaces'])) $val['workspaces'] = [];
    return $val;
}
function afb_set_global_field_map(array $map): bool {
    if (!isset($map['workspaces']) || !is_array($map['workspaces'])) $map['workspaces'] = [];
    return update_option(AFB_GLOBAL_FIELD_MAP_OPT, $map, false);
}
function afb_get_global_field_flags(): array {
    $val = get_option(AFB_GLOBAL_FIELD_FLAGS_OPT, []);
    return is_array($val) ? $val : [];
}
function afb_set_global_field_flags(array $flags): bool {
    return update_option(AFB_GLOBAL_FIELD_FLAGS_OPT, $flags, false);
}

/** Soft utils */
function afb_cf_index_by_gid(array $fields): array {
    $idx = [];
    foreach ($fields as $f) if (!empty($f['gid'])) $idx[(string)$f['gid']] = $f;
    return $idx;
}
function afb_cf_string_value(array $f): string {
    if (array_key_exists('text_value', $f)     && $f['text_value']     !== null) return trim((string)$f['text_value']);
    if (array_key_exists('display_value', $f)  && $f['display_value']  !== null) return trim((string)$f['display_value']);
    if (isset($f['enum_value']['name']))  return (string)$f['enum_value']['name'];
    if (!empty($f['multi_enum_values']) && is_array($f['multi_enum_values'])) {
        $names = array_filter(array_map(fn($e)=>$e['name'] ?? '', $f['multi_enum_values']));
        return implode(', ', $names);
    }
    if (array_key_exists('number_value', $f)   && $f['number_value']   !== null) return (string)$f['number_value'];
    return '';
}
function afb_task_workspace_gid(array $task): ?string {
    if (!empty($task['workspace']['gid'])) return (string)$task['workspace']['gid'];
    foreach (($task['memberships'] ?? []) as $m) {
        if (!empty($m['project']['workspace']['gid'])) return (string)$m['project']['workspace']['gid'];
    }
    if (!empty($task['projects'][0]['workspace']['gid'])) return (string)$task['projects'][0]['workspace']['gid'];
    return null;
}
/** Collect all project gids from a task */
function afb_task_project_gids(array $task): array {
    $gids = [];
    foreach (($task['projects'] ?? []) as $p) if (!empty($p['gid'])) $gids[] = (string)$p['gid'];
    foreach (($task['memberships'] ?? []) as $m) if (!empty($m['project']['gid'])) $gids[] = (string)$m['project']['gid'];
    return array_values(array_unique($gids));
}

/**
 * Resolve which mapping to use for a task:
 * 1) If any mapped portfolio for the workspace contains any of the task's projects, use that portfolio mapping
 * 2) Else use the workspace 'default' mapping (if any)
 * 3) Else no mapped gids
 */
function afb_pick_mapping_for_task(array $task, array $map): array {
    $ws_gid = afb_task_workspace_gid($task);
    if (!$ws_gid) return ['first_name'=>'','last_name'=>'','email'=>''];
    $wsMap = $map['workspaces'][$ws_gid] ?? null;
    if (!$wsMap) return ['first_name'=>'','last_name'=>'','email'=>''];

    $projGids = afb_task_project_gids($task);

    // Check portfolio mappings first
    if (!empty($wsMap['portfolios']) && is_array($wsMap['portfolios']) && $projGids) {
        foreach ($wsMap['portfolios'] as $pf_gid => $cfg) {
            $pfProjects = array_map('strval', $cfg['projects'] ?? []);
            if (!$pfProjects) continue;
            if (array_intersect($projGids, $pfProjects)) {
                return [
                    'first_name' => (string)($cfg['first_name'] ?? ''),
                    'last_name'  => (string)($cfg['last_name']  ?? ''),
                    'email'      => (string)($cfg['email']      ?? ''),
                ];
            }
        }
    }

    // Fallback to workspace default
    if (!empty($wsMap['default'])) {
        return [
            'first_name' => (string)($wsMap['default']['first_name'] ?? ''),
            'last_name'  => (string)($wsMap['default']['last_name']  ?? ''),
            'email'      => (string)($wsMap['default']['email']      ?? ''),
        ];
    }

    return ['first_name'=>'','last_name'=>'','email'=>''];
}

/** Extract submitter values by the resolved mapping, with safe fallbacks */
function afb_extract_submitter_by_map(array $task, array $map): array {
    $first = $last = $email = '';

    $gidMap    = afb_pick_mapping_for_task($task, $map);
    $field_idx = afb_cf_index_by_gid($task['custom_fields'] ?? []);

    if (!empty($gidMap['first_name']) && !empty($field_idx[$gidMap['first_name']])) $first = afb_cf_string_value($field_idx[$gidMap['first_name']]);
    if (!empty($gidMap['last_name'])  && !empty($field_idx[$gidMap['last_name'] ])) $last  = afb_cf_string_value($field_idx[$gidMap['last_name'] ]);
    if (!empty($gidMap['email'])      && !empty($field_idx[$gidMap['email']     ])) $email = afb_cf_string_value($field_idx[$gidMap['email']     ]);

    // Fallbacks (no name guessing)
    if ($email === '' && !empty($task['created_by']['email'])) $email = trim((string)$task['created_by']['email']);
    if (($first === '' || $last === '') && !empty($task['created_by']['name'])) {
        $parts = preg_split('/\s+/', trim((string)$task['created_by']['name']));
        if ($parts && count($parts) > 1) { $first = $first ?: $parts[0]; $last = $last ?: end($parts); }
        elseif ($parts) { $first = $first ?: $parts[0]; }
    }
    if ($email === '' && !empty($task['followers']) && is_array($task['followers'])) {
        foreach ($task['followers'] as $f) { if (!empty($f['email'])) { $email = trim((string)$f['email']); break; } }
    }

    return ['first_name'=>$first, 'last_name'=>$last, 'email'=>$email];
}
