<div class="container-fluid piutang-page" id="container-wrapper">
  <div class="piutang-page-header">
    <div class="piutang-hero-main">
      <div class="piutang-hero-icon"><i class="fa fa-file-text-o"></i></div>
      <div class="piutang-heading-copy">
        <h1>Laporan Piutang</h1>
        <p>Laporan piutang pelanggan</p>
      </div>
    </div>

    <div class="piutang-summary-card" aria-label="Ringkasan total piutang">
      <div class="piutang-summary-copy">
        <span>Total Piutang</span>
        <strong id="ringkasan-total-piutang">—</strong>
        <small id="ringkasan-sumber">Menunggu data...</small>
      </div>
    </div>

    <div class="piutang-hero-art" aria-hidden="true">
      <i class="fa fa-clipboard"></i>
      <span><i class="fa fa-money"></i></span>
    </div>
  </div>

  <form action="<?=base_url();?>laporan/cetak_piutang" method="post" id="cetak-piutang" target="_blank">
    <div class="piutang-content-card">
      <div class="piutang-filter-section">
        

        <div class="filter-bar">
          <div class="form-group piutang-filter-cashier">
            <label for="user"><i class="fa fa-user-o"></i> KASIR</label>
            <select name="user" id="user" class="form-control custom-select" onchange="search_Piutang()">
              <option value="0">Semua kasir</option>
              <?php
                foreach ($pilihan AS $values){
                  if($this->session->idu==$values['id_user'] AND $level!='admin'){
                    echo '<option value="'.$values['id_user'].'" selected>'.$values['nama_lengkap'].'</option>';
                  }else{
                    echo '<option value="'.$values['id_user'].'">'.$values['nama_lengkap'].'</option>';
                  }
                }
              ?>
            </select>
          </div>

          <div class="form-group piutang-filter-period">
            <label for="periode"><i class="fa fa-calendar"></i> PERIODE</label>
            <input type="text" id="periode" class="form-control date-piutang" name="range" placeholder="Pilih rentang tanggal" onchange="search_Piutang();" />
          </div>

          <div class="form-group piutang-filter-search">
            <label for="keywords_piutang"><i class="fa fa-search"></i> PENCARIAN</label>
            <input type="text" class="form-control" name="keywords" id="keywords_piutang" placeholder="Nomor transaksi atau pelanggan">
          </div>

          <div class="piutang-actions" role="toolbar" aria-label="Aksi laporan piutang">
            <button type="button" data-toggle="tooltip" class="btn piutang-btn piutang-btn-clear clear_piutang" id="clear" data-original-title="Bersihkan filter">
              <i class="fa fa-times"></i><span>Clear</span>
            </button>
            <button type="button" data-info="cari" class="btn piutang-btn piutang-btn-primary cari_piutang" data-id="0">
              <i class="fa fa-search"></i><span>Cari</span>
            </button>
            <button class="btn piutang-btn piutang-btn-print print_pdf_piutang" data-url="piutang" type="button" data-toggle="tooltip" data-original-title="Cetak Piutang" data-placement="left">
              <i class="fa fa-file-pdf-o"></i><span>Print</span>
            </button>
          </div>
        </div>
      </div>

      <div class="piutang-data-section">
        <div class="piutang-data-heading">
          <h2>Daftar Piutang</h2>
          <p>Rincian tagihan pelanggan berdasarkan filter yang dipilih.</p>
        </div>
        <div class="table-responsive">
          <div id="data_piutang"></div>
        </div>
      </div>
    </div>
  </form>
</div>

<!-- Modal WA -->
<div aria-hidden="true" aria-labelledby="myModalLabel" class="modal left fade" id="OpenModalWa" role="dialog" tabindex="-1">
  <div class="modal-dialog modal-dialog-slide" role="document">
    <div class="modal-content flat">
      <div class="modal-header">
        <h4 class="modal-title" id="WaLabel">Kirim Invoice</h4>
        <button aria-label="Close" class="close" data-dismiss="modal" type="button">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="load-data-wa"></div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-success kirim_pesan" type="button"><i class="fa fa-send"></i> Kirim</button> 
        <button class="btn btn-danger" data-dismiss="modal" type="button">Batal</button> 
      </div>
    </div>
  </div>
</div>

<style>
  .piutang-page{
    color:#17233c;
    padding-bottom:28px;
  }
  .piutang-page-header{
    position:relative;
    overflow:hidden;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:20px;
    min-height:96px;
    margin-bottom:16px;
    padding:18px 28px;
    border-radius:14px;
    background:var(--app-theme-color, #124fa8);
    color:var(--app-theme-text-color, #fff);
    box-shadow:0 8px 22px rgba(16,24,40,.16);
  }
  .piutang-hero-main{
    display:flex;
    align-items:center;
    min-width:0;
  }
  .piutang-hero-icon{
    display:flex;
    align-items:center;
    justify-content:center;
    flex:0 0 54px;
    width:54px;
    height:54px;
    margin-right:18px;
    border:1px solid rgba(var(--app-theme-text-rgb, 255,255,255),.55);
    border-radius:13px;
    background:rgba(var(--app-theme-text-rgb, 255,255,255),.12);
    color:var(--app-theme-text-color, #fff);
    font-size:25px;
  }
  .piutang-heading-copy h1{
    margin:0 0 5px;
    color:var(--app-theme-text-color, #fff);
    font-size:26px;
    font-weight:700;
    letter-spacing:-.4px;
  }
  .piutang-filter-heading p,
  .piutang-data-heading p{
    margin:0;
    color:#667085;
    font-size:13px;
  }
  .piutang-heading-copy p{
    margin:0;
    color:rgba(var(--app-theme-text-rgb, 255,255,255),.82);
    font-size:13px;
  }
  .piutang-summary-card{
    position:relative;
    z-index:2;
    display:flex;
    align-items:center;
    justify-content:flex-end;
    min-width:250px;
    margin-right:96px;
    padding:0;
    text-align:right;
  }
  .piutang-hero-art{
    position:absolute;
    right:32px;
    top:8px;
    color:rgba(var(--app-theme-text-rgb, 255,255,255),.30);
    font-size:70px;
    line-height:1;
    transform:rotate(-8deg);
  }
  .piutang-hero-art span{
    position:absolute;
    right:-15px;
    bottom:-2px;
    display:flex;
    align-items:center;
    justify-content:center;
    width:40px;
    height:40px;
    border-radius:50%;
    background:#f59e0b;
    color:#fff;
    font-size:19px;
  }
  .piutang-summary-copy{
    display:flex;
    flex-direction:column;
    min-width:0;
  }
  .piutang-summary-copy span{
    color:rgba(var(--app-theme-text-rgb, 255,255,255),.82);
    font-size:12px;
    font-weight:600;
  }
  .piutang-summary-copy strong{
    margin:1px 0;
    color:var(--app-theme-text-color, #fff);
    font-size:24px;
    line-height:1.2;
  }
  .piutang-summary-copy small{
    color:rgba(var(--app-theme-text-rgb, 255,255,255),.68);
    font-size:10px;
  }
  .piutang-content-card{
    overflow:hidden;
    border:1px solid #dde5ef;
    border-radius:12px;
    background:#fff;
    box-shadow:0 8px 24px rgba(16,24,40,.06);
  }
  .piutang-filter-section{
    padding:18px 20px 20px;
    border-bottom:1px solid #e6ebf2;
    background:#fff;
  }
  .piutang-filter-heading,
  .piutang-data-heading{
    margin-bottom:14px;
  }
  .piutang-filter-heading h2,
  .piutang-data-heading h2{
    margin:0 0 3px;
    color:#17233c;
    font-size:16px;
    font-weight:700;
  }
  .piutang-page .filter-bar{
    display:grid;
    grid-template-columns:minmax(170px,.9fr) minmax(235px,1.15fr) minmax(240px,1.2fr) auto;
    gap:12px;
    align-items:end;
  }
  .piutang-page .form-group{ margin:0; }
  .piutang-page .form-group label{
    display:block;
    margin:0 0 7px;
    color:#344054;
    font-size:12px;
    font-weight:700;
  }
  .piutang-page .form-group label i{
    width:15px;
    color:#1769e8;
    text-align:center;
  }
  .piutang-page .form-control,
  .piutang-page .custom-select{
    width:100%;
    height:42px;
    padding:8px 12px;
    border:1px solid #d5deea;
    border-radius:7px;
    background-color:#fff;
    color:#344054;
    font-size:13px;
    box-shadow:none;
  }
  .piutang-page .custom-select{ padding-right:30px; }
  .piutang-page .form-control:focus,
  .piutang-page .custom-select:focus{
    border-color:#6ea8fe;
    box-shadow:0 0 0 3px rgba(23,105,232,.10);
  }
  .piutang-actions{
    display:flex;
    align-items:center;
    gap:8px;
  }
  .piutang-btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:6px;
    height:42px;
    min-width:78px;
    padding:0 13px;
    border-radius:7px;
    font-size:12px;
    font-weight:700;
    line-height:1;
    box-shadow:0 2px 5px rgba(16,24,40,.08);
  }
  .piutang-btn-clear{
    border:1px solid #f3b5ba;
    background:#fff;
    color:#dc3545;
  }
  .piutang-btn-clear:hover{ background:#fff5f5; color:#bd2130; }
  .piutang-btn-primary{
    border:1px solid #1769e8;
    background:#1769e8;
    color:#fff;
  }
  .piutang-btn-primary:hover{ background:#0f58c7; color:#fff; }
  .piutang-btn-print{
    border:1px solid #159b60;
    background:#159b60;
    color:#fff;
  }
  .piutang-btn-print:hover{ background:#0f8050; color:#fff; }

  /* Tiga filter desktop/tablet mengikuti gaya halaman Kategori Produk */
  @media (min-width:768px){
    .piutang-page .filter-bar{
      gap:.5rem;
      align-items:center;
    }

    .piutang-page .piutang-filter-cashier,
    .piutang-page .piutang-filter-period{
      display:flex;
      align-items:stretch;
      min-width:0;
    }

    .piutang-page .piutang-filter-cashier > label,
    .piutang-page .piutang-filter-period > label{
      display:inline-flex;
      align-items:center;
      justify-content:center;
      min-height:36px;
      margin:0;
      padding:.25rem .5rem;
      background:var(--app-theme-color, #3f51b5);
      border:1px solid var(--app-theme-color, #3f51b5);
      border-radius:.2rem 0 0 .2rem;
      color:var(--app-theme-text-color, #fff);
      font-size:.8rem;
      font-weight:500;
      line-height:1.5;
      white-space:nowrap;
      box-shadow:0 .125rem .25rem rgba(58,59,69,.2);
    }

    .piutang-page .piutang-filter-cashier > label i,
    .piutang-page .piutang-filter-period > label i{
      display:none;
    }

    .piutang-page .piutang-filter-cashier > .form-control,
    .piutang-page .piutang-filter-period > .form-control{
      flex:1 1 auto;
      min-width:0;
      height:36px;
      min-height:36px;
      border-color:#d1d3e2;
      border-left:0;
      border-radius:0 .2rem .2rem 0;
      color:#344054;
      font-size:.875rem;
      font-weight:500;
      box-shadow:none;
    }

    .piutang-page .piutang-filter-cashier > .custom-select{
      padding-right:1.75rem;
    }

    .piutang-page .piutang-filter-search > label{
      display:none;
    }

    .piutang-page .piutang-filter-search > .form-control{
      height:36px;
      min-height:36px;
      border-color:#d1d3e2;
      border-radius:.2rem;
      color:#344054;
      font-size:.875rem;
      font-weight:500;
      box-shadow:none;
    }

    .piutang-page .piutang-filter-cashier > .form-control:focus,
    .piutang-page .piutang-filter-period > .form-control:focus,
    .piutang-page .piutang-filter-search > .form-control:focus{
      border-color:var(--app-theme-color, #3f51b5);
      box-shadow:0 0 0 .15rem rgba(63,81,181,.18);
    }
  }

  .piutang-data-section{
    padding:18px 16px 16px;
    background:#fff;
  }
  .piutang-data-heading{ padding:0 4px; }
  .piutang-table-wrap{
    min-width:1120px;
    overflow:hidden;
    border:1px solid #dfe6ef;
    border-radius:9px;
    background:#fff;
  }
  .piutang-page .piutang-table{
    width:100%;
    color:#344054;
    font-size:12px;
  }
  .piutang-page .piutang-table thead th{
    padding:11px 9px;
    border-top:0;
    border-bottom:1px solid #d8e1ed;
    background:#f2f6fc;
    color:#344054;
    font-size:12px;
    font-weight:700;
    white-space:nowrap;
    vertical-align:middle;
  }
  .piutang-page .piutang-table tbody td{
    padding:11px 9px;
    border-top:0;
    border-bottom:1px solid #e7ecf3;
    background:#fff;
    color:#475467;
    font-size:12px;
    vertical-align:middle;
  }
  .piutang-page .piutang-table tbody tr:nth-child(even) td{ background:#fbfcfe; }
  .piutang-page .piutang-table tbody tr:hover td{ background:#f7faff; }
  .piutang-page .piutang-table tfoot th{
    padding:12px 9px;
    border:0;
    border-top:1px solid #c9d9ed;
    background:#eaf3ff;
    color:#175fc2;
    font-size:12px;
    font-weight:800;
    vertical-align:middle;
  }
  .piutang-page .piutang-table a.kirim_wa{
    color:#159b60!important;
    font-weight:600;
    text-decoration:none;
  }
  .piutang-page .piutang-table a.kirim_wa:hover{ color:#0f8050!important; }
  .piutang-trx-code{
    display:inline-block;
    padding:4px 7px;
    border:1px solid #cfe0f8;
    border-radius:5px;
    background:#edf5ff;
    color:#1769e8;
    font-weight:700;
    white-space:nowrap;
  }
  .piutang-pay-btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:5px;
    min-height:32px;
    padding:6px 10px;
    border:1px solid #1769e8;
    border-radius:6px;
    background:#1769e8;
    color:#fff;
    font-size:12px;
    font-weight:700;
    line-height:1;
    white-space:nowrap;
    box-shadow:none;
  }
  .piutang-pay-btn:hover{ background:#0f58c7; color:#fff; }
  .piutang-page .piutang-table th,
  .piutang-page .piutang-table td,
  .piutang-page .piutang-table a,
  .piutang-page .piutang-table span,
  .piutang-page .piutang-table button{
    font-size:14px!important;
  }

  .piutang-page button,
  .piutang-page input,
  .piutang-page select,
  .piutang-page textarea{
    font-family:inherit;
  }

  /* Modal slide-in (kiri), responsif */
  .modal.left .modal-dialog{
    position: fixed;
    margin: auto;
    width: 420px;
    max-width: 95vw;
    height: 100%;
    transform: translate3d(0, 0, 0);
    right: auto;
    left: 0;
  }
  .modal.left .modal-content{
    height: 100%;
    overflow-y: auto;
    border-radius: 0;
  }
  .modal.left.fade .modal-dialog{
    -webkit-transition: opacity .3s linear, left .3s ease-out;
    -moz-transition: opacity .3s linear, left .3s ease-out;
    -o-transition: opacity .3s linear, left .3s ease-out;
    transition: opacity .3s linear, left .3s ease-out;
  }
  .modal.left.fade.show .modal-dialog{ left: 0; }

  @media (max-width:1199.98px){
    .piutang-page .filter-bar{
      grid-template-columns:repeat(2,minmax(0,1fr));
    }
    .piutang-actions{ justify-content:flex-start; }
  }
  @media (max-width:767.98px){
    .piutang-page-header{
      align-items:stretch;
      flex-direction:column;
      padding:16px 18px;
    }
    .piutang-summary-card{
      justify-content:flex-start;
      min-width:0;
      margin-right:0;
      padding-left:64px;
      text-align:left;
    }
    .piutang-hero-art{ display:none; }
    .piutang-page .filter-bar{ grid-template-columns:1fr; }
    .piutang-actions{ display:grid; grid-template-columns:repeat(3,1fr); }
    .piutang-btn{ width:100%; }
  }
  @media (max-width:575.98px){
    .piutang-heading-copy h1{ font-size:22px; }
    .piutang-hero-icon{
      flex-basis:46px;
      width:46px;
      height:46px;
      margin-right:13px;
    }
    .piutang-summary-card{ padding-left:59px; }
    .piutang-filter-section{ padding:16px 14px; }
    .piutang-data-section{ padding:16px 10px 12px; }
    .piutang-actions{ grid-template-columns:1fr; }
  }
</style>

<script>
  // ==== FIX UTAMA: pastikan global, dipasang sedini mungkin ====
  // Jika file lain memanggil searchFilter(), pastikan selalu ada.
  if (typeof window.searchFilter !== 'function') {
    window.searchFilter = function () {
      // Default: trigger pencarian ulang (bisa diubah sesuai kebutuhan)
      var $btn = $('.cari_piutang');
      if ($btn.length) $btn.click();
    };
  }

  // ============ UTIL DASAR, AMAN DARI TIPE ============
  function toStr(v){ try{ return (v===null||v===undefined) ? '' : String(v); }catch(e){ return ''; } }

  // Ubah apa pun (string/number/element text) menjadi INTEGER rupiah (tanpa desimal)
  // Menerima format "Rp 1.234.567,89" / "1.234.567" / 1234567 / dsb.
  function toIntRupiah(value){
    var s = toStr(value);
    if(!s) return 0;
    // bersihkan: buang semua selain digit, titik, koma
    s = s.replace(/[^\d\.,]/g,'');
    // hapus titik ribuan (titik yang diikuti 3 digit di akhir kelompok)
    s = s.replace(/\.(?=\d{3}\b)/g,'');
    // buang desimal (koma + digit)
    s = s.replace(/\,\d+$/,'');
    // sisakan digit saja
    var digits = s.replace(/\D/g,'');
    if(!digits) return 0;
    var n = parseInt(digits,10);
    return isFinite(n) && n>0 ? n : 0;
  }

  // Format integer → "Rp x.xxx.xxx"
  function formatRp(n){
    var num = parseInt(n,10);
    if(!isFinite(num) || num<0) num = 0;
    var s = String(num);
    var rev = s.split('').reverse().join('');
    var chunks = rev.match(/\d{1,3}/g) || ['0'];
    var withDots = chunks.join('.').split('').reverse().join('');
    return 'Rp ' + withDots;
  }

  // ============ AUTOCOMPLETE KEYWORDS ============
  $("#keywords_piutang").autocomplete({
    source: function (request, response) {
      $.ajax({
        url: base_url + "pembukuan/cari",
        dataType: "json",
        method: "POST",
        data: { name_startsWith: request.term, type: "data_table", row_num: 1 },
        success: function (data) {
          response($.map(data, function (item) {
            var code = item.split("|");
            return { label: code[0], value: code[0], data: item };
          }));
        },
        error: function (xhr, ajaxOptions, thrownError) {
          sweet("Peringatan!!!", thrownError, "warning", "warning");
        },
      });
    },
    autoFocus: true,
    minLength: 0,
    select: function (event, ui) {
      var names = ui.item.data.split("|");
      $("#keywords_piutang").val(names[0]);
    }
  });

  // ============ DATERANGE PICKER ============
  $('.date-piutang').daterangepicker({
    autoApply: true,
    dateLimit: { days: 120 },
    alwaysShowCalendars: true,
    startDate: moment().startOf('month'),
    endDate: (typeof end!=='undefined'? end : moment()), // guard jika 'end' tidak ada
    opens: "left",
    locale: { format: 'DD/MM/YYYY' },
    ranges: {
      'Hari ini': [moment(), moment()],
      'Kemarin': [moment().subtract(1,'day'), moment()],
      'Minggu Ini': [moment().startOf('isoWeek'), moment()],
      '7 Hari Terakhir': [moment().subtract(6,'day'), moment()],
      'Bulan ini': [moment().startOf('month'), moment()],
      'Bulan sebelumnya': [
        moment().startOf('month').subtract(1,'month'),
        moment().startOf('month').subtract(1,'day')
      ],
      'Tahun ini': [moment().startOf('year'), moment()],
    }
  });

  // ============ WA ============
  $(".kirim_pesan").click(function(e) {
    var dataform = $("#form-wa").serialize();
    $.ajax({
      type: "POST",
      url: base_url+"whatsapp/kirim_pesan",
      dataType: 'json',
      data: dataform,
      cache: false,
      beforeSend: function () { $('body').loading(); },
      success: handleKirim,
      error: function(xhr, status, error) {
        showNotif('top-right','Simpan data',error,'error');
        $('body').loading('stop');
      }
    });
  });

  function handleKirim(data) {
    $('#OpenModalWa').modal('hide'); 
    if(data && data.status===true){
      showNotif('bottom-right','Simpan data',data.msg && data.msg.detail ? data.msg.detail : 'Terkirim','success');
    }else{
      var number = (data && data.target) ? data.target : '';
      var message = encodeURIComponent(data && data.msg ? data.msg : '');
      window.open('https://wa.me/' + number + '?text=' + message, '_blank');
    }
  }

  // ============ INIT ============
  $(document).ready(function() {
    $(".cari_piutang").trigger('click');
  });

  function search_Piutang(){ $(".cari_piutang").click(); }

  // ============ AJAX & RINGKASAN ============
  $(document).on('click','.cari_piutang',function(e){
    e.preventDefault();
    var info = $(this).attr('data-info');
    var user = $("#user").val();
    var periode = $("#periode").val();
    var keywords = $("#keywords_piutang").val();

    $.ajax({
      url: base_url + 'pembukuan/cari_piutang',
      data: {user:user,periode:periode,info:info,keywords:keywords},
      method: 'POST',
      beforeSend: function () { $('body').loading(); },
      success: function(html) {
        $("#data_piutang").html(html);
        $("#rekapan").attr('disabled',false);
        $('body').loading('stop');

        // Update ringkasan
        updateRingkasanPiutang(html);
      },
      error: function (xhr, ajaxOptions, thrownError) {
        sweet('Peringatan!!!',thrownError,'warning','warning');
        $('body').loading('stop');
      }
    });
  });

  $(document).on('click','.clear_piutang',function(e){
    e.preventDefault();
    $('#user').val(0);
    $('#periode').val('');
    $('#keywords_piutang').val('');
    $(".cari_piutang").click();
  });

  $(document).on('click','.print_pdf_piutang',function(e){
    e.preventDefault();
    $("#cetak-piutang").submit();
  });

  // =========================
  //  RINGKASAN TOTAL PIUTANG
  // =========================
  function updateRingkasanPiutang(html){
    var $temp = $('<div/>').html(toStr(html));

    // 1) Coba baca dari penanda total yang disediakan server
    var $mark = $temp.find('#total_piutang, .total-piutang, [data-role="piutang-total"]');
    if($mark.length){
      var raw = $mark.first().attr('data-total');
      if(!raw) raw = $mark.first().text();
      var total = toIntRupiah(raw);
      applyRingkasan(total, 'dari elemen total');
      return;
    }

    // 2) Hitung dari kolom "Piutang"
    var sum = sumPiutangFromTables($temp);
    if(sum !== null){
      applyRingkasan(sum, 'dihitung dari kolom "Piutang"');
      return;
    }

    // 3) Fallback: coba cari teks "Total Piutang" di konten
    var teks = toStr($temp.text()).replace(/\s+/g,' ');
    var m = teks.match(/total\s*piutang[^0-9Rp]*((Rp)?\s?[\d\.\,]+)/i);
    if(m && m[1]){
      applyRingkasan(toIntRupiah(m[1]), 'dari konten tabel');
      return;
    }

    // 4) Tidak ketemu apa pun
    $('#ringkasan-total-piutang').text('—');
    $('#ringkasan-sumber').text('total tidak ditemukan');
  }

  // Menjumlah kolom "Piutang" dari semua tabel di partial
  function sumPiutangFromTables($container){
    var total = 0, found = false;
    var $tables = $container.find('table');
    if($tables.length===0) return null;

    $tables.each(function(){
      var $t = $(this);
      var col = findPiutangColIndex($t);
      if(col === -1) return;

      // baris data
      var $rows = $t.find('tbody tr');
      if($rows.length===0){
        $rows = $t.find('tr').not('thead tr, tfoot tr');
      }
      var sub = 0;
      $rows.each(function(){
        var txt = getCellTextByIndexWithColspan($(this), col);
        var v = toIntRupiah(txt);
        if(isFinite(v)) sub += v;
      });

      if(sub>0){ total += sub; found = true; }
    });

    return found ? total : null;
  }

  function findPiutangColIndex($table){
    var $ths = $table.find('thead th');
    if($ths.length===0){
      var $first = $table.find('tr').first();
      $ths = $first.find('th');
    }
    if($ths.length===0) return -1;
    var idx = -1;
    $ths.each(function(i){
      var txt = toStr($(this).text()).trim().toLowerCase();
      if(/piutang/i.test(txt)){ idx = i; return false; }
    });
    return idx;
  }

  function getCellTextByIndexWithColspan($tr, targetIndex){
    var current = 0, out = '';
    $tr.children('td,th').each(function(){
      var span = parseInt($(this).attr('colspan')||'1',10);
      var start = current, end = current + span - 1;
      if(targetIndex >= start && targetIndex <= end){
        out = toStr($(this).text()).trim();
        return false;
      }
      current += span;
    });
    return out;
  }

  function applyRingkasan(totalInt, sumber){
    var formatted = formatRp(totalInt);
    $('#ringkasan-total-piutang').text(formatted);
    $('#ringkasan-sumber').text(sumber||'');
  }
</script>
