<?php
declare(strict_types=1);
require_once __DIR__ . '/_inc/boot.php';
require_once __DIR__ . '/_inc/db.php';
require_once __DIR__ . '/_inc/pickpack.php';

$pdo = db();
auth_require_any_permission(['use_crons', 'manage_settings']);

$title = 'Open leads';
$active = 'crons';
$msg = '';

function open_leads_provider_expr(): string {
  return "CASE
    WHEN l.lead_number LIKE 'PP-%' THEN 'PICKPACK'
    WHEN l.lead_number LIKE 'AH-%' THEN 'EFC'
    ELSE COALESCE(c.fulfillment_provider,'EFC')
  END";
}

function open_leads_tracking_missing_sql(string $providerExpr): string {
  return "(
    l.tracking_number IS NULL
    OR TRIM(l.tracking_number)=''
    OR UPPER(TRIM(l.tracking_number)) IN ('PICKPACK','LINK','PDF','LABEL','PENDING','N/A','NA','NONE','NULL','UNKNOWN','0','-')
    OR l.tracking_number LIKE 'http://%'
    OR l.tracking_number LIKE 'https://%'
    OR LOWER(l.tracking_number) LIKE '%.pdf%'
    OR (
      ({$providerExpr})<>'QCARGO'
      AND (
        TRIM(l.tracking_number)=TRIM(l.lead_number)
        OR (l.order_id_remote IS NOT NULL AND l.order_id_remote<>'' AND TRIM(l.tracking_number)=TRIM(l.order_id_remote))
      )
    )
  )";
}

function open_leads_base_expr(): string {
  return "GREATEST(
    COALESCE(l.created_at_remote, '1970-01-01 00:00:00'),
    COALESCE(l.confirmed_at, '1970-01-01 00:00:00'),
    COALESCE(l.created_at, '1970-01-01 00:00:00')
  )";
}

function open_leads_details_ok_sql(): string {
  return "(
    l.details_fetched_at IS NOT NULL
    AND l.items_json IS NOT NULL
    AND l.customer_name IS NOT NULL AND TRIM(l.customer_name)<>''
    AND l.phone IS NOT NULL AND TRIM(l.phone)<>''
    AND l.address IS NOT NULL AND TRIM(l.address)<>''
    AND l.city IS NOT NULL AND TRIM(l.city)<>''
  )";
}

function open_leads_terminal_status_sql(): string {
  $statuses = "'no answer 9','canceled','out_of_area','out of area','duplicated','archived'";
  $latestNorm = "(SELECT hterm.status_norm FROM lead_history hterm WHERE hterm.lead_number=l.lead_number ORDER BY COALESCE(hterm.status_at,hterm.created_at) DESC, hterm.id DESC LIMIT 1)";
  $latestRaw = "(SELECT LOWER(TRIM(hraw.status_raw)) FROM lead_history hraw WHERE hraw.lead_number=l.lead_number ORDER BY COALESCE(hraw.status_at,hraw.created_at) DESC, hraw.id DESC LIMIT 1)";
  return "(
    LOWER(TRIM(COALESCE(l.current_status,''))) IN ({$statuses})
    OR COALESCE({$latestNorm}, '') IN ({$statuses})
    OR COALESCE({$latestRaw}, '') IN ({$statuses})
  )";
}

function open_leads_scalar($value): string {
  return trim((string)($value ?? ''));
}

function open_leads_reason(array $row): array {
  $reasons = [];
  $age = (int)($row['age_hours'] ?? 0);
  $historyCount = (int)($row['history_count'] ?? 0);
  $current = open_leads_scalar($row['current_status'] ?? '');
  $latest = open_leads_scalar($row['latest_raw'] ?? '');
  $detailsOk = (int)($row['details_ok'] ?? 0) === 1;
  $trackingMissing = (int)($row['tracking_missing'] ?? 0) === 1;
  $terminalOpen = (int)($row['terminal_open'] ?? 0) === 1;
  $historyAge = (int)($row['history_age_hours'] ?? 0);
  $detailsAge = (int)($row['details_age_hours'] ?? 0);

  if ($terminalOpen) $reasons[] = 'archive candidate';
  if ($trackingMissing) $reasons[] = 'missing tracking';
  if ($historyCount === 0) $reasons[] = 'no history';
  if ($current === '') $reasons[] = 'blank status';
  if (!$detailsOk) $reasons[] = 'missing details';
  if ($historyCount > 0 && $historyAge >= 6) $reasons[] = 'history stale ' . $historyAge . 'h';
  if ($detailsAge >= 6) $reasons[] = 'details stale ' . $detailsAge . 'h';
  if ($age >= 96) $reasons[] = 'open 96h+';
  elseif ($age >= 72) $reasons[] = 'open 72h+';
  elseif ($age >= 48) $reasons[] = 'open 48h+';
  if (!$reasons) $reasons[] = $latest !== '' ? ('waiting: ' . $latest) : 'open / waiting';
  return $reasons;
}

function open_leads_archive(PDO $pdo, array $leadNumbers, string $reason): int {
  $leadNumbers = array_values(array_unique(array_filter(array_map(static function($v): string {
    return trim((string)$v);
  }, $leadNumbers), static function(string $v): bool {
    return $v !== '';
  })));
  if (!$leadNumbers) return 0;

  $now = now_dt();
  $reason = trim($reason);
  if ($reason === '') $reason = 'Manual archive from open leads report';
  $noteLine = '[' . $now . '] Archived manually: ' . $reason;
  $updated = 0;

  $pdo->beginTransaction();
  try {
    $st = $pdo->prepare("UPDATE leads SET
        final_status=1,
        current_status='archived',
        current_status_at=?,
        details_fetched_at=COALESCE(details_fetched_at, ?),
        history_fetched_at=COALESCE(history_fetched_at, ?),
        last_sync_job='manual_archive',
        last_sync_at=?,
        updated_at=?,
        note=CASE WHEN note IS NULL OR note='' THEN ? ELSE CONCAT(note, '\n', ?) END
      WHERE lead_number=? AND final_status=0");
    $hist = $pdo->prepare("INSERT IGNORE INTO lead_history(lead_number,status_raw,status_norm,status_at,note,created_at)
      VALUES(?,?,?,?,?,?)");
    foreach ($leadNumbers as $lead) {
      $st->execute([$now, $now, $now, $now, $now, $noteLine, $noteLine, $lead]);
      $updated += (int)$st->rowCount();
      $hist->execute([$lead, 'Archived manually', 'archived', $now, $reason, $now]);
    }
    $pdo->commit();
  } catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    throw $e;
  }

  return $updated;
}

function open_leads_filters_from(array $src): array {
  return [
    'q' => trim((string)($src['q'] ?? '')),
    'country' => strtoupper(trim((string)($src['country'] ?? ''))),
    'provider' => strtoupper(trim((string)($src['provider'] ?? ''))),
    'issue' => strtolower(trim((string)($src['issue'] ?? ''))),
    'min_age' => isset($src['min_age']) ? max(0, min(2160, (int)$src['min_age'])) : 0,
    'limit' => isset($src['limit']) ? max(50, min(5000, (int)$src['limit'])) : 500,
  ];
}

function open_leads_build_where(array $filters, string $providerExpr, string $missingSql, string $baseExpr, string $detailsOkSql, string $terminalSql): array {
  $where = ['l.final_status=0'];
  $params = [];
  $minAge = (int)($filters['min_age'] ?? 0);
  $country = (string)($filters['country'] ?? '');
  $provider = (string)($filters['provider'] ?? '');
  $q = (string)($filters['q'] ?? '');
  $issue = (string)($filters['issue'] ?? '');

  if ($minAge > 0) {
    $where[] = "TIMESTAMPDIFF(HOUR, {$baseExpr}, NOW()) >= ?";
    $params[] = $minAge;
  }
  if ($country !== '') {
    $where[] = 'UPPER(l.country)=?';
    $params[] = $country;
  }
  if ($provider !== '' && in_array($provider, ['EFC','PICKPACK','QCARGO'], true)) {
    $where[] = "({$providerExpr})=?";
    $params[] = $provider;
  }
  if ($q !== '') {
    $where[] = '(l.lead_number LIKE ? OR l.customer_name LIKE ? OR l.email LIKE ? OR l.phone LIKE ? OR l.tracking_number LIKE ?)';
    $like = '%' . $q . '%';
    array_push($params, $like, $like, $like, $like, $like);
  }
  if ($issue === 'missing_tracking') {
    $where[] = $missingSql;
  } elseif ($issue === 'missing_details') {
    $where[] = 'NOT ' . $detailsOkSql;
  } elseif ($issue === 'no_history') {
    $where[] = 'NOT EXISTS (SELECT 1 FROM lead_history hn WHERE hn.lead_number=l.lead_number)';
  } elseif ($issue === 'stale_history') {
    $where[] = "(l.history_fetched_at IS NULL OR l.history_fetched_at < DATE_SUB(NOW(), INTERVAL 6 HOUR))";
  } elseif ($issue === 'stale_details') {
    $where[] = "(l.details_fetched_at IS NULL OR l.details_fetched_at < DATE_SUB(NOW(), INTERVAL 6 HOUR))";
  } elseif ($issue === 'terminal_open') {
    $where[] = $terminalSql;
  }

  return [$where, $params];
}

function open_leads_matching_lead_numbers(PDO $pdo, array $where, array $params, string $baseExpr, int $limit = 10000): array {
  $limit = max(1, min(10000, $limit));
  $st = $pdo->prepare("SELECT l.lead_number
    FROM leads l
    LEFT JOIN countries c ON c.code=l.country
    WHERE " . implode(' AND ', $where) . "
    ORDER BY TIMESTAMPDIFF(HOUR, {$baseExpr}, NOW()) DESC, COALESCE(l.current_status_at,l.updated_at,l.created_at) ASC
    LIMIT {$limit}");
  $st->execute($params);
  $rows = $st->fetchAll(PDO::FETCH_COLUMN);
  return array_values(array_filter(array_map('strval', $rows)));
}

$filters = open_leads_filters_from($_GET);
$q = (string)$filters['q'];
$country = (string)$filters['country'];
$provider = (string)$filters['provider'];
$issue = (string)$filters['issue'];
$minAge = (int)$filters['min_age'];
$limit = (int)$filters['limit'];
$providerExpr = open_leads_provider_expr();
$missingSql = open_leads_tracking_missing_sql($providerExpr);
$baseExpr = open_leads_base_expr();
$detailsOkSql = open_leads_details_ok_sql();
$terminalSql = open_leads_terminal_status_sql();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    $op = (string)($_POST['op'] ?? '');
    if ($op === 'archive_selected') {
      $selected = $_POST['lead'] ?? [];
      if (!is_array($selected)) $selected = [$selected];
      $count = open_leads_archive($pdo, $selected, (string)($_POST['archive_reason'] ?? ''));
      $msg = 'Archived ' . $count . ' lead(s). They will not be refreshed by normal crons.';
    } elseif ($op === 'archive_matching_old') {
      $archiveHours = max(1, min(2160, (int)($_POST['archive_hours'] ?? 720)));
      $postFilters = open_leads_filters_from($_POST);
      $postFilters['min_age'] = $archiveHours;
      [$archiveWhere, $archiveParams] = open_leads_build_where($postFilters, $providerExpr, $missingSql, $baseExpr, $detailsOkSql, $terminalSql);
      $leadNumbers = open_leads_matching_lead_numbers($pdo, $archiveWhere, $archiveParams, $baseExpr, 10000);
      $count = open_leads_archive($pdo, $leadNumbers, (string)($_POST['archive_reason'] ?? ('Bulk archive older than ' . $archiveHours . 'h')));
      $msg = 'Archived ' . $count . ' lead(s) older than ' . $archiveHours . 'h matching current filters.';
    }
  } catch (Throwable $e) {
    $msg = 'ERROR: ' . $e->getMessage();
  }
}

[$where, $params] = open_leads_build_where($filters, $providerExpr, $missingSql, $baseExpr, $detailsOkSql, $terminalSql);

$latestRawSql = "(SELECT h.status_raw FROM lead_history h WHERE h.lead_number=l.lead_number ORDER BY COALESCE(h.status_at,h.created_at) DESC, h.id DESC LIMIT 1)";
$latestNormSql = "(SELECT h.status_norm FROM lead_history h WHERE h.lead_number=l.lead_number ORDER BY COALESCE(h.status_at,h.created_at) DESC, h.id DESC LIMIT 1)";
$latestAtSql = "(SELECT COALESCE(h.status_at,h.created_at) FROM lead_history h WHERE h.lead_number=l.lead_number ORDER BY COALESCE(h.status_at,h.created_at) DESC, h.id DESC LIMIT 1)";

$sql = "SELECT
    l.lead_number,
    l.country,
    {$providerExpr} AS provider,
    l.customer_name,
    l.email,
    l.phone,
    l.current_status,
    l.current_status_at,
    l.created_at_remote,
    l.confirmed_at,
    l.created_at,
    l.updated_at,
    l.tracking_number,
    l.order_id_remote,
    l.courier_code,
    l.shipping_company,
    l.details_fetched_at,
    l.history_fetched_at,
    l.last_sync_job,
    l.last_sync_at,
    l.qty_cards,
    l.note,
    TIMESTAMPDIFF(HOUR, {$baseExpr}, NOW()) AS age_hours,
    TIMESTAMPDIFF(HOUR, COALESCE(l.history_fetched_at, {$baseExpr}), NOW()) AS history_age_hours,
    TIMESTAMPDIFF(HOUR, COALESCE(l.details_fetched_at, {$baseExpr}), NOW()) AS details_age_hours,
    CASE WHEN {$missingSql} THEN 1 ELSE 0 END AS tracking_missing,
    CASE WHEN {$detailsOkSql} THEN 1 ELSE 0 END AS details_ok,
    CASE WHEN {$terminalSql} THEN 1 ELSE 0 END AS terminal_open,
    (SELECT COUNT(*) FROM lead_history hc WHERE hc.lead_number=l.lead_number) AS history_count,
    {$latestRawSql} AS latest_raw,
    {$latestNormSql} AS latest_norm,
    {$latestAtSql} AS latest_at
  FROM leads l
  LEFT JOIN countries c ON c.code=l.country
  WHERE " . implode(' AND ', $where) . "
  ORDER BY age_hours DESC, COALESCE(l.current_status_at,l.updated_at,l.created_at) ASC
  LIMIT {$limit}";

$st = $pdo->prepare($sql);
$st->execute($params);
$rows = $st->fetchAll();

$countries = $pdo->query("SELECT DISTINCT country FROM leads WHERE final_status=0 AND country IS NOT NULL AND country<>'' ORDER BY country")->fetchAll(PDO::FETCH_COLUMN);
$summary = [
  'total' => count($rows),
  'missing_tracking' => 0,
  'missing_details' => 0,
  'no_history' => 0,
  'terminal_open' => 0,
  'open_48' => 0,
  'open_96' => 0,
];
foreach ($rows as $row) {
  if ((int)($row['tracking_missing'] ?? 0) === 1) $summary['missing_tracking']++;
  if ((int)($row['details_ok'] ?? 0) !== 1) $summary['missing_details']++;
  if ((int)($row['history_count'] ?? 0) === 0) $summary['no_history']++;
  if ((int)($row['terminal_open'] ?? 0) === 1) $summary['terminal_open']++;
  if ((int)($row['age_hours'] ?? 0) >= 48) $summary['open_48']++;
  if ((int)($row['age_hours'] ?? 0) >= 96) $summary['open_96']++;
}

$cfg = app_cfg();
$cronKey = (string)($cfg['security']['cron_key'] ?? '');

require_once __DIR__ . '/_inc/layout_top.php';
?>
<div data-autorefresh="1" data-kind="open_leads"></div>

<section class="card wide" style="margin-bottom:14px">
  <div class="card-h">
    <div>
      <div class="card-title">Open leads audit</div>
      <div class="muted">All non-final leads across every country/provider. Use this to find stuck shipments and archive them manually.</div>
    </div>
    <div class="row" style="justify-content:flex-end">
      <a class="btn btn-sm btn-ghost" href="/crons.php">Crons</a>
      <a class="btn btn-sm btn-ghost" href="/bad_tracking.php">Bad tracking</a>
    </div>
  </div>
  <?php if($msg !== ''): ?><div class="pill" style="margin:0 16px 12px"><?= h($msg) ?></div><?php endif; ?>
  <div class="kpi-row">
    <div class="kpi neutral"><div class="k">OPEN</div><div class="v"><?= (int)$summary['total'] ?></div><div class="p">Visible rows</div></div>
    <div class="kpi warn"><div class="k">NO TRACKING</div><div class="v"><?= (int)$summary['missing_tracking'] ?></div><div class="p">Invalid or empty tracking</div></div>
    <div class="kpi warn"><div class="k">MISSING DETAILS</div><div class="v"><?= (int)$summary['missing_details'] ?></div><div class="p">Required fields incomplete</div></div>
    <div class="kpi bad"><div class="k">NO HISTORY</div><div class="v"><?= (int)$summary['no_history'] ?></div><div class="p">No provider/courier status rows</div></div>
    <div class="kpi bad"><div class="k">ARCHIVE CANDIDATES</div><div class="v"><?= (int)$summary['terminal_open'] ?></div><div class="p">Terminal status but still open</div></div>
    <div class="kpi warn"><div class="k">48H+</div><div class="v"><?= (int)$summary['open_48'] ?></div><div class="p">Still open</div></div>
    <div class="kpi bad"><div class="k">96H+</div><div class="v"><?= (int)$summary['open_96'] ?></div><div class="p">Archive candidates</div></div>
  </div>
</section>

<section class="card wide">
  <form class="row" method="get" action="/open_leads.php">
    <input class="input" type="text" name="q" value="<?= h($q) ?>" placeholder="Search lead/customer/email/phone/tracking" style="min-width:260px" />
    <select class="input" name="min_age" style="max-width:130px">
      <?php foreach([0,12,24,48,72,96,168,720] as $h0): ?>
        <option value="<?= (int)$h0 ?>" <?= $minAge===$h0?'selected':'' ?>><?= $h0===0 ? 'all ages' : ((int)$h0 . 'h+') ?></option>
      <?php endforeach; ?>
    </select>
    <select class="input" name="country" style="max-width:180px">
      <option value="">All countries</option>
      <?php foreach($countries as $c): $c = (string)$c; ?>
        <option value="<?= h($c) ?>" <?= $country===strtoupper($c)?'selected':'' ?>><?= h($c) ?></option>
      <?php endforeach; ?>
    </select>
    <select class="input" name="provider" style="max-width:160px">
      <option value="">All providers</option>
      <?php foreach(['EFC','PICKPACK','QCARGO'] as $p): ?>
        <option value="<?= h($p) ?>" <?= $provider===$p?'selected':'' ?>><?= h($p) ?></option>
      <?php endforeach; ?>
    </select>
    <select class="input" name="issue" style="max-width:180px">
      <?php
        $issues = [
          '' => 'All issues',
          'missing_tracking' => 'Missing tracking',
          'missing_details' => 'Missing details',
          'no_history' => 'No history',
          'stale_history' => 'Stale history',
          'stale_details' => 'Stale details',
          'terminal_open' => 'Archive candidates',
        ];
      ?>
      <?php foreach($issues as $k=>$label): ?>
        <option value="<?= h($k) ?>" <?= $issue===$k?'selected':'' ?>><?= h($label) ?></option>
      <?php endforeach; ?>
    </select>
    <select class="input" name="limit" style="max-width:130px">
      <?php foreach([100,250,500,1000,2500,5000] as $l0): ?>
        <option value="<?= (int)$l0 ?>" <?= $limit===$l0?'selected':'' ?>>max <?= (int)$l0 ?></option>
      <?php endforeach; ?>
    </select>
    <button class="btn" type="submit">Apply</button>
    <a class="btn btn-ghost" href="/open_leads.php">Reset</a>
  </form>

  <form method="post" class="row" style="margin-top:12px; gap:10px; align-items:center">
    <input type="hidden" name="op" value="archive_matching_old" />
    <input type="hidden" name="q" value="<?= h($q) ?>" />
    <input type="hidden" name="country" value="<?= h($country) ?>" />
    <input type="hidden" name="provider" value="<?= h($provider) ?>" />
    <input type="hidden" name="issue" value="<?= h($issue) ?>" />
    <input type="hidden" name="limit" value="<?= (int)$limit ?>" />
    <input class="input" type="number" name="archive_hours" value="720" min="1" max="2160" style="max-width:130px" />
    <input class="input" name="archive_reason" value="Bulk old open lead archive - stop refresh" style="min-width:300px" />
    <button class="btn btn-ghost" type="submit" onclick="return confirm('Archive ALL open leads older than selected hours matching current filters?')">Archive all old matching</button>
    <div class="muted small">Uses current filters + selected age. 720h = 30 days. Max 10000 per click.</div>
  </form>

  <form method="post" style="margin-top:12px">
    <input type="hidden" name="op" value="archive_selected" />
    <div class="row" style="gap:10px; align-items:center">
      <input class="input" name="archive_reason" placeholder="Archive reason / note" value="Old open lead - stop refresh" style="min-width:280px" />
      <button class="btn btn-ghost" type="submit" onclick="return confirm('Archive selected leads and stop normal refresh?')">Archive selected</button>
      <div class="muted small">Archive sets <code>final_status=1</code>, <code>current_status=archived</code>, and removes these leads from normal refresh queues.</div>
    </div>

    <div class="table-wrap" style="margin-top:12px">
      <table class="table">
        <thead>
          <tr>
            <th></th>
            <th>Lead</th>
            <th>Age</th>
            <th>Provider</th>
            <th>Country</th>
            <th>Status</th>
            <th>Latest history</th>
            <th>Tracking</th>
            <th>Last sync</th>
            <th>Why stuck</th>
            <th class="right">Actions</th>
          </tr>
        </thead>
        <tbody>
        <?php if(!$rows): ?>
          <tr><td colspan="11" class="muted">No open leads for this filter.</td></tr>
        <?php endif; ?>
        <?php foreach($rows as $row):
          $lead = (string)$row['lead_number'];
          $age = (int)($row['age_hours'] ?? 0);
          $trackingLabel = trim(strip_tracking_date_suffix((string)($row['tracking_number'] ?? '')));
          $courierLabel = trim((string)($row['courier_code'] ?? ''));
          if ($courierLabel === '') $courierLabel = trim((string)($row['shipping_company'] ?? ''));
          if (strcasecmp($trackingLabel, 'PICKPACK') === 0 || tracking_value_is_label_url($trackingLabel) || ($trackingLabel !== '' && $trackingLabel === trim((string)($row['order_id_remote'] ?? '')))) $trackingLabel = '';
          if ($courierLabel !== '') $courierLabel = normalize_courier_code($courierLabel) ?? $courierLabel;
          if (strcasecmp($courierLabel, 'PICKPACK') === 0) $courierLabel = '';
          $url = $trackingLabel !== '' ? build_tracking_url($courierLabel, $trackingLabel, $row['country']) : null;
          $reasons = open_leads_reason($row);
          $ageClass = $age >= 96 ? 'badge-bad' : ($age >= 48 ? 'badge-warn' : '');
        ?>
          <tr>
            <td><input type="checkbox" name="lead[]" value="<?= h($lead) ?>" /></td>
            <td><a class="lead-link" href="/lead.php?lead=<?= urlencode($lead) ?>"><?= h($lead) ?></a></td>
            <td><span class="badge <?= h($ageClass) ?>"><?= (int)$age ?>h</span></td>
            <td><span class="badge"><?= h($row['provider']) ?></span></td>
            <td><?= h($row['country']) ?></td>
            <td>
              <span class="badge"><?= h($row['current_status']) ?></span>
              <div class="t-sub muted"><?= h(dd($row['current_status_at'])) ?></div>
            </td>
            <td>
              <div class="t-top"><?= h($row['latest_raw'] ?: $row['latest_norm']) ?></div>
              <div class="t-sub muted"><?= h(dd($row['latest_at'])) ?> · <?= (int)($row['history_count'] ?? 0) ?> rows</div>
            </td>
            <td>
              <?php if($url): ?>
                <a href="<?= h($url) ?>" target="_blank" rel="noopener">
                  <div class="t-top"><?= h($trackingLabel) ?></div>
                  <?php if($courierLabel !== ''): ?><div class="t-sub muted"><?= h($courierLabel) ?></div><?php endif; ?>
                </a>
              <?php else: ?>
                <div class="t-top"><?= h($trackingLabel !== '' ? $trackingLabel : 'Pending') ?></div>
                <?php if($courierLabel !== ''): ?><div class="t-sub muted"><?= h($courierLabel) ?></div><?php endif; ?>
              <?php endif; ?>
            </td>
            <td>
              <div class="t-top"><?= h($row['last_sync_job']) ?></div>
              <div class="t-sub muted"><?= h(dd($row['last_sync_at'])) ?></div>
              <div class="t-sub muted">D <?= h(dd($row['details_fetched_at'])) ?> / H <?= h(dd($row['history_fetched_at'])) ?></div>
            </td>
            <td>
              <?php foreach(array_slice($reasons, 0, 4) as $reason): ?>
                <span class="badge <?= str_contains($reason, '96h') || str_contains($reason, 'no history') ? 'badge-bad' : 'badge-warn' ?>"><?= h($reason) ?></span>
              <?php endforeach; ?>
            </td>
            <td class="right">
              <a class="btn btn-sm btn-ghost" target="_blank" rel="noopener" href="/cron/run.php?job=watch_tracking&key=<?= urlencode($cronKey) ?>&lead=<?= urlencode($lead) ?>&force=1&limit=1">Check tracking</a>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </form>
</section>

<?php require_once __DIR__ . '/_inc/layout_bottom.php'; ?>
