<?php
if (!defined('ABSPATH')) exit;
if (!current_user_can('manage_options')) wp_die('Unauthorized');

require_once plugin_dir_path(__DIR__) . 'global-field-map-helpers.php';

$accounts = afb_gf_get_accounts();
?>
<div class="wrap">
  <h1>Asana Global Field Map</h1>
  <p class="description" style="max-width: 920px; margin-top: 8px;">
    Select an Asana account to open its dedicated mapping editor. Each account opens on its own URL and manages workspace/portfolio mapping in one place.
  </p>

  <?php if (empty($accounts)): ?>
    <div class="notice notice-warning" style="max-width: 920px; margin-top: 12px;">
      <p>No Asana accounts were found. Add an account first in Asana Accounts.</p>
    </div>
  <?php else: ?>
    <table class="widefat striped" style="max-width: 1100px; margin-top: 12px;">
      <thead>
        <tr>
          <th style="width: 90px;">ID</th>
          <th>Account</th>
          <th style="width: 260px;">Default Portfolio</th>
          <th style="width: 120px;">Status</th>
          <th style="width: 180px;">Action</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($accounts as $account): ?>
          <?php
            $edit_url = add_query_arg([
              'page' => 'afb-global-field-map-edit',
              'pat_id' => (int)$account['id'],
              'target' => 'workspace',
            ], admin_url('admin.php'));
          ?>
          <tr>
            <td><?= esc_html((string)$account['id']) ?></td>
            <td>
              <strong><?= esc_html($account['label'] !== '' ? $account['label'] : ('Account #' . (int)$account['id'])) ?></strong>
            </td>
            <td><?= esc_html($account['portfolio_gid'] !== '' ? $account['portfolio_gid'] : '—') ?></td>
            <td><?= $account['active'] ? '<span style="color:#166534;">Active</span>' : '<span style="color:#6b7280;">Inactive</span>' ?></td>
            <td><a class="button button-primary" href="<?= esc_url($edit_url) ?>">Manage Mapping</a></td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  <?php endif; ?>
</div>
