<?php
/**
 * Timeline Tab – mini-Gantt of dated subtasks
 */
if ( ! defined( 'ABSPATH' ) ) exit;

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

/* ── Helper: read cache & return subtasks array ─────────────── */
$load_cache = function(string $file): array {
    if (!file_exists($file)) return [];
    $data = json_decode(file_get_contents($file), true);
    return is_array($data['subtasks'] ?? null) ? $data['subtasks'] : $data;
};

/* ── 1) Try initial load (<15 min fresh) ────────────────────── */
$age         = file_exists($cache_file) ? time() - filemtime($cache_file) : PHP_INT_MAX;
$all_subtasks = ($age < 900) ? $load_cache($cache_file) : [];

/* ── 2) Auto-regenerate if empty or stale ───────────────────── */
if (empty($all_subtasks)) {
    $regen_url = plugins_url('tools/generate-dashboard-summary.php', $plugin_root.'/asana-form-builder')
               . '?token=' . $token;
    wp_remote_get($regen_url, ['timeout' => 20]);
    $all_subtasks = $load_cache($cache_file);   // reload after regen
}

echo '<!-- Timeline cache items: '.count($all_subtasks).' (age='.$age.'s) -->';

/* ── Transform for Frappe Gantt ─────────────────────────────── */
$subtasks = [];
foreach ($all_subtasks as $t) {
    if (str_starts_with($t['name'] ?? '', 'Section:')) continue;
    $start = $t['start_on'] ?? $t['due_on'] ?? null;
    $end   = $t['due_on']   ?? $t['start_on'] ?? null;
    if (!$start || !$end) continue;

    $done = $t['completed'] ?? false;
    [$badge, $bar] = match ($t['resource_subtype'] ?? 'default_task') {
        'milestone' => ['Milestone', 'bar-milestone'],
        'approval'  => ['Approval',  'bar-approval'],
        default     => [null, $done ? 'bar-complete' : 'bar-open'],
    };

    $subtasks[] = [
        'id'           => $t['gid'],
        'name'         => $t['name'] ?: 'Untitled',
        'start'        => $start,
        'end'          => $end,
        'progress'     => $done ? 100 : 0,
        'custom_class' => $bar,
        'badge'        => $badge,
    ];
}
?>

<!-- Gantt styles -->
<link rel="stylesheet" href="<?= plugin_dir_url(__DIR__) . '../../assets/frappe-gantt.css'; ?>">
<style>
  .bar-complete  { fill:#00A63E !important; }
  .bar-open      { fill:#ff0000 !important; }
  .bar-milestone { fill:#fde047 !important; }
  .bar-approval  { fill:#a855f7 !important; }
  #gantt { min-height:320px; }

  .afb-gantt-popup {
    background:#fff; border-radius:0.5rem; padding:1rem;
    box-shadow:0 8px 16px rgba(0,0,0,.12); max-width:360px;
  }
  .afb-gantt-title { font-weight:600; font-size:.875rem; margin-bottom:.5rem; }
  .afb-gantt-badge {
    display:inline-block; background:#f3f4f6; color:#374151;
    font-size:.75rem; font-weight:500; border-radius:.375rem; padding:.15rem .5rem;
  }
  .afb-gantt-date { font-size:.75rem; color:#6b7280; }
  .bar-wrapper .handle { display:none !important; }
  .bar-wrapper, .bar { cursor:default !important; }
</style>

<section class="bg-white shadow rounded-lg p-6 max-w-screen-2xl mx-auto">
<?php if (empty($subtasks)) : ?>
  <p class="text-gray-500 text-sm">No dated subtasks to display.</p>
<?php else : ?>
  <div id="gantt-wrapper" class="overflow-x-auto">
    <svg id="gantt"></svg>
  </div>
<?php endif; ?>
</section>

<script src="<?= plugin_dir_url(__DIR__) . '../../assets/frappe-gantt.min.js'; ?>"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
  const tasks = <?= json_encode($subtasks); ?>;
  if (!tasks.length || typeof window.Gantt !== 'function') return;

  const viewMode = tasks.length > 60 ? 'Month'
                : tasks.length > 14 ? 'Week'
                : 'Day';

  new window.Gantt('#gantt', tasks, {
    view_mode: viewMode,
    popup_width: 420,
    custom_popup_html: ({ name, start, badge }) => `
      <div class="afb-gantt-popup">
        <div class="afb-gantt-title">${name}</div>
        ${badge ? `<div class="afb-gantt-badge">${badge}</div>` : ''}
        <div class="afb-gantt-date">${start}</div>
      </div>`
  });
});
</script>
