<?php
// task-comms/partials/layout/subtasks.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';

$cache_fresh = file_exists($cache_path) &&
               (time() - filemtime($cache_path)) < 15 * MINUTE_IN_SECONDS;

if (!$cache_fresh) {
    $regen_url = add_query_arg(
        ['token' => $token, 'force' => 1],
        home_url('/wp-content/plugins/asana-form-builder/tools/generate-dashboard-summary.php')
    );
    wp_remote_get($regen_url, ['timeout' => 20]);
    for ($i = 0; $i < 10; $i++) {
        clearstatcache(true, $cache_path);
        if (file_exists($cache_path) && filesize($cache_path) > 0) {
            $cache_fresh = true; break;
        }
        usleep(500_000);
    }
}

if (!$cache_fresh) {
    echo '<div class="gateway-card" style="color:#dc2626;font-size:.875rem">Cache missing: <code>' . esc_html($cache_path) . '</code></div>';
    return;
}

$data     = json_decode(file_get_contents($cache_path), true);
$subtasks = $data['subtasks'] ?? [];

echo '<!-- âœ… loaded ' . count($subtasks) . ' subtasks â€“ ' . date('c', filemtime($cache_path)) . ' -->';

/* â”€â”€ Section stats â”€â”€ */
$sectionStats = [];
$currIdx = null; $total = 0; $done = 0;
foreach ($subtasks as $i => $s) {
    if (($s['resource_subtype'] ?? '') === 'section') {
        if ($currIdx !== null) $sectionStats[$currIdx] = ['completed'=>$done,'total'=>$total];
        $currIdx = $i; $total = $done = 0;
    } else {
        $total++;
        if (!empty($s['completed'])) $done++;
    }
}
if ($currIdx !== null) $sectionStats[$currIdx] = ['completed'=>$done,'total'=>$total];

$hasAnyHeaders = false;
foreach ($subtasks as $s) {
    if (($s['resource_subtype'] ?? '') === 'section') { $hasAnyHeaders = true; break; }
    if (str_starts_with($s['name'] ?? '', 'Section:')) { $hasAnyHeaders = true; break; }
}

$globalDone = $globalTotal = 0;
foreach ($subtasks as $s) {
    if (($s['resource_subtype'] ?? '') !== 'section' && !str_starts_with($s['name'] ?? '', 'Section:')) {
        $globalTotal++;
        if (!empty($s['completed'])) $globalDone++;
    }
}
$globalPct = $globalTotal ? round($globalDone / $globalTotal * 100) : 0;
?>

<div class="gateway-card">

  <?php if (empty($subtasks)) : ?>
    <div style="text-align:center;padding:2.5rem 1rem">
      <p style="font-size:.875rem;color:#94a3b8">No subtasks found for this task.</p>
    </div>
  <?php else : ?>

    <!-- Global progress (no sections) -->
    <?php if (!$hasAnyHeaders): ?>
      <div style="margin-bottom:1.25rem">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.5rem">
          <p class="gateway-label" style="margin:0">Progress</p>
          <span style="font-size:.8125rem;font-weight:600;color:#4f46e5"><?= $globalDone ?> / <?= $globalTotal ?> complete</span>
        </div>
        <div class="gateway-progress-bar"><div class="gateway-progress-fill" style="width:<?= $globalPct ?>%"></div></div>
        <p style="font-size:.6875rem;color:#94a3b8;text-align:right;margin:.35rem 0 0"><?= $globalPct ?>%</p>
      </div>
    <?php endif; ?>

    <!-- Subtask list -->
    <div>
      <?php foreach ($subtasks as $idx => $sub) :
        $type       = $sub['resource_subtype'] ?? '';
        $isSection  = $type === 'section';
        $isMstone   = $type === 'milestone';
        $isApproval = $type === 'approval';
        $completed  = !empty($sub['completed']);
        $name       = trim($sub['name']);
        $isFakeHeader = (!$isSection) && str_starts_with($name, 'Section:');
        if ($isFakeHeader) $headingText = trim(substr($name, strlen('Section:')));
        $assignee  = $sub['assignee']['name'] ?? 'Unassigned';
        $dueLabel  = $sub['due_on'] ?? null;
        $isOverdue = !$completed && $dueLabel && strtotime($dueLabel) < strtotime('today');

        $parts    = preg_split('/\s+/u', trim($assignee));
        $initials = mb_strtoupper(mb_substr($parts[0] ?? 'U', 0, 1) . (count($parts) > 1 ? mb_substr(end($parts), 0, 1) : ''));
        if ($initials === '') $initials = 'U';
      ?>

      <?php if ($isSection) :
        $stat = $sectionStats[$idx] ?? ['completed'=>0,'total'=>0];
        $pct  = $stat['total'] ? round($stat['completed'] / $stat['total'] * 100) : 0;
      ?>
        <div class="gateway-section-head" style="<?= $idx > 0 ? 'border-top:1px solid #f1f5f9;padding-top:1.25rem;margin-top:.5rem' : '' ?>">
          <p class="gateway-section-title"><?= esc_html($name) ?></p>
          <span style="font-size:.75rem;font-weight:600;color:#4f46e5"><?= $stat['completed'] ?> / <?= $stat['total'] ?></span>
        </div>
        <div class="gateway-progress-bar" style="margin-bottom:.75rem">
          <div class="gateway-progress-fill" style="width:<?= $pct ?>%"></div>
        </div>
        <?php continue; endif; ?>

      <?php if ($isFakeHeader) :
        $fdone = $ftotal = 0;
        for ($j = $idx + 1; $j < count($subtasks); $j++) {
            $next = $subtasks[$j];
            if (($next['resource_subtype'] ?? '') === 'section' || str_starts_with($next['name'] ?? '', 'Section:')) break;
            $ftotal++;
            if (!empty($next['completed'])) $fdone++;
        }
        $fpct = $ftotal ? round($fdone / $ftotal * 100) : 0;
      ?>
        <div class="gateway-section-head" style="<?= $idx > 0 ? 'border-top:1px solid #f1f5f9;padding-top:1.25rem;margin-top:.5rem' : '' ?>">
          <p class="gateway-section-title"><?= esc_html($headingText) ?></p>
          <span style="font-size:.75rem;font-weight:600;color:#4f46e5"><?= $fdone ?> / <?= $ftotal ?></span>
        </div>
        <div class="gateway-progress-bar" style="margin-bottom:.75rem">
          <div class="gateway-progress-fill" style="width:<?= $fpct ?>%"></div>
        </div>
        <?php continue; endif; ?>

      <!-- Normal task row -->
      <div class="gateway-subtask-row"<?= $isOverdue ? ' style="background:#fff5f5;border-radius:.5rem;margin-left:-.5rem;margin-right:-.5rem;padding-left:.5rem;padding-right:.5rem"' : '' ?>>  
        <!-- Status dot -->
        <span style="width:.625rem;height:.625rem;border-radius:9999px;flex-shrink:0;background:<?= $completed ? '#22c55e' : '#e2e8f0' ?>;border:<?= $completed ? 'none' : '1.5px solid #94a3b8' ?>"></span>

        <!-- Name + badges -->
        <div style="flex:1;min-width:0">
          <a href="https://app.asana.com/0/0/<?= esc_attr($sub['gid']) ?>"
             target="_blank" rel="noopener noreferrer"
             style="font-size:.875rem;color:<?= $completed ? '#94a3b8' : '#1e293b' ?>;<?= $completed ? 'text-decoration:line-through;' : '' ?>font-weight:500;text-decoration-color:#cbd5e1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:block">
            <?= esc_html($name) ?>
          </a>
          <?php if ($isMstone || $isApproval): ?>
            <span style="font-size:.625rem;font-weight:700;padding:.1rem .45rem;border-radius:9999px;margin-top:.2rem;display:inline-block;<?= $isMstone ? 'background:#fef9c3;color:#854d0e' : 'background:#ede9fe;color:#6d28d9' ?>">
              <?= $isMstone ? 'Milestone' : 'Approval' ?>
            </span>
          <?php endif; ?>
        </div>

        <!-- Due date -->
        <?php if ($dueLabel): ?>
          <span style="font-size:.75rem;color:<?= $isOverdue ? '#dc2626' : '#94a3b8' ?>;white-space:nowrap;flex-shrink:0;display:flex;align-items:center;gap:.25rem;<?= $isOverdue ? 'font-weight:600' : '' ?>">
            <svg xmlns="http://www.w3.org/2000/svg" style="width:.875rem;height:.875rem" 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>
            <?= esc_html(date_i18n('M j', strtotime($dueLabel))) ?><?= $isOverdue ? ' <span style="font-size:.6rem;background:#fee2e2;color:#dc2626;padding:.05rem .35rem;border-radius:9999px;margin-left:.2rem">Overdue</span>' : '' ?>
          </span>
        <?php endif; ?>

        <!-- Assignee avatar -->
        <span style="width:1.625rem;height:1.625rem;border-radius:9999px;background:#e0e7ff;color:#4f46e5;display:flex;align-items:center;justify-content:center;font-size:.625rem;font-weight:700;flex-shrink:0" title="<?= esc_attr($assignee) ?>">
          <?= esc_html($initials) ?>
        </span>
      </div>

      <?php endforeach; ?>
    </div>

  <?php endif; ?>
</div>
