<div class="wa-report-table-wrap">
<table class="wa-report-table">
  <thead><tr><th class="wa-report-number">#</th><th class="wa-report-time">Waktu</th><th>Nama Penerima</th><th>No WhatsApp</th><th>Status</th><th>Pesan Terkirim / Keterangan</th><th></th></tr></thead>
  <tbody>
  <?php if (!empty($result)): $no = 1; foreach ($result as $row):
    $statusKey = strtolower(trim((string) $row->status));
    $stateKey = isset($row->state) ? strtolower(trim((string) $row->state)) : '';
    $statusMap = [
      'pending'=>['Menunggu','waiting'],'waiting'=>['Terjadwal','waiting'],'processing'=>['Diproses','waiting'],
      'sent'=>['Terkirim','success'],'delivered'=>['Diterima','success'],'read'=>['Dibaca','success'],
      'invalid'=>['Nomor Tidak Valid','failed'],'expired'=>['Kedaluwarsa','failed'],'failed'=>['Gagal','failed'],'url unreachable'=>['URL Tidak Dapat Diakses','failed']
    ];
    $displayKey = in_array($stateKey, ['read','delivered'], true) ? $stateKey : $statusKey;
    $statusInfo = isset($statusMap[$displayKey]) ? $statusMap[$displayKey] : [ucfirst($displayKey ?: 'Menunggu'),'waiting'];
    $customer = !empty($row->id_konsumen) ? cekKonsumen($row->id_konsumen) : [];
    $name = !empty($customer['nama']) ? $customer['nama'] : 'Penerima';
    $phone = !empty($customer['no_hp']) ? $customer['no_hp'] : $row->target;
    $created = !empty($row->create_date) ? date('d/m/Y H:i', strtotime($row->create_date)) : '-';
  ?>
  <tr data-status="<?=html_escape($displayKey);?>" data-group="<?=$statusInfo[1];?>">
    <td class="wa-report-number"><?=$no;?></td>
    <td class="wa-report-time"><?=html_escape($created);?></td>
    <td class="wa-report-recipient"><b><?=html_escape($name);?></b></td>
    <td class="wa-report-recipient"><small><i class="fa fa-whatsapp text-success"></i> <?=html_escape($phone);?></small></td>
    <td class="wa-report-status">
      <span class="wa-status-badge <?=$statusInfo[1];?>"><?=html_escape($statusInfo[0]);?></span>
      <?php if ($statusKey !== '' && $stateKey !== '' && $stateKey !== $statusKey): ?>
        <small class="wa-report-state"><?=html_escape('Status: '.$statusKey.' · State: '.$stateKey);?></small>
      <?php endif; ?>
    </td>
    <td class="wa-report-message"><?=nl2br(html_escape($row->message));?></td>
    <td class="wa-report-action"><button type="button" class="wa-report-delete" data-id="<?=encrypt_url($row->id);?>" data-konsumen="<?=encrypt_url($row->id_konsumen);?>" data-toggle="modal" data-target="#confirm-delete" title="Hapus"><i class="fa fa-trash"></i></button></td>
  </tr>
  <?php $no++; endforeach; else: ?>
  <tr class="wa-report-empty"><td colspan="7"><i class="fa fa-clock-o"></i>Belum ada riwayat pengiriman pesan pada sesi ini.</td></tr>
  <?php endif; ?>
  </tbody>
</table>
</div>
<nav aria-label="Navigasi halaman" class="wa-report-pagination"><?=$this->ajax_pagination->create_links();?></nav>
