<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>AI Sales Report</title>
  <style>
    body { font-family: DejaVu Sans, sans-serif; font-size: 12px; color:#111827; line-height:1.45; }
    .header { padding: 14px 16px; background:#111827; color:#fff; border-radius:8px; }
    .meta { font-size: 10px; color:#6b7280; margin-top: 10px; }
    .card { border:1px solid #e5e7eb; border-radius:10px; padding:12px; margin-top:10px; }
    h1 { font-size: 18px; margin: 0; }
    h2 { font-size: 13px; margin: 16px 0 8px; }
    table { width: 100%; border-collapse: collapse; margin-top: 10px; table-layout: fixed; }
    th, td { border: 1px solid #e5e7eb; padding: 6px; text-align: left; vertical-align: top; word-wrap: break-word; }
    th { background: #f3f4f6; font-size: 10.5px; font-weight:700; }
    td { font-size: 10.5px; }
    .text-right { text-align:right; white-space:nowrap; }
    .badge { display:inline-block; padding:2px 8px; border-radius:999px; font-size:10px; border:1px solid #e5e7eb; }
    .muted { color:#6b7280; }
    ul { margin: 6px 0 0 18px; padding:0; }
    li { margin-bottom: 3px; }
  </style>
</head>
<body>
@php
  /*
  |--------------------------------------------------------------------------
  | Sinkron nominal AI Sales Report
  |--------------------------------------------------------------------------
  | - Pembulatan harga/tagihan/omset/laba/piutang ke atas kelipatan Rp1.000.
  | - Tidak membuat minimal Rp10.000 di laporan AI karena template ini hanya
  |   menerima data ringkasan/JSON dan tidak punya info unit meter/m2 per item.
  | - PPN, pajak, tax, kembalian/change, qty, jumlah item tidak ikut dibulatkan.
  */
  $__roundTo = 1000;

  $__formatRupiah = function ($value) {
      return 'Rp ' . number_format((float) $value, 0, ',', '.');
  };

  $__parseNumber = function ($value) {
      if (is_numeric($value)) {
          return (float) $value;
      }

      if (!is_string($value)) {
          return null;
      }

      $text = trim($value);
      if ($text === '') {
          return null;
      }

      $hasMoneyMark = preg_match('/rp|idr|rupiah/i', $text);
      $clean = preg_replace('/[^0-9,\.\-]/', '', $text);
      if ($clean === '' || $clean === '-' || $clean === null) {
          return null;
      }

      if (str_contains($clean, ',') && str_contains($clean, '.')) {
          $clean = str_replace('.', '', $clean);
          $clean = str_replace(',', '.', $clean);
      } elseif ($hasMoneyMark) {
          $clean = str_replace('.', '', $clean);
          $clean = str_replace(',', '.', $clean);
      } elseif (substr_count($clean, '.') > 1) {
          $clean = str_replace('.', '', $clean);
      } elseif (substr_count($clean, ',') > 1) {
          $clean = str_replace(',', '', $clean);
      } elseif (str_contains($clean, ',') && !str_contains($clean, '.')) {
          $clean = str_replace(',', '.', $clean);
      }

      return is_numeric($clean) ? (float) $clean : null;
  };

  $__isMoneyColumn = function ($column, $value) {
      $column = strtolower((string) $column);
      $valueText = strtolower((string) $value);

      $exclude = ['ppn', 'pajak', 'tax', 'kembalian', 'change', 'qty', 'kuantitas', 'jumlah item', 'jumlah order', 'jumlah transaksi', 'jumlah produk', 'persen', '%', 'tanggal', 'date', 'invoice', 'status'];
      foreach ($exclude as $word) {
          if (str_contains($column, $word)) {
              return false;
          }
      }

      if (preg_match('/rp|idr|rupiah/i', $valueText)) {
          return true;
      }

      $include = ['total', 'omset', 'pendapatan', 'revenue', 'penjualan', 'tagihan', 'dibayar', 'bayar', 'sisa', 'piutang', 'laba', 'hpp', 'biaya', 'beban', 'modal', 'harga', 'subtotal', 'grand', 'net', 'amount', 'income', 'profit', 'cost'];
      foreach ($include as $word) {
          if (str_contains($column, $word)) {
              return true;
          }
      }

      return false;
  };

  $__syncDisplayValue = function ($column, $value) use ($__parseNumber, $__isMoneyColumn, $__formatRupiah, $__roundTo) {
      if (is_array($value)) {
          return json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
      }

      if (!$__isMoneyColumn($column, $value)) {
          return $value;
      }

      $number = $__parseNumber($value);
      if ($number === null) {
          return $value;
      }

      if ($number <= 0) {
          return $__formatRupiah(0);
      }

      return $__formatRupiah(ceil($number / $__roundTo) * $__roundTo);
  };
@endphp

<div class="header">
  <h1>{{ $title }}</h1>
  <div class="meta" style="color:#d1d5db;">Generated: {{ $generatedAt }}</div>
</div>

<div class="card">
  <div><span class="badge">Pertanyaan</span></div>
  <div style="margin-top:6px;"><b>{{ $question }}</b></div>

  <h2>Ringkasan AI</h2>
  <div class="muted">{{ $description ?: '-' }}</div>
</div>

@if(!empty($exec))
  <div class="card">
    <h2>Executive Summary</h2>
    <ul>
      @if(!empty($exec['line1'])) <li>{{ $exec['line1'] }}</li> @endif
      @if(!empty($exec['line2'])) <li>{{ $exec['line2'] }}</li> @endif
      @if(!empty($exec['line3'])) <li>{{ $exec['line3'] }}</li> @endif
    </ul>
    @if(!empty($exec['trend_badge']))
      <div class="muted">Trend: <b>{{ $exec['trend_badge'] }}</b></div>
    @endif
  </div>
@endif

<div class="card">
  <h2>Data</h2>

  @if(!empty($rows))
    <table>
      <thead>
        <tr>
          @foreach(array_keys($rows[0]) as $col)
            <th>{{ $col }}</th>
          @endforeach
        </tr>
      </thead>
      <tbody>
        @foreach($rows as $row)
          <tr>
            @foreach($row as $col => $val)
              @php
                $displayVal = $__syncDisplayValue($col, $val);
                $isRight = $__isMoneyColumn($col, $val) && $__parseNumber($val) !== null;
              @endphp
              <td class="{{ $isRight ? 'text-right' : '' }}">{{ $displayVal }}</td>
            @endforeach
          </tr>
        @endforeach
      </tbody>
    </table>
  @else
    <div class="muted">Tidak ada data.</div>
  @endif
</div>

</body>
</html>
