<?php

// task-comms/partials/layout/overview-details.php

$token = $_GET['asana_comms_token'] ?? get_query_var('asana_comms_token');
$plugin_root = dirname(__DIR__, 3);
$cache_path  = $plugin_root . '/cache/tasks-summary-' . $token . '.json';

if (!file_exists($cache_path)) {
  echo '<div class="gateway-card" style="border-color:#fee2e2;color:#dc2626;font-size:.875rem">Cache missing for task details.</div>';
  return;
}

$data         = json_decode(file_get_contents($cache_path), true);
$task         = $data['parent'] ?? [];
$fields       = $task['custom_fields'] ?? [];

$field_index = [];
foreach ($fields as $f) {
  if (!empty($f['name'])) $field_index[$f['name']] = $f;
}

$assignee    = $task['assignee']['name'] ?? 'Unassigned';
$created_at  = $task['created_at'] ?? '';
$due_date    = $task['due_on'] ?? '';
$modified    = $task['modified_at'] ?? '';
$notes       = $task['notes'] ?? '';
$project     = $task['projects'][0]['name'] ?? null;
$project_gid = preg_replace('/\D+/', '', (string)($task['projects'][0]['gid'] ?? ''));
$identity    = function_exists('afb_get_submitter_identity_from_task')
  ? afb_get_submitter_identity_from_task($task)
  : ['name' => '', 'email' => ''];

$email       = (string)($identity['email'] ?? '');
$status      = $field_index['Status (SCB)']['enum_value']['name'] ?? '';
$submitter   = trim((string)($identity['name'] ?? ''));

$section     = null;
foreach ($task['memberships'] ?? [] as $membership) {
  if (($membership['project']['name'] ?? '') === $project) {
    $section = $membership['section']['name'] ?? null;
    break;
  }
}

// Extra fields visibility can be configured via admin settings.
$legacy_skip_fields = ['First Name (SCB)', 'Last Name (SCB)', 'Email Address (SCB)', 'Status (SCB)', 'Triage Summary', 'Job Number (SCB)', 'Client Gateway (SCB)', 'Create Client Gateway (SCB)', 'Client Gateway PIN (SCB)'];
$hard_skip_fields = function_exists('afb_client_gateway_hard_skip_names')
  ? afb_client_gateway_hard_skip_names()
  : ['Client Gateway PIN (SCB)'];
$hidden_field_keys = function_exists('afb_get_client_gateway_hidden_field_keys_for_project')
  ? afb_get_client_gateway_hidden_field_keys_for_project($project_gid)
  : null;

$extra_fields = [];
foreach ($fields as $f) {
  $name = $f['name'] ?? '';

  if (!$name || in_array($name, $hard_skip_fields, true)) continue;

  if ($hidden_field_keys === null && in_array($name, $legacy_skip_fields, true)) {
    continue;
  }

  $field_key = function_exists('afb_client_gateway_field_key')
    ? afb_client_gateway_field_key($f)
    : 'name:' . sanitize_title((string) $name);

  if (is_array($hidden_field_keys) && in_array($field_key, $hidden_field_keys, true)) {
    continue;
  }

  $val = match ($f['type'] ?? '') {
    'text'       => $f['text_value'] ?? '',
    'number'     => isset($f['number_value']) ? (string)$f['number_value'] : '',
    'enum'       => $f['enum_value']['name'] ?? '',
    'date'       => $f['date_value']['date'] ?? '',
    'multi_enum' => !empty($f['multi_enum_values'])
        ? implode(', ', array_map(fn($v) => $v['name'] ?? '', $f['multi_enum_values']))
        : '',
    default      => '',
  };
  if ($val !== '' && $val !== null) {
    $extra_fields[] = [
      'key' => $field_key,
      'label' => $name,
      'value' => is_array($val) ? implode(', ', $val) : (string) $val,
    ];
  }
}

?>

<div class="space-y-4 mb-2">

  <div class="space-y-4">

    <!-- Submitter + Meta card -->
    <div class="gateway-card">

      <!-- Submitter -->
      <p class="gateway-label">Submitted By</p>
      <div class="flex items-center gap-3 mt-2 mb-5 pb-5" style="border-bottom:1px solid #f1f5f9">
        <div class="w-11 h-11 rounded-full flex items-center justify-center text-white font-bold text-base flex-shrink-0"
             style="background:linear-gradient(135deg,#4f46e5,#7c3aed)">
          <?= esc_html(mb_strtoupper(mb_substr($submitter ?: 'U', 0, 1))) ?>
        </div>
        <div>
          <p style="font-weight:600;color:#1e293b;font-size:.9375rem;line-height:1.3;margin:0">
            <?= $submitter ? esc_html($submitter) : 'Unknown Submitter' ?>
          </p>
          <?php if ($email): ?>
            <p style="font-size:.8125rem;color:#64748b;margin:.15rem 0 0">
              <?= esc_html($email) ?>
            </p>
          <?php endif; ?>
        </div>
      </div>

      <!-- Meta grid -->
      <div class="grid grid-cols-1 sm:grid-cols-2 gap-0">

        <?php if ($created_at): ?>
        <div class="gateway-meta-item">
          <span class="gateway-meta-icon">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
              <path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5"/>
            </svg>
          </span>
          <div>
            <p class="gateway-meta-key">Created</p>
            <p class="gateway-meta-val"><?= esc_html(date_i18n('M j, Y g:i A', strtotime($created_at))) ?></p>
          </div>
        </div>
        <?php endif; ?>

        <div class="gateway-meta-item">
          <span class="gateway-meta-icon">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
              <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z"/>
            </svg>
          </span>
          <div>
            <p class="gateway-meta-key">Assigned To</p>
            <div class="flex items-center gap-1.5 mt-0.5">
              <?php
                $av_parts = preg_split('/\s+/u', trim($assignee));
                $av_initials = mb_strtoupper(mb_substr($av_parts[0] ?? 'U', 0, 1) . (count($av_parts) > 1 ? mb_substr(end($av_parts), 0, 1) : ''));
              ?>
              <span class="w-5 h-5 rounded-full flex items-center justify-center text-[9px] font-bold"
                    style="background:#003087;color:white;flex-shrink:0">
                <?= esc_html($av_initials) ?>
              </span>
              <p class="gateway-meta-val"><?= esc_html($assignee) ?></p>
            </div>
          </div>
        </div>

        <?php if ($project): ?>
        <div class="gateway-meta-item">
          <span class="gateway-meta-icon">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
              <path stroke-linecap="round" stroke-linejoin="round" d="M2.25 12.75V12A2.25 2.25 0 014.5 9.75h15A2.25 2.25 0 0121.75 12v.75m-8.69-6.44l-2.12-2.12a1.5 1.5 0 00-1.061-.44H4.5A2.25 2.25 0 002.25 6v12a2.25 2.25 0 002.25 2.25h15A2.25 2.25 0 0021.75 18V9a2.25 2.25 0 00-2.25-2.25h-5.379a1.5 1.5 0 01-1.06-.44z"/>
            </svg>
          </span>
          <div>
            <p class="gateway-meta-key">Project</p>
            <p class="gateway-meta-val"><?= esc_html($project) ?></p>
          </div>
        </div>
        <?php endif; ?>

        <?php if ($section): ?>
        <div class="gateway-meta-item">
          <span class="gateway-meta-icon">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
              <path stroke-linecap="round" stroke-linejoin="round" d="M3.75 12h16.5m-16.5 3.75h16.5M3.75 19.5h16.5M5.625 4.5h12.75a1.875 1.875 0 010 3.75H5.625a1.875 1.875 0 010-3.75z"/>
            </svg>
          </span>
          <div>
            <p class="gateway-meta-key">Queue / Section</p>
            <p class="gateway-meta-val"><?= esc_html($section) ?></p>
          </div>
        </div>
        <?php endif; ?>

        <?php if ($due_date): ?>
        <div class="gateway-meta-item">
          <span class="gateway-meta-icon">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
              <path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"/>
            </svg>
          </span>
          <div>
            <p class="gateway-meta-key">Due Date</p>
            <p class="gateway-meta-val"><?= esc_html(date_i18n('M j, Y', strtotime($due_date))) ?></p>
          </div>
        </div>
        <?php endif; ?>

        <?php if ($modified): ?>
        <div class="gateway-meta-item">
          <span class="gateway-meta-icon">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
              <path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99"/>
            </svg>
          </span>
          <div>
            <p class="gateway-meta-key">Last Modified</p>
            <p class="gateway-meta-val"><?= esc_html(date_i18n('M j, Y g:i a', strtotime($modified))) ?></p>
          </div>
        </div>
        <?php endif; ?>

        <?php if ($status): ?>
        <div class="gateway-meta-item">
          <span class="gateway-meta-icon">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
              <path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
            </svg>
          </span>
          <div>
            <p class="gateway-meta-key">Status</p>
            <p class="gateway-meta-val"><?= esc_html($status) ?></p>
          </div>
        </div>
        <?php endif; ?>

      </div><!-- /meta grid -->
    </div><!-- /submitter card -->

    <!-- Description (accordion) -->
    <?php if (!empty($notes)): ?>
    <div class="gateway-card" style="padding:0;overflow:hidden">
      <button type="button" onclick="afbToggleDesc(this)"
              style="width:100%;display:flex;align-items:center;justify-content:space-between;gap:.75rem;padding:1rem 1.25rem;background:none;border:none;cursor:pointer;text-align:left">
        <div style="display:flex;align-items:center;gap:.625rem">
          <span style="width:1.75rem;height:1.75rem;border-radius:.4rem;background:#e0e7ff;display:flex;align-items:center;justify-content:center;flex-shrink:0">
            <svg xmlns="http://www.w3.org/2000/svg" style="width:1rem;height:1rem;color:#4f46e5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
              <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"/>
            </svg>
          </span>
          <div>
            <p class="gateway-label" style="margin:0">Request Description</p>
            <p style="font-size:.75rem;color:#94a3b8;margin:.1rem 0 0" class="afb-desc-hint">Click to view details</p>
          </div>
        </div>
        <svg xmlns="http://www.w3.org/2000/svg" class="afb-chevron" style="width:1.125rem;height:1.125rem;color:#94a3b8;transition:transform .25s ease;flex-shrink:0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
          <path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7"/>
        </svg>
      </button>

      <div class="afb-desc-body" style="max-height:0;overflow:hidden;transition:max-height .3s ease">
        <div style="padding:0 1.25rem 1.25rem">
          <div style="padding-left:1rem;border-left:3px solid #e0e7ff">
            <div style="font-size:.875rem;color:#334155;line-height:1.7">
              <?= nl2br(esc_html($notes)) ?>
            </div>
          </div>
        </div>
      </div>
    </div>

    <script>
    function afbToggleDesc(btn) {
      var body    = btn.nextElementSibling;
      var chevron = btn.querySelector('.afb-chevron');
      var hint    = btn.querySelector('.afb-desc-hint');
      var open    = body.style.maxHeight && body.style.maxHeight !== '0px';
      if (open) {
        body.style.maxHeight = '0';
        chevron.style.transform = '';
        hint.textContent = 'Click to view details';
      } else {
        body.style.maxHeight = body.scrollHeight + 'px';
        chevron.style.transform = 'rotate(180deg)';
        hint.textContent = 'Click to collapse';
      }
    }
    </script>
    <?php endif; ?>

    <?php if (!empty($extra_fields)): ?>
    <div class="gateway-card">
      <div class="gateway-details-head">
        <div>
          <p class="gateway-label" style="margin-bottom:.15rem">Additional Details</p>
          <p class="gateway-details-count"><?= esc_html((string) count($extra_fields)) ?> field<?= count($extra_fields) === 1 ? '' : 's' ?></p>
        </div>
      </div>

      <dl class="gateway-details-list">
        <?php foreach ($extra_fields as $row): ?>
          <div class="gateway-details-row">
            <dt class="gateway-detail-key"><?= esc_html($row['label']) ?></dt>
            <dd class="gateway-detail-val"><?= esc_html($row['value']) ?></dd>
          </div>
        <?php endforeach; ?>
      </dl>
    </div>
    <?php endif; ?>

    <?php include __DIR__ . '/collaborators.php'; ?>

  </div>

</div>
