<?php $this->load->helper('az_core'); if(!function_exists('rp_p')){ function rp_p($x){ return number_format((float)round($x),0,',','.'); } } ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Status Piutang</title>
<style type="text/css">
  :root{
    --ink:#1f2733; --muted:#6b7686; --line:#e3e8ef; --bg:#eef2f7;
    --red:#d6453f; --redbg:#fdeceb; --green:#1f9d63; --greenbg:#e9f7f0;
    --blue:#2f6fb0; --bluebg:#eaf2fa; --amber:#c9821a; --amberbg:#fdf3e2;
  }
  *{box-sizing:border-box;}
  body{margin:0;background:var(--bg);color:var(--ink);
       font-family:Arial,Helvetica,sans-serif;font-size:12px;}
  h1,h2,h3{font-family:'Trebuchet MS','Segoe UI',system-ui,sans-serif;margin:0;}
  .wrap{max-width:1180px;margin:0 auto;padding:18px;}

  /* toolbar */
  .toolbar{display:flex;flex-wrap:wrap;gap:8px;align-items:center;
           background:#fff;border:1px solid var(--line);border-radius:12px;
           padding:12px 14px;margin-bottom:16px;box-shadow:0 2px 10px rgba(31,39,51,.05);}
  .toolbar button{border:0;border-radius:9px;padding:9px 15px;font-size:13px;font-weight:700;
           cursor:pointer;color:#fff;display:inline-flex;align-items:center;gap:7px;
           transition:transform .12s ease, box-shadow .12s ease, filter .12s ease;}
  .toolbar button:hover{transform:translateY(-2px);box-shadow:0 6px 16px rgba(31,39,51,.18);filter:brightness(1.05);}
  .toolbar button:active{transform:translateY(0);}
  .b-print{background:var(--blue);} .b-pdf{background:#7a4fb0;} .b-xls{background:var(--green);}
  .b-toggle{background:#56657a;margin-left:auto;}
  .hint{width:100%;color:var(--muted);font-size:11px;margin-top:2px;}

  /* header */
  .head{background:linear-gradient(120deg,#243447,#33506e);color:#fff;border-radius:14px;
        padding:20px 22px;margin-bottom:16px;box-shadow:0 6px 20px rgba(36,52,71,.25);}
  .head h1{font-size:24px;letter-spacing:.3px;}
  .head .sub{font-size:13px;opacity:.92;margin-top:4px;}
  .head .meta{margin-top:10px;font-size:11px;opacity:.85;line-height:1.6;}
  .head .def{margin-top:10px;background:rgba(255,255,255,.12);border-radius:8px;
             padding:7px 10px;font-size:11px;line-height:1.5;}

  /* KPI */
  .kpis{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:16px;}
  .kpi{background:#fff;border:1px solid var(--line);border-left:5px solid var(--blue);
       border-radius:12px;padding:13px 14px;box-shadow:0 2px 8px rgba(31,39,51,.05);
       transition:transform .12s ease, box-shadow .12s ease;}
  .kpi:hover{transform:translateY(-3px);box-shadow:0 10px 22px rgba(31,39,51,.12);}
  .kpi .lbl{font-size:10.5px;text-transform:uppercase;letter-spacing:.6px;color:var(--muted);font-weight:700;}
  .kpi .val{font-family:'Trebuchet MS',system-ui,sans-serif;font-size:23px;font-weight:800;margin-top:5px;line-height:1.1;}
  .kpi .ext{font-size:10.5px;color:var(--muted);margin-top:3px;}
  .kpi.red{border-left-color:var(--red);} .kpi.red .val{color:var(--red);}
  .kpi.green{border-left-color:var(--green);} .kpi.green .val{color:var(--green);}
  .kpi.amber{border-left-color:var(--amber);} .kpi.amber .val{color:var(--amber);}

  .card{background:#fff;border:1px solid var(--line);border-radius:12px;padding:14px 16px;
        margin-bottom:16px;box-shadow:0 2px 8px rgba(31,39,51,.05);}
  .card h2{font-size:14px;margin-bottom:10px;display:flex;align-items:center;gap:8px;}
  .card h2 .dot{width:9px;height:9px;border-radius:50%;display:inline-block;}
  .two{display:grid;grid-template-columns:1.3fr 1fr;gap:16px;}

  table{border-collapse:collapse;width:100%;font-size:11.5px;}
  th,td{border:1px solid var(--line);padding:5px 7px;vertical-align:top;}
  thead th{background:#f3f6fa;text-align:center;font-weight:700;}
  td.r,th.r{text-align:right;} td.c,th.c{text-align:center;}
  tfoot td{background:#f7f9fc;font-weight:800;}
  tr.grp td{background:var(--blue);color:#fff;font-weight:800;border-color:var(--blue);}
  tr.grp.green td{background:var(--green);border-color:var(--green);}
  tr.grp td .sub{float:right;font-weight:700;}
  tr.subtot td{background:var(--redbg);font-weight:800;}
  tr.subtot.green td{background:var(--greenbg);}
  .pill{display:inline-block;padding:1px 8px;border-radius:20px;font-size:10px;font-weight:700;}
  .pill.red{background:var(--redbg);color:var(--red);} .pill.green{background:var(--greenbg);color:var(--green);}
  .pill.amber{background:var(--amberbg);color:var(--amber);} .pill.grey{background:#eef1f5;color:#56657a;}
  .sisa{color:var(--red);font-weight:800;}
  .aging-bar{height:8px;border-radius:5px;background:var(--red);display:inline-block;vertical-align:middle;}
  .hidden{display:none !important;}
  .empty{color:var(--muted);text-align:center;padding:10px;}

  @media (max-width:820px){ .kpis{grid-template-columns:repeat(2,1fr);} .two{grid-template-columns:1fr;} }

  @media print{
    .toolbar{display:none !important;}
    body{background:#fff;} .wrap{max-width:none;padding:0;}
    .kpi,.card,.head{box-shadow:none;}
    .kpi:hover{transform:none;}
    @page{margin:8mm;}
    table{font-size:9.5px;} th,td{padding:3px 4px;}
    .kpi .val{font-size:16px;}
  }
</style>
</head>
<body>
<div class="wrap">

  <div class="toolbar no-print">
    <button type="button" class="b-print" onclick="window.print();">🖨 Cetak</button>
    <button type="button" class="b-pdf"   onclick="window.print();">📄 Download PDF</button>
    <button type="button" class="b-xls"   onclick="exportExcelPiutang();">📊 Export Excel</button>
    <button type="button" class="b-toggle" id="btnToggleLunas" onclick="toggleLunas();">👁 Tampilkan Bill Lunas (<?php echo $n_lunas_all;?>)</button>
    <div class="hint">💡 PDF: pada dialog cetak pilih tujuan <b>“Save as PDF”</b>. Tips cetak: pilih orientasi <b>Landscape</b> agar kolom lega.</div>
  </div>

  <div id="printArea">

    <div class="head">
      <h1>📊 STATUS PIUTANG — <?php echo strtoupper($outlet_title);?></h1>
      <div class="sub">Periode <?php echo (strlen($date_1)?$date_1:'...').' s/d '.(strlen($date_2)?$date_2:'...');?></div>
      <div class="meta">Dicetak: <?php echo $tanggal_cetak;?> &nbsp;|&nbsp; Total Bill: <?php echo $g['n_total'];?> &nbsp;|&nbsp; Bill Piutang: <?php echo $g['n_piutang'];?> &nbsp;|&nbsp; Bill Lunas: <?php echo $g['n_lunas'];?></div>
      <div class="def"><b>Definisi:</b> Piutang = sisa tagihan yang belum dibayar. CASH = lunas di depan. PANJAR/BELUM BAYAR = piutang sebesar (tagihan − panjar − pelunasan pickup). Umur dihitung sejak <b>tgl masuk</b>. Nilai dibulatkan ke rupiah terdekat.</div>
    </div>

    <!-- KPI GLOBAL -->
    <div class="kpis">
      <div class="kpi red"><div class="lbl">Total Piutang (Sisa)</div><div class="val">Rp <?php echo rp_p($g['sum_sisa']);?></div><div class="ext"><?php echo $g['n_piutang'];?> bill masih nunggak</div></div>
      <div class="kpi green"><div class="lbl">Sudah Terbayar</div><div class="val">Rp <?php echo rp_p($g['sum_tagihan_total']-$g['sum_sisa']);?></div><div class="ext">dari total tagihan Rp <?php echo rp_p($g['sum_tagihan_total']);?></div></div>
      <div class="kpi amber"><div class="lbl">Rasio Piutang</div><div class="val"><?php echo $g['ratio'];?>%</div><div class="ext">penjualan belum jadi uang</div></div>
      <div class="kpi"><div class="lbl">Total Tagihan</div><div class="val">Rp <?php echo rp_p($g['sum_tagihan_total']);?></div><div class="ext"><?php echo $g['n_total'];?> bill (lunas + piutang)</div></div>
      <div class="kpi amber"><div class="lbl">Umur Rata‑rata Piutang</div><div class="val"><?php echo $g['avg_umur'];?> hr</div><div class="ext">tertua <?php echo $g['max_umur'];?> hari</div></div>
      <div class="kpi red"><div class="lbl">Total Hari‑Piutang</div><div class="val"><?php echo rp_p($g['sum_umur']);?></div><div class="ext">akumulasi umur semua bill nunggak</div></div>
      <div class="kpi red"><div class="lbl">Lewat Jatuh Tempo</div><div class="val"><?php echo $g['n_lewat'];?> bill</div><div class="ext">nilai Rp <?php echo rp_p($g['sum_sisa_lewat']);?> (berisiko)</div></div>
      <div class="kpi green"><div class="lbl">Bill Lunas</div><div class="val"><?php echo $g['n_lunas'];?></div><div class="ext">tagihan Rp <?php echo rp_p($g['sum_tagihan_l']);?></div></div>
    </div>

    <div class="two">
      <!-- RINGKASAN PER OUTLET -->
      <div class="card">
        <h2><span class="dot" style="background:var(--blue)"></span> Ringkasan Piutang per Outlet</h2>
        <table>
          <thead><tr><th>Outlet</th><th class="c">Bill Ptg</th><th class="r">Nilai Piutang</th><th class="c">Bill Lunas</th><th class="r">Tagihan Lunas</th><th class="c">Rata Umur</th><th class="c">% Ptg</th></tr></thead>
          <tbody>
          <?php foreach ($groups as $gr){ $m=$gr['m']; ?>
            <tr>
              <td><b><?php echo htmlspecialchars((string)$gr['outlet_name']);?></b></td>
              <td class="c"><?php echo $m['n_piutang'];?></td>
              <td class="r sisa"><?php echo rp_p($m['sum_sisa']);?></td>
              <td class="c"><?php echo $m['n_lunas'];?></td>
              <td class="r"><?php echo rp_p($m['sum_tagihan_l']);?></td>
              <td class="c"><?php echo $m['avg_umur'];?> hr</td>
              <td class="c"><?php echo $m['ratio'];?>%</td>
            </tr>
          <?php } ?>
          </tbody>
          <tfoot><tr>
            <td>TOTAL</td><td class="c"><?php echo $g['n_piutang'];?></td><td class="r sisa"><?php echo rp_p($g['sum_sisa']);?></td>
            <td class="c"><?php echo $g['n_lunas'];?></td><td class="r"><?php echo rp_p($g['sum_tagihan_l']);?></td>
            <td class="c"><?php echo $g['avg_umur'];?> hr</td><td class="c"><?php echo $g['ratio'];?>%</td>
          </tr></tfoot>
        </table>
      </div>

      <!-- AGING -->
      <div class="card">
        <h2><span class="dot" style="background:var(--amber)"></span> Umur Piutang (Aging)</h2>
        <table>
          <thead><tr><th>Kelompok Umur</th><th class="c">Bill</th><th class="r">Nilai Piutang</th><th style="width:34%">Distribusi</th></tr></thead>
          <tbody>
          <?php $maxsum=1; foreach($aging as $a){ if($a['sum']>$maxsum)$maxsum=$a['sum']; }
                foreach ($aging as $a){ $w = ($maxsum>0)? round($a['sum']/$maxsum*100):0; ?>
            <tr>
              <td><b><?php echo $a['label'];?></b></td>
              <td class="c"><?php echo $a['n'];?></td>
              <td class="r sisa"><?php echo rp_p($a['sum']);?></td>
              <td><span class="aging-bar" style="width:<?php echo $w;?>%"></span></td>
            </tr>
          <?php } ?>
          </tbody>
        </table>
        <div class="hint" style="margin-top:8px">Makin kanan (makin tua) = makin perlu segera ditagih.</div>
      </div>
    </div>

    <!-- TOP PENUNGGAK -->
    <div class="card">
      <h2><span class="dot" style="background:var(--red)"></span> Top 10 Pelanggan Penunggak Terbesar</h2>
      <?php if (count($top)==0){ echo '<div class="empty">Tidak ada piutang pada periode ini. 🎉</div>'; } else { ?>
      <table>
        <thead><tr><th class="c" width="30">No</th><th>Nama Pelanggan</th><th>No. Telepon</th><th class="c">Jml Bill</th><th class="r">Total Nunggak</th></tr></thead>
        <tbody>
        <?php 
        $top_customers = (isset($top_customers) && is_array($top_customers)) ? $top_customers : [];
if (count($top_customers) === 0): ?>
    <tr><td colspan="7" align="center"><i>Tidak ada data penunggak.</i></td></tr>
<?php else:
    $no = 0;
    foreach ($top_customers as $row): $no++; ?>
    <tr>
        <td align="center"><?php echo $no; ?></td>
        <td><?php echo htmlspecialchars($row['customer_name']); ?></td>
        <td><?php echo htmlspecialchars($row['phone']); ?></td>
        <td align="center"><?php echo $row['jml_bill']; ?></td>
        <td align="right"><?php echo number_format($row['total_piutang'],0,',','.'); ?></td>
        <!-- kolom lain sesuai tabel Anda -->
    </tr>
<?php endforeach; endif; ?>
        </tbody>
      </table>
      <?php } ?>
    </div>

    <!-- DETAIL PIUTANG PER OUTLET -->
    <div class="card">
      <h2><span class="dot" style="background:var(--red)"></span> Rincian Bill MASIH PIUTANG (per Outlet)</h2>
      <table>
        <thead><tr>
          <th class="c" width="26">No</th><th>Kode Bill</th><th class="c">Tgl Masuk</th><th class="c">Umur</th>
          <th>Nama Pelanggan</th><th>No. Telepon</th><th class="r">Tagihan</th><th class="r">Sudah Bayar</th>
          <th class="r">Sisa Piutang</th><th>Posisi</th><th class="c">Status</th>
        </tr></thead>
        <tbody>
        <?php
        if ($g['n_piutang']==0){ echo "<tr><td colspan='11' class='empty'>Tidak ada bill piutang pada periode ini.</td></tr>"; }
        foreach ($groups as $gr){
          if (count($gr['piutang'])==0) continue;
          $sp=0; $st=0; $ss=0;
          echo "<tr class='grp'><td colspan='11'>📍 ".htmlspecialchars((string)$gr['outlet_name'])." <span class='sub'>Piutang: ".count($gr['piutang'])." bill &nbsp;|&nbsp; Rp ".rp_p($gr['m']['sum_sisa'])."</span></td></tr>";
          $no=0;
          foreach ($gr['piutang'] as $b){ $no++; $sp+=$b['tagihan']; $ss+=$b['sudah']; $st+=$b['sisa'];
            $umur_pill = ($b['umur']!=='-' && $b['umur']>30)?'amber':(($b['umur']!=='-' && $b['umur']>14)?'amber':'grey');
        ?>
          <tr>
            <td class="c"><?php echo $no;?></td>
            <td><?php echo htmlspecialchars((string)$b['code']);?></td>
            <td class="c"><?php echo $b['tgl'];?></td>
            <td class="c"><span class="pill <?php echo $umur_pill;?>"><?php echo $b['umur'];?> hr</span></td>
            <td><?php echo htmlspecialchars((string)$b['customer']);?></td>
            <td><?php echo htmlspecialchars((string)($b['phone']!=''?$b['phone']:'-'));?></td>
            <td class="r"><?php echo rp_p($b['tagihan']);?></td>
            <td class="r"><?php echo rp_p($b['sudah']);?></td>
            <td class="r sisa"><?php echo rp_p($b['sisa']);?></td>
            <td><?php echo htmlspecialchars((string)$b['stock']);?></td>
            <td class="c"><span class="pill red"><?php echo htmlspecialchars((string)$b['pay_status']);?></span></td>
          </tr>
        <?php } ?>
          <tr class="subtot"><td colspan="6" class="r">Sub‑total <?php echo htmlspecialchars((string)$gr['outlet_name']);?> (<?php echo count($gr['piutang']);?> bill)</td>
              <td class="r"><?php echo rp_p($sp);?></td><td class="r"><?php echo rp_p($ss);?></td><td class="r sisa"><?php echo rp_p($st);?></td><td colspan="2"></td></tr>
        <?php } ?>
        </tbody>
      </table>
    </div>

    <!-- DETAIL LUNAS (tersembunyi, bisa dimunculkan) -->
    <div class="lunas-block hidden">
      <div class="card">
        <h2><span class="dot" style="background:var(--green)"></span> Rincian Bill SUDAH LUNAS (per Outlet)</h2>
        <table>
          <thead><tr>
            <th class="c" width="26">No</th><th>Kode Bill</th><th class="c">Tgl Masuk</th>
            <th>Nama Pelanggan</th><th>No. Telepon</th><th class="r">Tagihan</th><th class="r">Dibayar</th>
            <th>Posisi</th><th class="c">Status</th>
          </tr></thead>
          <tbody>
          <?php
          if ($g['n_lunas']==0){ echo "<tr><td colspan='9' class='empty'>Tidak ada bill lunas pada periode ini.</td></tr>"; }
          foreach ($groups as $gr){
            if (count($gr['lunas'])==0) continue;
            $lt=0;
            echo "<tr class='grp green'><td colspan='9'>📍 ".htmlspecialchars((string)$gr['outlet_name'])." <span class='sub'>Lunas: ".count($gr['lunas'])." bill &nbsp;|&nbsp; Rp ".rp_p($gr['m']['sum_tagihan_l'])."</span></td></tr>";
            $no=0;
            foreach ($gr['lunas'] as $b){ $no++; $lt+=$b['tagihan']; ?>
              <tr>
                <td class="c"><?php echo $no;?></td>
                <td><?php echo htmlspecialchars((string)$b['code']);?></td>
                <td class="c"><?php echo $b['tgl'];?></td>
                <td><?php echo htmlspecialchars((string)$b['customer']);?></td>
                <td><?php echo htmlspecialchars((string)($b['phone']!=''?$b['phone']:'-'));?></td>
                <td class="r"><?php echo rp_p($b['tagihan']);?></td>
                <td class="r"><?php echo rp_p($b['sudah']);?></td>
                <td><?php echo htmlspecialchars((string)$b['stock']);?></td>
                <td class="c"><span class="pill green"><?php echo htmlspecialchars((string)$b['pay_status']);?></span></td>
              </tr>
            <?php } ?>
            <tr class="subtot green"><td colspan="5" class="r">Sub‑total <?php echo htmlspecialchars((string)$gr['outlet_name']);?> (<?php echo count($gr['lunas']);?> bill)</td>
                <td class="r"><?php echo rp_p($lt);?></td><td colspan="3"></td></tr>
          <?php } ?>
          </tbody>
        </table>
      </div>
    </div>

  </div><!-- /printArea -->
</div>

<script type="text/javascript">
function toggleLunas(){
  var blk = document.querySelector('.lunas-block');
  var btn = document.getElementById('btnToggleLunas');
  if (blk.classList.contains('hidden')){
    blk.classList.remove('hidden');
    btn.innerHTML = '🙈 Sembunyikan Bill Lunas (<?php echo $n_lunas_all;?>)';
  } else {
    blk.classList.add('hidden');
    btn.innerHTML = '👁 Tampilkan Bill Lunas (<?php echo $n_lunas_all;?>)';
  }
}
function exportExcelPiutang(){
  var area = document.getElementById('printArea').cloneNode(true);
  // sertakan bill lunas di Excel
  var hb = area.querySelectorAll('.lunas-block');
  for (var i=0;i<hb.length;i++){ hb[i].classList.remove('hidden'); }
  var html = area.innerHTML;
  var doc = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>Status Piutang</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>' + html + '</body></html>';
  var blob = new Blob(['\uFEFF' + doc], {type:'application/vnd.ms-excel;charset=utf-8;'});
  var url = URL.createObjectURL(blob);
  var a = document.createElement('a');
  a.href = url;
  a.download = 'Status_Piutang_<?php echo str_replace(' ','_',$outlet_title);?>_<?php echo date('Ymd');?>.xls';
  document.body.appendChild(a); a.click(); document.body.removeChild(a);
  URL.revokeObjectURL(url);
}
</script>
</body>
</html>