<?php
declare(strict_types=1);

// Helpers compartilhados para as páginas PHP do CRM (layout + dados do mock).

function eaq_load_crm_snapshot(): array {
  $crm = eaq_read_json('mock_crm.json', null);
  if ($crm === null) {
    require_once __DIR__ . '/mock_data.php';
    $crm = eaq_seed_mock_crm();
    eaq_write_json('mock_crm.json', $crm);
  }
  return is_array($crm) ? $crm : [];
}

function eaq_parse_utc_iso(?string $iso): ?DateTimeImmutable {
  if (empty($iso)) return null;
  try {
    return new DateTimeImmutable($iso);
  } catch (Throwable $e) {
    return null;
  }
}

function eaq_format_money_brl($value): string {
  $n = is_numeric($value) ? (float)$value : 0.0;

  $abs = abs($n);
  if ($abs >= 1_000_000) {
    return 'R$ ' . number_format($n / 1_000_000, 1, ',', '.') . 'M';
  }
  if ($abs >= 1_000) {
    return 'R$ ' . number_format($n / 1_000, 1, ',', '.') . 'k';
  }
  return 'R$ ' . number_format($n, 0, ',', '.');
}

function eaq_day_key_utc(DateTimeImmutable $dt): string {
  return $dt->format('Y-m-d');
}

function eaq_relative_due_label(?DateTimeImmutable $due, DateTimeImmutable $now): string {
  if ($due === null) return '—';

  $dueMid = $due->setTime(0, 0, 0);
  $nowMid = $now->setTime(0, 0, 0);
  $diffDays = (int)$dueMid->diff($nowMid)->format('%r%a');

  // Mesmo dia
  if ($diffDays === 0) {
    return 'Hoje ' . $due->format('H') . 'h';
  }
  // Amanhã
  if ($diffDays === 1) {
    return 'Amanhã';
  }
  // Ontem
  if ($diffDays === -1) {
    return 'Ontem';
  }
  // Atrasado (qualquer dia anterior)
  if ($diffDays < -1) {
    return 'Atrasado';
  }

  // Futuro distante
  return $due->format('d/m') ;
}

function eaq_first_open_followup_due_for_opportunity(array $crm, string $opportunityId): ?DateTimeImmutable {
  $now = new DateTimeImmutable('now', new DateTimeZone('UTC'));
  $due = null;

  foreach (($crm['followups'] ?? []) as $fu) {
    if (($fu['IsCompleted'] ?? false)) continue;
    if (($fu['OpportunityId'] ?? '') !== $opportunityId) continue;

    $fuDue = eaq_parse_utc_iso((string)($fu['DueDate'] ?? ''));
    if ($fuDue === null) continue;

    // Escolhe o mais próximo no tempo.
    if ($due === null || $fuDue < $due) {
      $due = $fuDue;
    }
  }

  return $due;
}

function eaq_stage_is_closed(?string $stage): bool {
  return in_array($stage, ['Won', 'Lost'], true);
}

function eaq_compute_readiness_percent_from_session(array $session): int {
  $flags = [
    !empty($session['HasExportPayload']) ? 1 : 0,
    !empty($session['HasHandoffReport']) ? 1 : 0,
    !empty($session['HasShareableSummary']) ? 1 : 0,
    !empty($session['HasQualityAssessment']) ? 1 : 0,
    !empty($session['HasImprovementPlan']) ? 1 : 0,
  ];
  $sum = array_sum($flags);
  return (int)round(($sum / max(1, count($flags))) * 100);
}

function eaq_load_manager_notes(): array {
  $notes = eaq_read_json('manager_notes.json', []);
  return is_array($notes) ? $notes : [];
}

function eaq_save_manager_notes(array $notes): void {
  eaq_write_json('manager_notes.json', $notes);
}

