<?php
/**
 * Client Gateway Creator
 * Manual link: /create-dashboard?task_gid=...&key=...   (creates)
 * Regenerate : /create-dashboard?task_gid=...&key=...&force=1  (must clear link manually first) CC-DEV
 */

/* ── 1. Boot WP ─────────────────────────────── */
$wp_load = dirname(__DIR__, 4) . '/wp-load.php';
if (!file_exists($wp_load)) {
    header('HTTP/1.1 500 Internal Server Error');
    echo 'wp-load.php not found.'; exit;
}
require_once $wp_load;

/* ── 2. Validate task_gid ───────────────────── */
$task_gid = sanitize_text_field($_GET['task_gid'] ?? '');
if (!$task_gid || !ctype_digit($task_gid)) {
    wp_die('Missing or invalid task_gid.', 400);
}
$force = ! empty($_GET['force']);  // any &force param counts

/* ── 3. Pick a PAT that can read the task ───── */
$pat = '';
$task_probe_url = "https://app.asana.com/api/1.0/tasks/{$task_gid}?opt_fields=gid";

if (function_exists('afb_asana_request_for_task')) {
  $probe = afb_asana_request_for_task($task_gid, $task_probe_url, 'GET', null, [200]);
  if (!empty($probe['success']) && !empty($probe['token'])) {
    $pat = (string) $probe['token'];
  }
}

if (!$pat) {
  global $wpdb;
  $accounts = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}asana_accounts ORDER BY active DESC, id DESC", ARRAY_A);
  foreach ($accounts as $acct) {
    $test_pat = afb_decrypt($acct['pat']);
    $resp     = wp_remote_get(
      $task_probe_url,
      ['headers'=>['Authorization'=>"Bearer {$test_pat}"],'timeout'=>6]
    );
    if (!is_wp_error($resp) && wp_remote_retrieve_response_code($resp) === 200) {
      $pat = $test_pat;
      break;
    }
  }
}

if (!$pat) {
  if (function_exists('afb_debug_log')) {
    afb_debug_log("ERROR [create-dashboard] no PAT can read task {$task_gid}");
  }
  wp_die('No stored PAT can access this task.', 500);
}

set_transient('afb_task_pat_' . md5($task_gid), (string) $pat, DAY_IN_SECONDS);

/* ── 4. Field IDs ───────────────────────────── */
$create_field_gid = sanitize_text_field((string) get_option('afb_client_gateway_create_field_gid', '1211304630299020'));
$link_field_gid   = sanitize_text_field((string) get_option('afb_client_gateway_link_field_gid', '1211304630299018'));
$pin_field_gid    = sanitize_text_field((string) get_option('afb_client_gateway_pin_field_gid', '1214258543781835'));

if (!ctype_digit($create_field_gid)) $create_field_gid = '1211304630299020';
if (!ctype_digit($link_field_gid))   $link_field_gid   = '1211304630299018';

/* ── 5. Pull task + current Client Gateway link ─── */
$opt_fields = 'name,custom_fields.name,custom_fields.gid,custom_fields.text_value';
$resp = wp_remote_get(
    "https://app.asana.com/api/1.0/tasks/{$task_gid}?opt_fields=".urlencode($opt_fields),
    ['headers'=>['Authorization'=>"Bearer {$pat}"],'timeout'=>6]
);
if (is_wp_error($resp) || wp_remote_retrieve_response_code($resp)!==200) wp_die('Asana API error.',500);

$task          = json_decode(wp_remote_retrieve_body($resp),true)['data'] ?? [];
$custom_fields = $task['custom_fields'] ?? [];
$current_link  = '';
foreach ($custom_fields as $f) {
    if ($f['gid']===$link_field_gid && !empty($f['text_value'])) {
        $current_link = esc_url_raw($f['text_value']);
        break;
    }
}

$cf_by_gid = [];
foreach ($custom_fields as $f) {
  if (!is_array($f)) {
    continue;
  }
  $gid = preg_replace('/\D+/', '', (string)($f['gid'] ?? ''));
  if ($gid === '') {
    continue;
  }
  $cf_by_gid[$gid] = [
    'gid'  => $gid,
    'name' => trim((string)($f['name'] ?? $gid)),
  ];
}

$find_cf_gid = static function(array $rows, array $patterns, array $exclude = []) {
  foreach ($rows as $row) {
    $name = trim((string)($row['name'] ?? ''));
    if ($name === '') {
      continue;
    }

    $skip = false;
    foreach ($exclude as $rx) {
      if (preg_match($rx, $name)) {
        $skip = true;
        break;
      }
    }
    if ($skip) {
      continue;
    }

    foreach ($patterns as $rx) {
      if (preg_match($rx, $name)) {
        return (string)($row['gid'] ?? '');
      }
    }
  }
  return '';
};

if (!isset($cf_by_gid[$link_field_gid])) {
  $resolved_link_gid = $find_cf_gid(
    array_values($cf_by_gid),
    [
      '/(^|\\b)client\\s+gateway\\s+link(\\b|$)/i',
      '/(^|\\b)client\\s+gateway(\\b|$)/i',
    ],
    [
      '/(^|\\b)create\\s+client\\s+gateway(\\b|$)/i',
      '/(^|\\b)(client\\s+)?gateway\\s*pin(\\b|$)/i',
    ]
  );

  if ($resolved_link_gid !== '') {
    $link_field_gid = $resolved_link_gid;
    update_option('afb_client_gateway_link_field_gid', $link_field_gid);

    // Re-evaluate current link using the resolved field id.
    foreach ($custom_fields as $f) {
      if ((string)($f['gid'] ?? '') === $link_field_gid && !empty($f['text_value'])) {
        $current_link = esc_url_raw((string)$f['text_value']);
        break;
      }
    }
  }
}

if (!isset($cf_by_gid[$pin_field_gid])) {
  $resolved_pin_gid = $find_cf_gid(
    array_values($cf_by_gid),
    [
      '/(^|\\b)(client\\s+)?gateway\\s*pin(\\b|$)/i',
    ]
  );

  if ($resolved_pin_gid !== '') {
    $pin_field_gid = $resolved_pin_gid;
    update_option('afb_client_gateway_pin_field_gid', $pin_field_gid);
  }
}

/* ── 6. Stop if link exists ─────────────────── */
if ($current_link) {
    header('Content-Type: text/html; charset=utf-8'); ?>
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Client Gateway Already Exists</title>
        <script src="https://cdn.tailwindcss.com"></script>
    </head>
    <body class="bg-zinc-50 min-h-screen flex items-center justify-center font-sans text-gray-900">
      <div class="bg-white border rounded-xl max-w-xl w-full p-8">
        <h2 class="text-2xl font-semibold text-blue-700 mb-4">A Client Gateway already exists for this task</h2>
        
        <p class="mb-4 break-words">
          <a href="<?php echo esc_url($current_link); ?>" class="text-blue-600 underline break-all hover:text-blue-800">
            <?php echo esc_html($current_link); ?>
          </a>
        </p>

        <div class="text-sm text-gray-700 bg-blue-50 border border-blue-100 rounded-md p-4">
          <p class="mb-1 text-left">
            If you need to generate a new Client Gateway:
          </p>
          <ul class="text-left list-disc list-inside space-y-1">
            <li>Go to the Asana task</li>
            <li>Clear the <strong>“Client Gateway”</strong> custom field manually</li>
            <li>Then click the <strong>“Create Client Gateway”</strong> link again</li>
          </ul>
        </div>
      </div>
    </body>
    </html>
    <?php exit;
}

/* ── 7. Create Client Gateway token + URL ────────── */
$token     = bin2hex(random_bytes(12));
$pin       = function_exists('afb_gateway_create_pin_for_token')
  ? afb_gateway_create_pin_for_token($token, YEAR_IN_SECONDS)
  : (string) random_int(100000, 999999);
$final_url = site_url("/task-dashboard/{$token}?task_gid={$task_gid}&key=" . rawurlencode((string)($_GET['key'] ?? '')));
$email_gateway_url = function_exists('afb_gateway_build_magic_link')
  ? afb_gateway_build_magic_link($final_url, $token, $task_gid)
  : $final_url;
set_transient("afb_token_task_{$token}", $task_gid, YEAR_IN_SECONDS);

/* ── 8. Save new link back to Asana ─────────── */
$cf_update = [
  $link_field_gid => $final_url,
];

if ($pin_field_gid !== '' && ctype_digit($pin_field_gid)) {
  $cf_update[$pin_field_gid] = $pin;
}

$update = [
  'data'=>['custom_fields'=>$cf_update]
];
$up = wp_remote_request(
    "https://app.asana.com/api/1.0/tasks/{$task_gid}",
    ['method'=>'PUT',
     'headers'=>['Authorization'=>"Bearer {$pat}",'Content-Type'=>'application/json'],
     'body'=>wp_json_encode($update),
     'timeout'=>8
    ]
);
  $up_code = (int) wp_remote_retrieve_response_code($up);
  $up_body = (string) wp_remote_retrieve_body($up);

  // If the PIN field is invalid/missing on this task's project, retry without PIN so gateway creation still succeeds.
  if (
    ($up_code < 200 || $up_code >= 300)
    && isset($cf_update[$pin_field_gid])
    && $pin_field_gid !== ''
    && (
      str_contains($up_body, "Custom field with ID {$pin_field_gid} is not on given object")
      || str_contains($up_body, 'Custom field with ID')
    )
  ) {
    unset($cf_update[$pin_field_gid]);
    $update = [
      'data' => ['custom_fields' => $cf_update]
    ];

    $up = wp_remote_request(
      "https://app.asana.com/api/1.0/tasks/{$task_gid}",
      ['method'=>'PUT',
       'headers'=>['Authorization'=>"Bearer {$pat}",'Content-Type'=>'application/json'],
       'body'=>wp_json_encode($update),
       'timeout'=>8
      ]
    );
    $up_code = (int) wp_remote_retrieve_response_code($up);
    $up_body = (string) wp_remote_retrieve_body($up);
  }

  if ($up_code < 200 || $up_code >= 300) {
    $msg = 'Failed to update task with Client Gateway link.';
    $decoded = json_decode($up_body, true);
    $api_msg = (string)($decoded['errors'][0]['message'] ?? '');
    if ($api_msg !== '') {
      $msg .= ' Asana: ' . $api_msg;
    }
    wp_die($msg, 500);
  }


/* ── 8b. Email submitter (optional) ─────────────────────────── */

// Prevent spamming if create is triggered repeatedly (only set once we KNOW we’ll send)
$dedupe_key = 'afb_cg_email_sent_' . md5((string) $task_gid);
if (!get_transient($dedupe_key)) {

    // --- Detect submitter email/name from text custom fields (Step 5 payload) ---
    $submitter_email = '';
    $submitter_name  = '';

    foreach (($custom_fields ?? []) as $f) {
        $label = strtolower(trim((string)($f['name'] ?? '')));
        $val   = (string)($f['text_value'] ?? '');
        if (!$val) continue;

        // Name hint
        if (
            !$submitter_name
            && ($label === 'name' || str_contains($label, 'submitter') || str_contains($label, 'contact'))
        ) {
            $submitter_name = sanitize_text_field($val);
        }

        // Email hint (strong)
        if (!$submitter_email) {
            $maybe = sanitize_email($val);
            if ($maybe && is_email($maybe)) {
                $submitter_email = $maybe;
            }
        }
    }

    // --- Extract Job Number (SCB) if present ---
    $job_number = '';
    foreach (($custom_fields ?? []) as $cf) {
        if (($cf['name'] ?? '') === 'Job Number (SCB)') {
            $job_number = (string)($cf['text_value'] ?? $cf['number_value'] ?? '');
            break;
        }
    }

    if ($submitter_email && is_email($submitter_email)) {

        // ✅ Mark as sent ONLY when we’re actually about to send
        set_transient($dedupe_key, 1, 10 * MINUTE_IN_SECONDS);

        // ✅ Preferred: use your new template-based sender
        require_once plugin_dir_path(__FILE__) . '../includes/email-sender.php';

        if (function_exists('afb_send_client_gateway_created_email')) {

            afb_send_client_gateway_created_email([
                'to'          => $submitter_email,
                'name'        => $submitter_name ?: 'there',
                'task_name'   => (string)($task['name'] ?? ''),
                'task_gid'    => (string)$task_gid,
                'job_number'  => (string)$job_number,
                'gateway_url' => (string)$email_gateway_url,
              'gateway_pin' => (string)$pin,
            ]);

        } elseif (function_exists('afb_email_send')) {

            // Back-compat (if you still have the older mailer available)
            afb_email_send('client_gateway.created', [
                'to'          => $submitter_email,
                'name'        => $submitter_name ?: 'there',
                'task_gid'    => (string)$task_gid,
                'gateway_url' => (string)$email_gateway_url,
                'task_name'   => (string)($task['name'] ?? ''),
                'job_number'  => (string)$job_number,
              'gateway_pin' => (string)$pin,
            ]);

        } else {

            // Last resort: plain HTML wp_mail
            $subject = 'Your Client Gateway is ready';

            $task_name_safe = esc_html((string)($task['name'] ?? ''));
            $name_safe      = esc_html($submitter_name ?: 'there');
            $link_safe      = esc_url($email_gateway_url);

            $message = '<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>' . esc_html($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; }
    .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; }
  </style>
</head>
<body>
  <div class="container">
    <div class="content">
      <h2>Client Gateway Created</h2>
      <p>Hi ' . $name_safe . ',</p>
      <p>Your Client Gateway has been created for:</p>

      <div class="box">
        <div><strong>' . $task_name_safe . '</strong></div>'
        . (!empty($job_number) ? '<div class="muted">Job Number: <span class="mono">' . esc_html($job_number) . '</span></div>' : '') . '
        <div class="muted">Asana Task ID: <span class="mono">' . esc_html((string)$task_gid) . '</span></div>
      </div>

      <p style="margin:18px 0 10px;">Open your gateway here:</p>
      <p style="margin:0 0 10px;">
        <a href="' . $link_safe . '" class="btn">Open Client Gateway</a>
      </p>

      <p class="muted" style="margin-top:12px;">Gateway PIN:</p>
      <div class="box mono">' . esc_html((string) $pin) . '</div>

      <p class="muted" style="margin-top:16px;">If the button doesn’t work, copy and paste this link:</p>
      <div class="box mono">' . $link_safe . '</div>

      <p style="margin-top:18px;">Thanks</p>
    </div>

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

            $headers = ['Content-Type: text/html; charset=UTF-8'];
            wp_mail($submitter_email, $subject, $message, $headers);
        }
    }
}



/* ── 9. Build summary cache locally ─────────────────────────── */

function afb_write_dashboard_cache(string $task_gid, string $token, string $pat): void {
    $cache_dir  = dirname(__DIR__) . '/cache/';
    if (!is_dir($cache_dir)) mkdir($cache_dir, 0755, true);
    $cache_file = $cache_dir . "tasks-summary-{$token}.json";

    // 1) Parent meta — include gid/email for assignee/followers so notifications can use cache data directly.
    $parent_fields = implode(',', [
      'name,notes,completed,start_on,due_on,created_at,modified_at',
      'assignee.gid,assignee.name,assignee.email',
      'projects.name,followers.gid,followers.name,followers.email',
      'custom_fields.gid,custom_fields.name,custom_fields.type,custom_fields.text_value,custom_fields.number_value,custom_fields.enum_value.gid,custom_fields.enum_value.name,custom_fields.enum_value.color,custom_fields.multi_enum_values.gid,custom_fields.multi_enum_values.name,custom_fields.multi_enum_values.color'
    ]);
    $p   = wp_remote_get(
            "https://app.asana.com/api/1.0/tasks/{$task_gid}?opt_fields={$parent_fields}",
            ['headers'=>['Authorization'=>"Bearer {$pat}"], 'timeout'=>12]
          );
    $parent = json_decode(wp_remote_retrieve_body($p), true)['data'] ?? [];

    // 2) Subtasks — single paged call with fields; no per-subtask N+1; no photos.
    $subs = [];
    $sub_fields = urlencode('gid,name,completed,start_on,due_on,resource_subtype,assignee.name');
    $url = "https://app.asana.com/api/1.0/tasks/{$task_gid}/subtasks?opt_fields={$sub_fields}&limit=100";

    while ($url) {
        $resp = wp_remote_get($url, ['headers'=>['Authorization'=>"Bearer {$pat}"], 'timeout'=>12]);
        $body = json_decode(wp_remote_retrieve_body($resp), true);
        foreach (($body['data'] ?? []) as $row) {
            $subs[] = [
                'gid'              => $row['gid'] ?? null,
                'name'             => $row['name'] ?? '(Untitled)',
                'completed'        => $row['completed'] ?? false,
                'start_on'         => $row['start_on'] ?? null,
                'due_on'           => $row['due_on']   ?? null,
                'resource_subtype' => $row['resource_subtype'] ?? 'default_task',
                // keep structure, but no image URL (UI renders initials)
                'assignee'         => [
                    'name'  => $row['assignee']['name'] ?? 'Unassigned',
                    'photo' => null,
                ],
            ];
        }
        $url = $body['next_page']['uri'] ?? null;
    }

    file_put_contents($cache_file, wp_json_encode([
        'parent'   => $parent,
        'subtasks' => $subs,
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

afb_write_dashboard_cache($task_gid, $token, $pat);

/* ── 10. Success page ───────────────────────── */
header('Content-Type: text/html; charset=utf-8'); ?>
<!DOCTYPE html><html lang="en"><head>
  <meta charset="utf-8"><title>Client Gateway Created</title>
  <meta http-equiv="refresh" content="5;url=<?php echo esc_url($final_url); ?>">
  <script src="https://cdn.tailwindcss.com"></script>
</head><body class="font-sans antialiased">
  <div class="max-w-xl mx-auto mt-24 px-6 py-8 rounded-lg text-center text-grey-900">
    <h2 class="text-1xl font-semibold mb-2">Client Gateway created.</h2>
    <p class="mb-4">Your Client Gateway is ready:</p>
    <a href="<?php echo esc_url($final_url); ?>"
       class="inline-block bg-white text-blue-900 font-medium px-5 py-2 rounded border border-blue-900 hover:bg-blue-50 transition">
       Open Client Gateway
    </a>
    <p class="text-sm mt-4 text-blue-800">Redirecting automatically in 5&nbsp;seconds…</p>
  </div>
</body></html>
<?php
/* optional debug log...
$log = WP_CONTENT_DIR.'/custom-debug.log';
file_put_contents($log,'['.current_time('mysql')."] Client Gateway created for {$task_gid}\n",FILE_APPEND);
*/
