<?php
// asana-form-builder/admin/emails/client-gateway-created.php

// Ensure variables are defined (these should be passed in from your email sender)
$name        = $name        ?? ($submitter_name ?? '');
$task_name   = $task_name   ?? '';
$job_number  = $job_number  ?? '';
$gateway_url = $gateway_url ?? '';
$task_gid    = $task_gid    ?? '';
$gateway_pin = $gateway_pin_template ?? ($gateway_pin ?? '');

// Optional: allow subject/body overrides via WP options (safe defaults)
$subject_template = (isset($subject_template_override) && trim((string)$subject_template_override) !== '')
  ? (string) $subject_template_override
  : (string) get_option('afb_cg_email_subject', 'Client Gateway Created');

$default_body_content = '
  <p>Your Client Gateway has been created.</p>
  <p>You can access it using the button below.</p>
';

$custom_body_content = (isset($body_template_override) && trim((string)$body_template_override) !== '')
  ? (string) $body_template_override
  : (string) get_option('afb_cg_email_body', $default_body_content);

// Build heading + body (keep consistent with your submission template style)
$heading = (isset($heading) && trim((string)$heading) !== '')
  ? sanitize_text_field((string)$heading)
  : 'Client Gateway Created';

// Some safe display values
$display_name      = $name ?: 'there';
$task_name_display = $task_name ?: '';
$job_display       = $job_number ?: '';
$gid_display       = $task_gid ?: '';
$link_display      = $gateway_url ?: '';
$pin_display       = $gateway_pin ?: '';
$workspace_display = sanitize_text_field((string) get_bloginfo('name'));
$first_name_display = $display_name;
if (preg_match('/^\S+/', trim($display_name), $m)) {
  $first_name_display = (string) $m[0];
}

// Build a details block (only show rows that exist)
$details_rows = '';

// Job number first (matches your screenshot order)
if ($job_display !== '') {
  $details_rows .= '<div style="color:#6b7280;font-size:13px;margin:0 0 6px;">
    Job Number: <span style="font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,\'Liberation Mono\',\'Courier New\',monospace;">' . esc_html($job_display) . '</span>
  </div>';
}

// ✅ Prefer Task Name instead of Task ID
if ($task_name_display !== '') {
  $details_rows .= '<div style="color:#6b7280;font-size:13px;margin:0;">
    Task: <span style="font-weight:600;color:#111827;">' . esc_html($task_name_display) . '</span>
  </div>';
} elseif ($gid_display !== '') {
  // Fallback only if task name is missing
  $details_rows .= '<div style="color:#6b7280;font-size:13px;margin:0;">
    Asana Task ID: <span style="font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,\'Liberation Mono\',\'Courier New\',monospace;">' . esc_html($gid_display) . '</span>
  </div>';
}

if ($pin_display !== '') {
  $details_rows .= '<div style="color:#6b7280;font-size:13px;margin:6px 0 0;">
    Gateway PIN: <span style="font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,\'Liberation Mono\',\'Courier New\',monospace;color:#111827;">' . esc_html($pin_display) . '</span>
  </div>';
}


// Subject/body tokens (supports modern {{token}} + legacy {token})
$token_values = [
  'task_name' => $task_name_display,
  'job_number' => $job_display,
  'request_number' => $job_display,
  'gateway_url' => $link_display,
  'task_gid' => $gid_display,
  'name' => $display_name,
  'first_name' => $first_name_display,
  'gateway_pin' => $pin_display,
  'workspace_name' => $workspace_display,
];

if (function_exists('afb_email_expand_placeholders')) {
  $final_subject = afb_email_expand_placeholders($subject_template, $token_values);
} else {
  $legacy_map = [];
  foreach ($token_values as $k => $v) {
    $legacy_map['{{' . $k . '}}'] = (string) $v;
    $legacy_map['{' . $k . '}'] = (string) $v;
  }
  $final_subject = strtr((string) $subject_template, $legacy_map);
}

// Body: prepend greeting only when custom body does not already start with one
$custom_body_prefix = strtolower(trim((string) wp_strip_all_tags($custom_body_content)));
$prepend_intro = !preg_match('/^(hi|hello|dear)\b/', $custom_body_prefix);
$email_body = ($prepend_intro ? '<p>Hi ' . esc_html($display_name) . ',</p>' : '') . $custom_body_content;

if (function_exists('afb_email_expand_placeholders')) {
  $email_body = afb_email_expand_placeholders($email_body, $token_values);
} else {
  $legacy_map = [];
  foreach ($token_values as $k => $v) {
    $legacy_map['{{' . $k . '}}'] = (string) $v;
    $legacy_map['{' . $k . '}'] = (string) $v;
  }
  $email_body = strtr((string) $email_body, $legacy_map);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title><?= esc_html($final_subject) ?></title>
  <style>
    body { font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Arial,sans-serif; background:#f9fafb; padding:32px; color:#1f2937; }
    .container { background:#fff; border-radius:6px; padding:32px; max-width:600px; margin:0 auto; box-shadow:0 1px 3px rgba(0,0,0,0.05); border:1px solid #e5e7eb; }
    .email-head { background:linear-gradient(135deg,#0f2f5f,#1d4f91); border-radius:8px; padding:16px 18px; margin:0 0 18px; }
    .email-kicker { margin:0 0 6px; color:rgba(255,255,255,.75); font-size:12px; letter-spacing:.08em; text-transform:uppercase; font-weight:700; }
    .email-title { margin:0; color:#fff; font-size:18px; line-height:1.35; font-weight:700; }
    .content { font-size:15px; line-height:1.6; }
    .footer  { margin-top:28px; font-size:13px; color:#6b7280; text-align:center; }
    .btn     { display:inline-block;padding:10px 20px;background:#2563eb;color:#ffffff;border-radius:4px;text-decoration:none;font-weight:600; }
    h2 { font-size:20px; margin:0 0 14px; color:#111827; }
    .muted { color:#6b7280; font-size:13px; margin-top:8px; }
    .box { background:#f8fafc; border:1px solid #e5e7eb; border-radius:6px; padding:14px 16px; margin:16px 0; }
    .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size:13px; word-break:break-all; }
    .link { color:#2563eb; text-decoration:underline; }
  </style>
</head>
<body>
  <div class="container">
    <div class="content">
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;border-radius:8px;margin:0 0 18px;">
        <tr><td bgcolor="#1d4f91" style="background-color:#1d4f91;padding:16px 18px;border-radius:8px;">
          <p style="margin:0 0 6px;color:rgba(255,255,255,.8);font-size:12px;letter-spacing:.08em;text-transform:uppercase;font-weight:700;">Corporate Services Division</p>
          <h1 style="margin:0;color:#ffffff;font-size:18px;line-height:1.35;font-weight:700;"><?= esc_html($heading) ?></h1>
        </td></tr>
      </table>

      <?= wp_kses_post($email_body) ?>

      <?php if ($details_rows !== '') : ?>
        <div class="box">
          <?= wp_kses_post($details_rows) ?>
        </div>
      <?php endif; ?>

      <?php if (!empty($gateway_url)) : ?>
        <p style="margin:18px 0 10px;">Open your gateway here:</p>

        <p style="margin:0 0 10px;">
          <a href="<?= esc_url($gateway_url) ?>" class="btn">Open Client Gateway</a>
        </p>

        <p class="muted" style="margin-top:16px;">If the button doesn’t work, copy and paste this link:</p>
        <div class="box mono"><?= esc_html($gateway_url) ?></div>
      <?php else : ?>
        <div class="box">
          <p style="margin:0;color:#b91c1c;"><strong>Gateway link unavailable.</strong></p>
          <p class="muted" style="margin:6px 0 0;">No gateway URL was provided to this template.</p>
        </div>
      <?php endif; ?>
    </div>

    <div class="footer">
      <p style="margin:0;">This is an automated message.</p>
    </div>
  </div>
</body>
</html>
