<?php
// File: admin/pages/settings-global-fields.php
if (!defined('ABSPATH')) exit;
if (!current_user_can('manage_options')) wp_die('Unauthorized');

// helpers + security + asana client + the same helpers your working page uses
$__afb_gf_path = AFB_PLUGIN_DIR . 'includes/functions/globalfields/global-fields.php';
if (!file_exists($__afb_gf_path)) $__afb_gf_path = AFB_PLUGIN_DIR . 'includes/functions/global-fields.php';
require_once $__afb_gf_path; unset($__afb_gf_path);

require_once AFB_PLUGIN_DIR . 'includes/security.php';
require_once AFB_PLUGIN_DIR . 'includes/lib/asana-client.php';
// ⬇️ these two are what your working page relies on
if (!function_exists('afb_get_portfolio_projects'))  require_once AFB_PLUGIN_DIR . 'includes/functions/asana/portfolio-projects.php';
if (!function_exists('afb_get_project_fields'))      require_once AFB_PLUGIN_DIR . 'includes/functions/asana/project-fields.php';

global $wpdb;
$account_table = $wpdb->prefix . 'asana_accounts';
$accounts      = $wpdb->get_results("SELECT * FROM $account_table ORDER BY id DESC", ARRAY_A);

/* ---------- 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 = $cf['type'] ?? '';
    $name = $cf['name'] ?? $cf['gid'];
    // short type suffix for clarity
    $suffix = $t ? " • ($t)" : '';
    return $name . $suffix;
}

/* ---------- State ---------- */
$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';

/* ---------- PATs (use RAW like your working code) ---------- */
$pat_rows = [];
$raw_pat_by_id = [];
foreach ($accounts as $acct) {
    $pid = (int)$acct['id'];
    $pat_rows[] = [
        'id'            => $pid,
        'name'          => $acct['label'] ?: ('Account #'.$pid),
        'pat'           => $acct['pat'],                 // ← RAW (matches working page)
        'portfolio_gid' => trim((string)($acct['portfolio_gid'] ?? '')),
    ];
    $raw_pat_by_id[$pid] = $acct['pat'];
}
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'])) {
    // Prefer a PAT-level default portfolio, else any saved mapping for this workspace
    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 (use the SAME helpers as your working page) ---------- */
$fields_for_ui = [];
$__dbg = ['projects'=>0,'cfs'=>0,'library'=>0,'samples'=>[],'notes'=>[]];

if ($ACTIVE_PAT_TOKEN && $selected_ws_gid) {
    $dedup = [];

    if ($target_scope === 'portfolio' && $selected_pf_gid) {
        // Get projects via the helper that you know works
        $proj_items = (array) afb_get_portfolio_projects($selected_pf_gid, $ACTIVE_PAT_TOKEN);
        foreach ($proj_items as $p) {
            if (empty($p['gid'])) continue;
            $__dbg['projects']++;

            // Pull the project custom field settings exactly like your working tool
            $settings = (array) afb_get_project_fields($p['gid'], $ACTIVE_PAT_TOKEN);
            foreach ($settings as $s) {
                $cf = $s['custom_field'] ?? null;
                if (!$cf || empty($cf['gid'])) continue;

                $gid = (string)$cf['gid'];
                if (!isset($dedup[$gid])) {
                    $dedup[$gid] = [
                        'gid'  => $gid,
                        'name' => afb_cf_label($cf),
                        // we don't need more here for the picker; just a clean label
                    ];
                    $__dbg['cfs']++;
                    if (count($__dbg['samples']) < 6) $__dbg['samples'][] = $dedup[$gid]['name'];
                }
            }
        }

        // Optional fallback: workspace field library (any type)
        if (!$dedup) {
            $lib = afb_asana_items(
                afb_fetch_asana(
                    'workspaces/' . urlencode($selected_ws_gid) .
                    '/custom_fields?limit=200&opt_fields=gid,name,type',
                    $ACTIVE_PAT_TOKEN
                )
            );
            foreach ($lib as $cf) {
                if (empty($cf['gid'])) continue;
                $gid = (string)$cf['gid'];
                if (!isset($dedup[$gid])) {
                    $dedup[$gid] = [
                        'gid'  => $gid,
                        'name' => afb_cf_label($cf) . ' • (library)',
                    ];
                    $__dbg['library']++;
                    if (count($__dbg['samples']) < 6) $__dbg['samples'][] = $dedup[$gid]['name'];
                }
            }
            if (!$lib) $__dbg['notes'][] = 'Library empty or no access.';
        }
    } else {
        // Workspace selection only -> library
        $lib = afb_asana_items(
            afb_fetch_asana(
                'workspaces/' . urlencode($selected_ws_gid) .
                '/custom_fields?limit=200&opt_fields=gid,name,type',
                $ACTIVE_PAT_TOKEN
            )
        );
        foreach ($lib as $cf) {
            if (empty($cf['gid'])) continue;
            $gid = (string)$cf['gid'];
            $dedup[$gid] = ['gid'=>$gid, 'name'=>afb_cf_label($cf) . ' • (library)'];
            $__dbg['library']++;
            if (count($__dbg['samples']) < 6) $__dbg['samples'][] = $dedup[$gid]['name'];
        }
        if (!$lib) $__dbg['notes'][] = 'Workspace library empty or no access.';
    }

    $fields_for_ui = array_values($dedup);
    usort($fields_for_ui, fn($a,$b)=>strcasecmp($a['name'],$b['name']));
}

/* ---------- 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'] ?? ''));

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

        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, '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, 'email' => $email, 'updated' => time(),
            ];
            afb_set_global_field_map($map);
            add_settings_error('afb_gf', 'saved', 'Saved workspace default.', 'updated');
        }
    }

    // 🔁 Redirect to GET with the same filters so the UI shows the saved values
    $page_slug = isset($_GET['page']) ? sanitize_text_field($_GET['page']) : '';
    $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 = $map['workspaces'][$selected_ws_gid]['default'] ?? ['first_name'=>'','last_name'=>'','email'=>''];
$existing_pf      = $map['workspaces'][$selected_ws_gid]['portfolios'][$selected_pf_gid] ?? ['first_name'=>'','last_name'=>'','email'=>''];

settings_errors('afb_gf');
?>
<div class="wrap">
  <h1>Asana Text Fields Picker</h1>
  <p>Pick a PAT and workspace, then save a mapping for the workspace default or a specific portfolio override.
     When a portfolio is selected, the dropdowns list <strong>custom fields on that portfolio’s projects</strong> (deduped, any type).</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 custom fields found for the current selection. Ensure the PAT can access the portfolio’s projects.</em></p>
  <?php else: ?>
    <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) {
          $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;
        };
      ?>

      <table class="form-table" role="presentation">
        <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>
      </table>

      <p class="submit">
        <button type="submit" class="button button-primary">
          <?= $target_scope === 'portfolio' ? 'Save portfolio mapping' : 'Save workspace default' ?>
        </button>
      </p>
    </form>
  <?php endif; ?>
</div>
