<?php
// asana-form-builder/admin/pages/global-fields.php
if (!defined('ABSPATH')) exit;
if (!current_user_can('manage_options')) wp_die('Unauthorized');

require_once plugin_dir_path(__DIR__) . 'asana-accounts.php';

global $wpdb;
$account_table = $wpdb->prefix . 'asana_accounts';

/* ---------- Utils ---------- */
function afb_asana_items($res) {
    if (!$res) return [];
    if (isset($res['data']) && is_array($res['data'])) return $res['data'];
    if (is_array($res)) return $res;
    return [];
}
function afb_sel($a,$b){ return selected($a,$b,false); }
function afb_cf_label($cf){
  $t = afb_cf_type(is_array($cf) ? $cf : []);
    $name = $cf['name'] ?? $cf['gid'] ?? '';
    $suffix = $t ? " • ($t)" : '';
    return $name . $suffix;
}

function afb_cf_type(array $field) {
  $type = strtolower((string)($field['type'] ?? ''));
  if ($type !== '') return $type;
  $type = strtolower((string)($field['resource_subtype'] ?? ''));
  if ($type !== '') return $type;
  return strtolower((string)($field['representation_type'] ?? ''));
}

function afb_add_field_to_index(array &$index, array $field) {
  $gid = preg_replace('/\D+/', '', (string)($field['gid'] ?? ''));
  if (!$gid) return;

  $type = afb_cf_type($field);
  // Identity and gateway values are plain text. Keep explicit non-text fields out,
  // but allow unknown type metadata because some Asana responses omit type keys.
  if ($type !== '' && $type !== 'text') return;

  $name = trim((string)($field['name'] ?? $gid));
  $index[$gid] = [
    'gid'  => $gid,
    'name' => $name,
    'type' => $type,
  ];
}

function afb_collect_workspace_custom_fields($workspace_gid, $pat, array &$dbg) {
  if (!$workspace_gid || !$pat) return [];

  $endpoint = 'workspaces/' . urlencode($workspace_gid) . '/custom_fields?limit=200&opt_fields=gid,name,type,resource_subtype';
  $rows = afb_asana_items(afb_fetch_asana($endpoint, $pat));

  $index = [];
  foreach ($rows as $row) {
    afb_add_field_to_index($index, is_array($row) ? $row : []);
  }

  $dbg['workspace_fields'] = count($rows);
  return $index;
}

function afb_collect_portfolio_custom_fields($portfolio_gid, $pat, array &$dbg) {
  if (!$portfolio_gid || !$pat) return [];

  $projects = afb_asana_items(afb_get_portfolio_projects($portfolio_gid, $pat));

  // Fallback: some workspaces return a non-standard items payload through helpers.
  if (!$projects) {
    $projects = afb_asana_items(
      afb_fetch_asana('portfolios/' . urlencode($portfolio_gid) . '/items?limit=200&opt_fields=gid,name,resource_type,resource_subtype', $pat)
    );
  }

  $index = [];
  $field_cache = [];
  $project_gids = [];
  foreach ($projects as $item) {
    $gid = preg_replace('/\D+/', '', (string)($item['gid'] ?? ''));
    if ($gid === '') {
      continue;
    }

    $resource_type = strtolower((string)($item['resource_type'] ?? ''));
    $resource_subtype = strtolower((string)($item['resource_subtype'] ?? ''));

    // Primary path: explicit projects. Fallback path: allow unknown for odd payloads.
    if ($resource_type === 'project' || $resource_subtype === 'project' || $resource_type === '') {
      $project_gids[$gid] = true;
    }
  }

  if (!$project_gids) {
    $dbg['notes'][] = 'No project IDs found in selected portfolio payload.';
  }

  foreach (array_keys($project_gids) as $project_gid) {
    $dbg['projects']++;
    $settings = afb_asana_items(afb_get_project_fields($project_gid, $pat));

    // Fallback for environments where custom_field is not expanded.
    if (!$settings) {
      $settings = afb_asana_items(
        afb_fetch_asana('projects/' . urlencode($project_gid) . '/custom_field_settings?limit=200&opt_fields=custom_field.gid,custom_field.name,custom_field.type,custom_field.resource_subtype,custom_field.representation_type,custom_field_gid', $pat)
      );
    }

    if (!$settings) {
      continue;
    }

    foreach ($settings as $setting) {
      if (!is_array($setting)) continue;
      $field = [];
      if (!empty($setting['custom_field']) && is_array($setting['custom_field'])) {
        $field = $setting['custom_field'];
      } elseif (!empty($setting['custom_field_gid'])) {
        $cf_gid = preg_replace('/\D+/', '', (string)$setting['custom_field_gid']);
        if ($cf_gid !== '') {
          if (!isset($field_cache[$cf_gid])) {
            $field_cache[$cf_gid] = afb_fetch_asana('custom_fields/' . urlencode($cf_gid) . '?opt_fields=gid,name,type,resource_subtype', $pat);
          }
          if (is_array($field_cache[$cf_gid])) {
            $field = $field_cache[$cf_gid];
          }
        }
      }
      afb_add_field_to_index($index, $field);
    }
  }

  return $index;
}

function afb_guess_identity_field_gid(array $fields_for_ui, $kind) {
  $patterns = [
    'first_name' => '/(^|\\b)(first\\s*name|forename|given\\s*name)(\\b|$)/i',
    'last_name'  => '/(^|\\b)(last\\s*name|surname|family\\s*name)(\\b|$)/i',
    'email'      => '/(^|\\b)(work\\s*)?e-?mail(\\b|$)/i',
  ];

  $pattern = $patterns[$kind] ?? null;
  if (!$pattern) return '';

  foreach ($fields_for_ui as $f) {
    if (preg_match($pattern, (string)($f['name'] ?? ''))) {
      return (string)($f['gid'] ?? '');
    }
  }
  return '';
}

/* ---------- Global map helpers (read/write mu-plugin JSON) ---------- */
function afb_get_global_field_map() {
    if (function_exists('get_global_field_map')) return get_global_field_map();
    if (function_exists('load_global_field_map')) return load_global_field_map();
    $path = WP_CONTENT_DIR . '/mu-plugins/global-field-map.json';
    if (!file_exists($path)) return [];
    $json = file_get_contents($path);
    return json_decode($json, true) ?: [];
}
function afb_set_global_field_map(array $map) {
    $path = WP_CONTENT_DIR . '/mu-plugins/global-field-map.json';
    $json = json_encode($map, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    if ($json === false) return false;
    $res = @file_put_contents($path, $json);
    if ($res === false) return false;
    @chmod($path, 0644);
    return true;
}

/* ---------- State (from GET) ---------- */
$map = afb_get_global_field_map();

$selected_pat_id   = isset($_GET['pat_id']) ? (int)$_GET['pat_id'] : 0;
$selected_ws_gid   = isset($_GET['workspace_gid']) ? preg_replace('/\D+/', '', (string)$_GET['workspace_gid']) : '';
$target_scope      = isset($_GET['target']) ? sanitize_text_field($_GET['target']) : 'workspace'; // 'workspace'|'portfolio'
$selected_pf_gid   = isset($_GET['portfolio_gid']) ? preg_replace('/\D+/', '', (string)$_GET['portfolio_gid']) : '';
$debug_mode        = isset($_GET['debug']) && $_GET['debug'] == '1';

$page_slug = sanitize_text_field((string)($_GET['page'] ?? 'afb-global-field-map'));
$view_mode = '';
if (!empty($GLOBALS['afb_global_fields_mode'])) {
  $view_mode = sanitize_text_field((string)$GLOBALS['afb_global_fields_mode']);
}
if (!in_array($view_mode, ['identity', 'gateway', 'all'], true)) {
  if ($page_slug === 'afb-identity-field-map') {
    $view_mode = 'identity';
  } elseif ($page_slug === 'afb-gateway-field-map') {
    $view_mode = 'gateway';
  } else {
    $view_mode = 'all';
  }
}

$show_identity_rows = in_array($view_mode, ['identity', 'all'], true);
$show_gateway_rows  = in_array($view_mode, ['gateway', 'all'], true);

/* ---------- PATs ---------- */
$pat_rows = [];
$raw_pat_by_id = [];
$accounts = $wpdb->get_results("SELECT * FROM $account_table ORDER BY id DESC", ARRAY_A) ?: [];
foreach ($accounts as $acct) {
    $pid = (int)$acct['id'];
    $pat_plain = isset($acct['pat']) ? (function_exists('afb_decrypt') ? afb_decrypt($acct['pat']) : $acct['pat']) : '';
    $pat_rows[] = [
        'id'            => $pid,
        'name'          => $acct['label'] ?: ('Account #'.$pid),
        'pat'           => $pat_plain,
        'portfolio_gid' => trim((string)($acct['portfolio_gid'] ?? '')),
    ];
    $raw_pat_by_id[$pid] = $pat_plain;
}
if (!$selected_pat_id && $pat_rows) $selected_pat_id = $pat_rows[0]['id'];
$active_pat = null;
foreach ($pat_rows as $row) if ($row['id'] === $selected_pat_id) { $active_pat = $row; break; }
$ACTIVE_PAT_TOKEN = $raw_pat_by_id[$selected_pat_id] ?? '';

/* ---------- Workspaces for PAT ---------- */
$workspaces = [];
if ($ACTIVE_PAT_TOKEN) {
    $wsRes = afb_fetch_asana('workspaces', $ACTIVE_PAT_TOKEN);
    foreach (afb_asana_items($wsRes) as $ws) {
        if (empty($ws['gid'])) continue;
        $workspaces[$ws['gid']] = ['gid'=>$ws['gid'], 'name'=>$ws['name'] ?? $ws['gid']];
    }
    ksort($workspaces, SORT_STRING);
    if (!$selected_ws_gid && $workspaces) $selected_ws_gid = array_keys($workspaces)[0];
}

/* ---------- Portfolios (for saving overrides) ---------- */
$portfolios = [];
if ($ACTIVE_PAT_TOKEN && $selected_ws_gid) {
    $q  = 'portfolios?limit=200&workspace=' . urlencode($selected_ws_gid) . '&opt_fields=name,gid';
    $pf = afb_asana_items(afb_fetch_asana($q, $ACTIVE_PAT_TOKEN));
    if (!$pf) {
        $q2 = 'portfolios?limit=200&workspace=' . urlencode($selected_ws_gid) . '&owner=me&opt_fields=name,gid';
        $pf = afb_asana_items(afb_fetch_asana($q2, $ACTIVE_PAT_TOKEN));
    }
    foreach ($pf as $row) if (!empty($row['gid'])) $portfolios[$row['gid']] = ['gid'=>$row['gid'], 'name'=>$row['name'] ?? $row['gid']];

    // include PAT's saved portfolio if present
    $saved_pf_gid = $active_pat['portfolio_gid'] ?? '';
    if ($saved_pf_gid && empty($portfolios[$saved_pf_gid])) {
        $one = afb_fetch_asana('portfolios/' . urlencode($saved_pf_gid) . '?opt_fields=name,gid', $ACTIVE_PAT_TOKEN);
        $one = isset($one['data']) ? $one['data'] : $one;
        if (is_array($one) && !empty($one['gid'])) $portfolios[$one['gid']] = ['gid'=>$one['gid'], 'name'=>$one['name'] ?? $one['gid']];
    }
    ksort($portfolios, SORT_STRING);
    if ($target_scope === 'portfolio' && !$selected_pf_gid && $portfolios) {
        $selected_pf_gid = array_keys($portfolios)[0];
    }
}


/* ---------- Default view when no target provided ---------- */
if (empty($_GET['target'])) {
    if (!empty($active_pat['portfolio_gid'])) {
        $target_scope = 'portfolio';
        if (!$selected_pf_gid) $selected_pf_gid = preg_replace('/\D+/', '', (string)$active_pat['portfolio_gid']);
    } else {
        $saved_for_ws = $map['workspaces'][$selected_ws_gid]['portfolios'] ?? [];
        if ($saved_for_ws) {
            $target_scope = 'portfolio';
            if (!$selected_pf_gid) {
                $keys = array_keys($saved_for_ws);
                $selected_pf_gid = (string)$keys[0];
            }
        }
    }
}


/* ---------- FIELDS (auto-discover from Asana) ---------- */
$fields_for_ui = [];
$__dbg = [
    'workspace_fields' => 0,
    'projects'         => 0,
    'cfs'              => 0,
    'library'          => 0,
    'samples'          => [],
    'notes'            => [],
];

$fields_index = [];
if ($ACTIVE_PAT_TOKEN && $selected_ws_gid) {
    $workspace_index = afb_collect_workspace_custom_fields($selected_ws_gid, $ACTIVE_PAT_TOKEN, $__dbg);
    $fields_index = array_replace($fields_index, $workspace_index);

    if ($target_scope === 'portfolio' && $selected_pf_gid) {
        $portfolio_index = afb_collect_portfolio_custom_fields($selected_pf_gid, $ACTIVE_PAT_TOKEN, $__dbg);
        $fields_index = array_replace($fields_index, $portfolio_index);
        $__dbg['library'] = count($portfolio_index);
    }
}

if (!$fields_index) {
    $__dbg['notes'][] = 'No text custom fields discovered for this workspace/portfolio with the selected PAT.';
}

$fields_for_ui = array_values($fields_index);
usort($fields_for_ui, fn($a,$b)=>strcasecmp((string)$a['name'], (string)$b['name']));
$__dbg['cfs'] = count($fields_for_ui);
if ($fields_for_ui) {
    $__dbg['samples'] = array_slice(array_map(static function($f) {
        return (string)($f['name'] ?? '') . ' [' . (string)($f['gid'] ?? '') . ']';
    }, $fields_for_ui), 0, 5);
}

/* ---------- Handle save ---------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST'
    && isset($_POST['_afb_gf_nonce'])
    && wp_verify_nonce($_POST['_afb_gf_nonce'], 'afb_gf_globalsave')) {

    $pat_id        = (int)($_POST['pat_id'] ?? 0);
    $ws_gid        = preg_replace('/\D+/', '', (string)($_POST['workspace_gid'] ?? ''));
    $target        = sanitize_text_field($_POST['target'] ?? 'workspace');
    $portfolio_gid = preg_replace('/\D+/', '', (string)($_POST['portfolio_gid'] ?? ''));

    $first = preg_replace('/\D+/', '', (string)($_POST['first_name_gid'] ?? ''));
    $last  = preg_replace('/\D+/', '', (string)($_POST['last_name_gid'] ?? ''));
    $email = preg_replace('/\D+/', '', (string)($_POST['email_gid'] ?? ''));

    $gateway_create_manual = preg_replace('/\D+/', '', (string)($_POST['gateway_create_gid'] ?? ''));
    $gateway_link_manual   = preg_replace('/\D+/', '', (string)($_POST['gateway_link_gid'] ?? ''));
    $gateway_pin_manual    = preg_replace('/\D+/', '', (string)($_POST['gateway_pin_gid'] ?? ''));

    $gateway_create_select = preg_replace('/\D+/', '', (string)($_POST['gateway_create_select_gid'] ?? ''));
    $gateway_link_select   = preg_replace('/\D+/', '', (string)($_POST['gateway_link_select_gid'] ?? ''));
    $gateway_pin_select    = preg_replace('/\D+/', '', (string)($_POST['gateway_pin_select_gid'] ?? ''));

    $gateway_create = $gateway_create_select ?: $gateway_create_manual;
    $gateway_link   = $gateway_link_select ?: $gateway_link_manual;
    $gateway_pin    = $gateway_pin_select ?: $gateway_pin_manual;

    if ($show_gateway_rows) {
      $current_gateway_create = sanitize_text_field((string) get_option('afb_client_gateway_create_field_gid', '1211304630299020'));
      $current_gateway_link   = sanitize_text_field((string) get_option('afb_client_gateway_link_field_gid', '1211304630299018'));
      $current_gateway_pin    = sanitize_text_field((string) get_option('afb_client_gateway_pin_field_gid', '1214258543781835'));

      update_option('afb_client_gateway_create_field_gid', $gateway_create ?: $current_gateway_create);
      update_option('afb_client_gateway_link_field_gid', $gateway_link ?: $current_gateway_link);
      update_option('afb_client_gateway_pin_field_gid', $gateway_pin ?: $current_gateway_pin);
    }

    if ($show_identity_rows && $ws_gid) {
        if (!isset($map['workspaces'][$ws_gid])) $map['workspaces'][$ws_gid] = [];
        $map['workspaces'][$ws_gid]['source_meta']['pat_id'] = $pat_id;

      // Keep top-level identity keys in sync so front-end prefill works
      // without requiring the separate Triage GPT mapping screen.
      $map['first_name'] = $first;
      $map['last_name']  = $last;
      $map['work_email'] = $email;
      $map['email']      = $email;

        if ($target === 'portfolio' && $portfolio_gid) {
            if (!isset($map['workspaces'][$ws_gid]['portfolios'])) $map['workspaces'][$ws_gid]['portfolios'] = [];
            $map['workspaces'][$ws_gid]['portfolios'][$portfolio_gid] = [
          'first_name' => $first, 'last_name' => $last, 'work_email' => $email, 'email' => $email,
                'projects'   => [], 'updated' => time(),
            ];
            afb_set_global_field_map($map);
            add_settings_error('afb_gf', 'saved', 'Saved portfolio override.', 'updated');
        } else {
            $map['workspaces'][$ws_gid]['default'] = [
          'first_name' => $first, 'last_name' => $last, 'work_email' => $email, 'email' => $email, 'updated' => time(),
            ];
            afb_set_global_field_map($map);
            add_settings_error('afb_gf', 'saved', 'Saved workspace default.', 'updated');
        }
        } elseif ($show_gateway_rows) {
          add_settings_error('afb_gf', 'saved_gateway', 'Saved gateway field mapping.', 'updated');
    }

    $url = add_query_arg(
        array_filter([
            'page'          => $page_slug,
            'pat_id'        => $pat_id ?: null,
            'workspace_gid' => $ws_gid ?: null,
            'target'        => $target ?: null,
            'portfolio_gid' => ($target === 'portfolio' ? $portfolio_gid : null),
        ]),
        menu_page_url($page_slug, false)
    );
    wp_safe_redirect($url);
    exit;
}


/* ---------- Existing saved mapping (if any) ---------- */
$existing_default_raw = $map['workspaces'][$selected_ws_gid]['default'] ?? [];
$existing_pf_raw      = $map['workspaces'][$selected_ws_gid]['portfolios'][$selected_pf_gid] ?? [];

$existing_default = [
  'first_name' => (string)($existing_default_raw['first_name'] ?? $map['first_name'] ?? ''),
  'last_name'  => (string)($existing_default_raw['last_name'] ?? $map['last_name'] ?? ''),
  'email'      => (string)($existing_default_raw['work_email'] ?? $existing_default_raw['email'] ?? $map['work_email'] ?? $map['email'] ?? ''),
];

$existing_pf = [
  'first_name' => (string)($existing_pf_raw['first_name'] ?? $existing_default['first_name'] ?? ''),
  'last_name'  => (string)($existing_pf_raw['last_name'] ?? $existing_default['last_name'] ?? ''),
  'email'      => (string)($existing_pf_raw['work_email'] ?? $existing_pf_raw['email'] ?? $existing_default['email'] ?? ''),
];

$suggested = [
  'first_name' => afb_guess_identity_field_gid($fields_for_ui, 'first_name'),
  'last_name'  => afb_guess_identity_field_gid($fields_for_ui, 'last_name'),
  'email'      => afb_guess_identity_field_gid($fields_for_ui, 'email'),
];

if (empty($existing_default['first_name']) && !empty($suggested['first_name'])) $existing_default['first_name'] = $suggested['first_name'];
if (empty($existing_default['last_name']) && !empty($suggested['last_name'])) $existing_default['last_name'] = $suggested['last_name'];
if (empty($existing_default['email']) && !empty($suggested['email'])) $existing_default['email'] = $suggested['email'];
if (empty($existing_pf['first_name']) && !empty($suggested['first_name'])) $existing_pf['first_name'] = $suggested['first_name'];
if (empty($existing_pf['last_name']) && !empty($suggested['last_name'])) $existing_pf['last_name'] = $suggested['last_name'];
if (empty($existing_pf['email']) && !empty($suggested['email'])) $existing_pf['email'] = $suggested['email'];

$gateway_create_gid = sanitize_text_field((string) get_option('afb_client_gateway_create_field_gid', '1211304630299020'));
$gateway_link_gid   = sanitize_text_field((string) get_option('afb_client_gateway_link_field_gid', '1211304630299018'));
$gateway_pin_gid    = sanitize_text_field((string) get_option('afb_client_gateway_pin_field_gid', '1214258543781835'));

$page_title = 'Asana Global Field Map';
$page_description = 'Pick a PAT and workspace, then save a mapping for the workspace default or a specific portfolio override. The dropdowns are pulled directly from Asana text custom fields (workspace, plus portfolio projects when selected), so you can manage linking from this screen.';
if ($view_mode === 'identity') {
    $page_title = 'Asana Identity Field Map';
    $page_description = 'Manage identity-field mapping only (first name, last name, email) using the selected PAT/workspace scope.';
} elseif ($view_mode === 'gateway') {
    $page_title = 'Asana Gateway Field Map';
    $page_description = 'Manage gateway field mapping only (Create Gateway, Gateway Link, Gateway PIN) using discovered fields for the selected scope.';
}

settings_errors('afb_gf');
?>
<div class="wrap">
  <h1><?= esc_html($page_title) ?></h1>
    <?php if ($view_mode === 'all'): ?>
    <div class="notice notice-info" style="max-width: 980px; margin-top: 10px;">
      <p>
        Prefer separate mapping pages? Use
        <a href="<?= esc_url(admin_url('admin.php?page=afb-identity-field-map')) ?>">Identity Field Map</a>
        and
        <a href="<?= esc_url(admin_url('admin.php?page=afb-gateway-field-map')) ?>">Gateway Field Map</a>
        for focused updates.
      </p>
    </div>
    <?php endif; ?>
    <p><?= esc_html($page_description) ?></p>

  <form method="get">
    <input type="hidden" name="page" value="<?= esc_attr($_GET['page'] ?? '') ?>">
    <table class="form-table" role="presentation">
      <tr>
        <th scope="row"><label for="pat_id">Asana Account (PAT)</label></th>
        <td>
          <select id="pat_id" name="pat_id" onchange="this.form.submit()">
            <?php foreach ($pat_rows as $row): ?>
              <option value="<?= esc_attr($row['id']) ?>" <?= afb_sel($selected_pat_id,$row['id']) ?>>
                <?= esc_html(($row['name'] ?: 'Account #'.$row['id']).' • ID '.$row['id']) ?>
              </option>
            <?php endforeach; ?>
          </select>
          <?php if ($active_pat): ?>
            <p class="description">All calls below use this PAT<?= !empty($active_pat['portfolio_gid']) ? ', default portfolio: ' . esc_html($active_pat['portfolio_gid']) : '' ?>.</p>
          <?php endif; ?>
        </td>
      </tr>

      <?php if ($workspaces): ?>
      <tr>
        <th scope="row"><label for="workspace_gid">Workspace</label></th>
        <td>
          <select id="workspace_gid" name="workspace_gid" onchange="this.form.submit()">
            <?php foreach ($workspaces as $ws): ?>
              <option value="<?= esc_attr($ws['gid']) ?>" <?= afb_sel($selected_ws_gid,$ws['gid']) ?>>
                <?= esc_html($ws['name'].' • '.$ws['gid']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </td>
      </tr>
      <?php endif; ?>

      <?php if ($selected_ws_gid): ?>
      <tr>
        <th scope="row"><label for="target">Save mapping for</label></th>
        <td>
          <select id="target" name="target" onchange="this.form.submit()">
            <option value="workspace" <?= afb_sel($target_scope,'workspace') ?>>Workspace default</option>
            <option value="portfolio" <?= afb_sel($target_scope,'portfolio') ?>>A specific portfolio</option>
          </select>
        </td>
      </tr>
      <?php endif; ?>

      <?php if ($selected_ws_gid && $target_scope === 'portfolio'): ?>
      <tr>
        <th scope="row"><label for="portfolio_gid">Portfolio</label></th>
        <td>
          <select id="portfolio_gid" name="portfolio_gid" onchange="this.form.submit()">
            <?php foreach ($portfolios as $pf): ?>
              <option value="<?= esc_attr($pf['gid']) ?>" <?= afb_sel($selected_pf_gid,$pf['gid']) ?>>
                <?= esc_html($pf['name'].' • '.$pf['gid']) ?>
              </option>
            <?php endforeach; ?>
          </select>
          <?php if (!$portfolios): ?>
            <p class="description">No portfolios listed for this workspace and PAT.</p>
          <?php endif; ?>
        </td>
      </tr>
      <?php endif; ?>
    </table>
  </form>

  <hr />
  <h2>Custom fields available<?= $target_scope==='portfolio' && $selected_pf_gid ? ' in this portfolio' : '' ?></h2>

  <?php if ($debug_mode): ?>
    <p><small>
      Debug → projects scanned: <?= (int)$__dbg['projects'] ?>,
      distinct fields: <?= (int)$__dbg['cfs'] ?>,
      library fallback: <?= (int)$__dbg['library'] ?>.
      <?php if ($__dbg['samples']) : ?> Samples: <?= esc_html(implode(', ', $__dbg['samples'])) ?>.<?php endif; ?>
      <?php if ($__dbg['notes']) : ?> Notes: <?= esc_html(implode(' | ', $__dbg['notes'])) ?>.<?php endif; ?>
    </small></p>
  <?php endif; ?>

  <?php if (!$fields_for_ui): ?>
    <p><em>No text custom fields were found for the current selection. Ensure the PAT can access this workspace and selected portfolio projects.</em></p>
    <p class="description">Diagnostics: workspace fields seen <?= (int)$__dbg['workspace_fields'] ?>, portfolio projects scanned <?= (int)$__dbg['projects'] ?>.</p>
    <p class="description">You can still save by entering the GIDs manually below.</p>
  <?php endif; ?>

    <form method="post">
      <?php wp_nonce_field('afb_gf_globalsave', '_afb_gf_nonce'); ?>
      <input type="hidden" name="pat_id" value="<?= esc_attr($selected_pat_id) ?>">
      <input type="hidden" name="workspace_gid" value="<?= esc_attr($selected_ws_gid) ?>">
      <input type="hidden" name="target" value="<?= esc_attr($target_scope) ?>">
      <?php if ($target_scope === 'portfolio'): ?>
        <input type="hidden" name="portfolio_gid" value="<?= esc_attr($selected_pf_gid) ?>">
      <?php endif; ?>

      <?php
        $existing = ($target_scope === 'portfolio') ? $existing_pf : $existing_default;
        $render_select = function($name, $selected) use ($fields_for_ui) {
          if (empty($fields_for_ui)) {
            return '<input type="text" id="'.$name.'" name="'.$name.'" value="'.esc_attr((string)$selected).'" class="regular-text" inputmode="numeric" pattern="[0-9]*" />';
          }
          $html = '<select id="'.$name.'" name="'.$name.'"><option value="">— Select —</option>';
          foreach ($fields_for_ui as $f) {
            $sel = ($selected === $f['gid']) ? ' selected' : '';
            $html .= '<option value="'.esc_attr($f['gid']).'"'.$sel.'>'.esc_html($f['name'].' • '.$f['gid']).'</option>';
          }
          $html .= '</select>';
          return $html;
        };

        $render_gid_picker = function($name, $selected) use ($fields_for_ui) {
          $selected = (string)$selected;
          $found = false;
          $html = '<select id="'.$name.'" name="'.$name.'">';
          $html .= '<option value="">— Select detected field (optional) —</option>';
          foreach ($fields_for_ui as $f) {
            $gid = (string)($f['gid'] ?? '');
            if ($gid === '') continue;
            $sel = ($selected === $gid) ? ' selected' : '';
            if ($sel) $found = true;
            $html .= '<option value="'.esc_attr($gid).'"'.$sel.'>'.esc_html((string)($f['name'] ?? $gid).' • '.$gid).'</option>';
          }
          if ($selected !== '' && !$found) {
            $html .= '<option value="'.esc_attr($selected).'" selected>'.esc_html('Current manual value • '.$selected).'</option>';
          }
          $html .= '</select>';
          return $html;
        };
      ?>

      <table class="form-table" role="presentation">
        <?php if ($show_identity_rows): ?>
        <tr>
          <th scope="row"><label for="first_name_gid">First name</label></th>
          <td><?= $render_select('first_name_gid', (string)($existing['first_name'] ?? '')) ?></td>
        </tr>
        <tr>
          <th scope="row"><label for="last_name_gid">Last name / Surname</label></th>
          <td><?= $render_select('last_name_gid', (string)($existing['last_name'] ?? '')) ?></td>
        </tr>
        <tr>
          <th scope="row"><label for="email_gid">Email address</label></th>
          <td><?= $render_select('email_gid', (string)($existing['email'] ?? '')) ?></td>
        </tr>
        <?php endif; ?>

        <?php if ($show_gateway_rows): ?>
        <tr>
          <th scope="row"><label for="gateway_create_select_gid">Create Client Gateway field GID</label></th>
          <td>
            <?= $render_gid_picker('gateway_create_select_gid', (string)$gateway_create_gid) ?>
            <p style="margin-top:6px;"><input type="text" id="gateway_create_gid" name="gateway_create_gid" value="<?= esc_attr((string)$gateway_create_gid) ?>" class="regular-text" inputmode="numeric" pattern="[0-9]*" placeholder="Manual GID (optional)"></p>
            <p class="description">Used by task creation/enrichment to write the Create Client Gateway link (default: 1211304630299020).</p>
          </td>
        </tr>
        <tr>
          <th scope="row"><label for="gateway_link_select_gid">Client Gateway field GID</label></th>
          <td>
            <?= $render_gid_picker('gateway_link_select_gid', (string)$gateway_link_gid) ?>
            <p style="margin-top:6px;"><input type="text" id="gateway_link_gid" name="gateway_link_gid" value="<?= esc_attr((string)$gateway_link_gid) ?>" class="regular-text" inputmode="numeric" pattern="[0-9]*" placeholder="Manual GID (optional)"></p>
            <p class="description">Used by dashboard generation and expiry helpers to read/write the final Client Gateway URL (default: 1211304630299018).</p>
          </td>
        </tr>
        <tr>
          <th scope="row"><label for="gateway_pin_select_gid">Gateway PIN field GID</label></th>
          <td>
            <?= $render_gid_picker('gateway_pin_select_gid', (string)$gateway_pin_gid) ?>
            <p style="margin-top:6px;"><input type="text" id="gateway_pin_gid" name="gateway_pin_gid" value="<?= esc_attr((string)$gateway_pin_gid) ?>" class="regular-text" inputmode="numeric" pattern="[0-9]*" placeholder="Manual GID (optional)"></p>
            <p class="description">Used to store the generated gateway PIN on the task (default: 1214258543781835). Use the custom_field gid, not the custom_field_setting gid.</p>
          </td>
        </tr>
        <?php endif; ?>
      </table>

      <p class="submit">
        <button type="submit" class="button button-primary">
          <?php if ($view_mode === 'identity'): ?>
            <?= $target_scope === 'portfolio' ? 'Save identity portfolio mapping' : 'Save identity workspace default' ?>
          <?php elseif ($view_mode === 'gateway'): ?>
            Save gateway field mapping
          <?php else: ?>
            <?= $target_scope === 'portfolio' ? 'Save portfolio mapping' : 'Save workspace default' ?>
          <?php endif; ?>
        </button>
      </p>
    </form>
</div>
