<!-- Container Fluid-->
<div class="container-fluid" id="container-wrapper">
  <style>
    :root{
      --surface: #ffffff;
      --muted: #6b7280;
      --text: #1f2937;
      --brand: #3b82f6;
      --brand-2: #6366f1;
      --ring: rgba(59,130,246,.18);
      --shadow: 0 8px 24px rgba(2,6,23,.06), 0 2px 6px rgba(2,6,23,.06);
      --radius: 18px;
    }

    .card-soft{
      border: 0;
      border-radius: var(--radius);
      background: var(--surface);
      box-shadow: var(--shadow);
      overflow: hidden;
      transition: transform .18s ease, box-shadow .18s ease;
    }
    .card-soft:hover{
      transform: translateY(-1px);
      box-shadow: 0 12px 32px rgba(2,6,23,.10), 0 3px 10px rgba(2,6,23,.06);
    }
    .card-soft .card-body{ padding: 1rem 1.25rem; }
    .card-soft .card-header{
      background: #fff;
      border: 0;
      padding: .9rem 1rem;
    }

    .kpi{
      display:flex;
      align-items:center;
      justify-content:space-between;
      gap:.75rem;
      min-height:86px;
    }
    .kpi .label{
      font-size:.72rem;
      text-transform:uppercase;
      letter-spacing:.5px;
      color:var(--muted);
      margin-bottom:.25rem;
    }
    .kpi .value{
      font-size:1.8rem;
      font-weight:800;
      color:var(--text);
      line-height:1;
      word-break: break-word;
    }
    .kpi .badge-icon{
      width:50px;
      height:50px;
      border-radius:16px;
      display:grid;
      place-items:center;
      background: radial-gradient(120% 120% at 0% 0%, var(--brand) 0%, var(--brand-2) 100%);
      color:#fff;
      box-shadow: 0 10px 22px var(--ring);
    }
    .kpi .badge-icon i{ font-size:1.15rem; }

    .header-wrap{
      display:flex;
      align-items:center;
      justify-content:space-between;
      gap:.75rem;
      flex-wrap:wrap;
    }
    .header-wrap h6{
      margin:0;
      font-weight:800;
      color:var(--text);
      letter-spacing:.2px;
    }

    /* Right actions untuk header card (Produk Terlaris) */
    .header-actions{
      display:flex;
      align-items:center;
      justify-content:flex-end;
      flex-wrap:wrap;
    }
    .header-actions > *{ margin-left:.5rem; }
    .header-actions > *:first-child{ margin-left:0; }
    .header-actions small{ white-space:nowrap; }


    .btn-pill{ border-radius: 999px!important; }
    .btn-light-soft{
      background:#f8fafc;
      border:1px solid #e5e7eb;
      color:#111827;
    }
    .btn-light-soft:hover{ background:#eef2f7; }

    .dropdown-menu{
      max-height:60vh;
      overflow:auto;
      border-radius:14px;
    }
    .dropdown-item.active,
    .dropdown-item:active{
      background:rgba(59,130,246,.12);
      color:#111827;
    }

    /* tombol range biar rapih di header */
    .range-dd .btn-range{ white-space: nowrap; }


    /* =========================================================
       FIX KHUSUS: GRAFIK + INVOICE (sesuai request)
       - Grafik FULL width, anti-stretch
       - Invoice turun ke bawah, lebih lega
       - Tabel invoice: ellipsis, tidak maksa wrap, scroll rapi
       ========================================================= */
    .dashboard-row{ align-items:flex-start; } /* jangan saling “stretch” */

    /* ----- GRAFIK (anti-stretch) ----- */
    .chart-area{ position:relative; width:100%; }
    .chart-fluid{
      /* clamp = tinggi tidak “ngaco” di Windows scale 150% + responsif */
      height: clamp(260px, 36vh, 520px);
    }
    @media (max-width: 575.98px){
      .card-soft .card-body{ padding: .9rem 1rem; }
      .chart-fluid{ height: 280px; } /* HP */
    }
    @media (min-width: 1200px){
      .chart-fluid{ height: clamp(360px, 42vh, 560px); } /* desktop besar */
    }

    /* Grafik 2 kolom (sesuai request: 6 bulan terakhir) */
    .chart-fluid-2col{ height: clamp(220px, 28vh, 420px); }
    @media (max-width: 575.98px){
      .chart-fluid-2col{ height: 260px; } /* HP */
    }


    .chart-area canvas{
      width:100% !important;
      height:100% !important;
      display:block;
    }

    /* tinggi grafik 2 kolom & 3 kolom */
    .chart-fluid-2col{ height: clamp(220px, 28vh, 420px); }
    .chart-fluid-3col{ height: clamp(220px, 26vh, 380px); }

    @media (max-width: 575.98px){
      .chart-fluid-2col{ height: 260px; }
      .chart-fluid-3col{ height: 260px; }
    }


    /* ----- INVOICE (lebih rapi, tidak wrap aneh) ----- */
    .invoice-wrap{
      /* area scroll tetap rapi & proporsional */
      max-height: clamp(320px, 44vh, 560px);
      overflow:auto;
      -webkit-overflow-scrolling: touch;
    }

    .thead-light th{ background:#f3f6fb; border:0; }
    .table thead th{
      font-weight:700;
      font-size:.78rem;
      letter-spacing:.3px;
      color:#334155;
    }
    .table td{ vertical-align: middle; }

    .table-sticky thead th{
      position:sticky;
      top:0;
      z-index:2;
    }

    /* KUNCI: supaya kolom tidak maksa wrap dan bisa ellipsis */
    .invoice-table{
      table-layout: fixed;
      width: 100%;
      margin-bottom: 0;
    }
    .invoice-table th,
    .invoice-table td{
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    /* Lebih aman untuk konten link di kolom ORDER ID */
    .invoice-table td a{
      display:block;
      max-width:100%;
      overflow:hidden;
      text-overflow:ellipsis;
      white-space:nowrap;
    }

    /* Lebar kolom (biar tidak wrap aneh di scale 150%) */
    /* Lebar kolom (7 kolom) */
    .invoice-table th:nth-child(1), .invoice-table td:nth-child(1){ width: 18%; } /* ORDER ID */
    .invoice-table th:nth-child(2), .invoice-table td:nth-child(2){ width: 22%; } /* PELANGGAN */
    .invoice-table th:nth-child(3), .invoice-table td:nth-child(3){ width: 12%; } /* TOTAL */
    .invoice-table th:nth-child(4), .invoice-table td:nth-child(4){ width: 12%; } /* BAYAR */
    .invoice-table th:nth-child(5), .invoice-table td:nth-child(5){ width: 12%; } /* PIUTANG */
    .invoice-table th:nth-child(6), .invoice-table td:nth-child(6){ width: 12%; } /* STATUS */
    .invoice-table th:nth-child(7), .invoice-table td:nth-child(7){ width: 12%; } /* LUNAS */

    @media (max-width: 991.98px){
      .invoice-table{ min-width: 980px; } /* biar kolom baru nggak penyet */
    }

    /* =========================================================
   FIX KHUSUS iPad Air (1180 x 820)
   - kecilkan font & padding tabel invoice
   - kecilkan badge agar muat, minim "..."
   ========================================================= */
@media (width: 1180px) and (height: 820px),
       (min-width: 1024px) and (max-width: 1200px) and (min-height: 760px) and (max-height: 900px) {

  /* card invoice lebih rapat */
  #LoadingInvoice .card-header{ padding: .65rem .85rem; }
  #LoadingInvoice .card-header h6{ font-size: .92rem; }

  /* tabel invoice: font & padding diperkecil */
  #LoadingInvoice .invoice-table thead th{
    font-size: .68rem;
    padding: .45rem .55rem;
    letter-spacing: .25px;
  }

  #LoadingInvoice .invoice-table tbody td{
    font-size: .72rem;
    padding: .42rem .55rem;
  }

  /* badge status/lunas lebih kecil */
  #LoadingInvoice .badge{
    font-size: .62rem;
    padding: .22rem .45rem;
    border-radius: 8px;
    line-height: 1.1;
  }

  /* badge ORDER ID lebih ringkas */
  #LoadingInvoice .invoice-table td a .badge{
    font-size: .62rem;
    padding: .22rem .40rem;
  }

  /* kecilkan wrapper tinggi sedikit biar pas */
  #LoadingInvoice .invoice-wrap{
    max-height: clamp(280px, 40vh, 460px);
  }

  /* OPTIONAL (kalau masih kepotong): paksa tidak ellipsis di iPad Air */
  #LoadingInvoice .invoice-table th,
  #LoadingInvoice .invoice-table td{
    text-overflow: clip;     /* ganti dari ellipsis */
  }
}

    
    /* =========================================================
   FIX KHUSUS Windows 1920x1080 @ Scale 150%
   Target:
   - semua KPI + semua card: font lebih kecil & padding rapat
   - invoice table + lowstock table: minim "..." / ellipsis
   Catatan:
   - Windows scale 150% umumnya DPR ~1.5 dan CSS dpi ~144
   ========================================================= */

    /* Target akurat berdasarkan DPI (scale 150%) */
    @media (min-resolution: 144dpi) and (max-resolution: 168dpi) {

      /* ==== GLOBAL CARD SPACING ==== */
      .card-soft .card-header{ padding: .70rem .85rem; }
      .card-soft .card-body{ padding: .85rem 1rem; }

      /* judul card */
      .header-wrap h6{ font-size: .95rem; }
      .text-muted-600{ font-size: .78rem; }

      /* tombol kecil agar tidak makan ruang */
      .btn-sm{ padding: .28rem .55rem; font-size: .78rem; }
      .btn-pill{ padding-left: .60rem !important; padding-right: .60rem !important; }

      /* dropdown item lebih rapat */
      .dropdown-item{ font-size: .82rem; padding: .45rem .80rem; }

      /* ==== KPI ==== */
      .kpi{ min-height: 78px; gap: .6rem; }

      .kpi .label{
        font-size: .66rem;
        letter-spacing: .35px;
        margin-bottom: .2rem;
      }
      .kpi .value{
        font-size: 1.45rem;     /* sebelumnya 1.8rem */
        line-height: 1.05;
      }
      .kpi .badge-icon{
        width: 44px;            /* sebelumnya 50 */
        height: 44px;
        border-radius: 14px;
      }
      .kpi .badge-icon i{ font-size: 1.02rem; }

      /* ==== CHART CARD ==== */
      /* kecilkan tinggi chart sedikit supaya area teks tidak kepotong */
      .chart-fluid{ height: clamp(240px, 34vh, 480px); }
      .chart-fluid-2col{ height: clamp(210px, 26vh, 390px); }
      .chart-fluid-3col{ height: clamp(210px, 24vh, 350px); }

      /* ==== INVOICE TABLE ==== */
      #LoadingInvoice .card-header{ padding: .62rem .85rem; }
      #LoadingInvoice .card-header h6{ font-size: .92rem; }

      #LoadingInvoice .invoice-table thead th{
        font-size: .66rem;
        padding: .38rem .48rem;
        letter-spacing: .2px;
      }
      #LoadingInvoice .invoice-table tbody td{
        font-size: .70rem;
        padding: .36rem .48rem;
      }

      /* badge status/lunas kecil */
      #LoadingInvoice .badge{
        font-size: .60rem;
        padding: .18rem .40rem;
        border-radius: 8px;
        line-height: 1.1;
      }
      #LoadingInvoice .invoice-table td a .badge{
        font-size: .60rem;
        padding: .18rem .36rem;
      }

      /* hilangkan "..." khusus invoice */
      #LoadingInvoice .invoice-table th,
      #LoadingInvoice .invoice-table td{
        text-overflow: clip;   /* ganti ellipsis jadi clip */
      }

      /* ==== LOWSTOCK TABLE ==== */
      #LoadingKomposisiAkun .card-header{ padding: .62rem .85rem; }
      #LoadingKomposisiAkun .card-header h6{ font-size: .92rem; }

      #LoadingKomposisiAkun .lowstock-table thead th{
        font-size: .66rem;
        padding: .38rem .48rem;
      }
      #LoadingKomposisiAkun .lowstock-table tbody td{
        font-size: .70rem;
        padding: .36rem .48rem;
      }

      #LoadingKomposisiAkun .lowstock-badge{
        font-size: .62rem;
        padding: .14rem .38rem;
      }

      /* hilangkan "..." khusus lowstock (opsional, tapi biasanya perlu) */
      #LoadingKomposisiAkun .lowstock-table th,
      #LoadingKomposisiAkun .lowstock-table td{
        text-overflow: clip;
      }

      /* ==== OPTIONAL: jika masih kepotong, izinkan text turun baris untuk kolom tertentu ==== */
      /* Aktifkan ini kalau kamu lebih prefer teks turun baris daripada terpotong */
      /*
      #LoadingInvoice .invoice-table td:nth-child(2),
      #LoadingKomposisiAkun .lowstock-table td:nth-child(1){
        white-space: normal;
      }
      */
    }

    /* Fallback viewport umum Windows 1920@150% ≈ 1280x720 */
    @media (min-width: 1200px) and (max-width: 1366px) and (min-height: 650px) and (max-height: 820px){

      .card-soft .card-header{ padding: .70rem .85rem; }
      .card-soft .card-body{ padding: .85rem 1rem; }

      .kpi .label{ font-size: .66rem; }
      .kpi .value{ font-size: 1.45rem; }
      .kpi .badge-icon{ width: 44px; height: 44px; }
      .kpi .badge-icon i{ font-size: 1.02rem; }

      #LoadingInvoice .invoice-table thead th{ font-size: .66rem; padding: .38rem .48rem; }
      #LoadingInvoice .invoice-table tbody td{ font-size: .70rem; padding: .36rem .48rem; }
      #LoadingInvoice .invoice-table th,
      #LoadingInvoice .invoice-table td{ text-overflow: clip; }
    }



    /* =========================================================
   WIDGET: STOK BAHAN MENIPIS (replace Komposisi Akun)
   ========================================================= */
    .lowstock-wrap{
      max-height: clamp(220px, 26vh, 380px);
      overflow:auto;
      -webkit-overflow-scrolling: touch;
    }

    .lowstock-table{
      table-layout: fixed;
      width: 100%;
    }

    .lowstock-table th,
    .lowstock-table td{
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      vertical-align: middle;
    }

    /* ===== Lowstock table: bikin kolom SISA STOK lebih lega & tidak ellipsis ===== */
    .lowstock-table th:nth-child(1), .lowstock-table td:nth-child(1){ width: 55%; }
    .lowstock-table th:nth-child(2), .lowstock-table td:nth-child(2){ width: 45%; }


    /* biar value + unit + badge tidak jadi "..." */
    .lowstock-table td:nth-child(2){
      white-space: normal;     /* boleh turun baris */
      overflow: visible;
      text-overflow: clip;
    }

    /* bikin value + unit + badge tetap 1 baris */
    .lowstock-value{
      display:flex;
      justify-content:flex-end;
      align-items:center;
      flex-wrap:nowrap;      /* kunci: jangan turun baris */
      gap:8px;
      width:100%;
    }

    .lowstock-badge{
  padding:.14rem .40rem;
  font-size:.64rem;
  border-radius:999px;
  font-weight:800;
  letter-spacing:.2px;
  line-height:1.1;
}


    /* pastikan badge tidak ngecil */
    .lowstock-value .lowstock-badge{
      flex:0 0 auto;
      white-space:nowrap;
    }

    /* angka boleh tetap rapih */
    .lowstock-value .font-weight-bold{
      flex:0 0 auto;
    }

    @supports not (gap: 6px){
      .lowstock-value > *{ margin-left:6px; }
      .lowstock-value > *:first-child{ margin-left:0; }
    }

    .lowstock-badge{
      display:inline-block;
      padding:.18rem .45rem;
      border-radius:999px;
      font-size:.68rem;
      font-weight:800;
      letter-spacing:.2px;
      white-space:nowrap;
    }

    /* orange (sesuai request) */
    .badge-low-orange{
      background:#f59e0b;
      border:1px solid #f59e0b;
      color:#111827;
    }



    .lowstock-badge{
      display:inline-block;
      padding:.18rem .45rem;
      border-radius: 999px;
      font-size:.7rem;
      font-weight:700;
      margin-right:.4rem;
    }


    .mb-4 { margin-bottom:1.25rem !important; }
    .btn-sm{ padding:.35rem .75rem; }
    .text-muted-600{ color: var(--muted) !important; }

    /* =========================================================
   WIDGET: SALDO KAS (Tunai & Bank)
   ========================================================= */
    .kas-saldo-wrap{
      max-height: clamp(220px, 26vh, 380px);
      overflow:auto;
      -webkit-overflow-scrolling: touch;
    }
    .kas-saldo-table{
      table-layout: fixed;
      width: 100%;
      margin-bottom: 0;
    }
    .kas-saldo-table th,
    .kas-saldo-table td{
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      vertical-align: middle;
    }
    .kas-saldo-table th:nth-child(1), .kas-saldo-table td:nth-child(1){ width: 62%; }
    .kas-saldo-table th:nth-child(2), .kas-saldo-table td:nth-child(2){ width: 38%; }

    /* =========================================================
       WIDGET: TIMELINE MUTASI (HTML dari kas/cariMutasi)
       ========================================================= */
    .mutasi-wrap{
      max-height: clamp(260px, 38vh, 520px);
      overflow:auto;
      -webkit-overflow-scrolling: touch;
      padding: 12px;
    }

  </style>

  <div class="row mb-3 dashboard-row">

    <!-- KPI 1: Omset Hari Ini -->
    <div class="col-xl-4 col-md-6 mb-4">
      <div class="card card-soft h-100">
        <div class="card-body kpi" id="LoadingTotal">
          <div>
            <div class="label">OMSET PENJUALAN HARI INI</div>
            <div class="value load-count">0</div>
          </div>
          <div class="badge-icon" aria-hidden="true">
            <i class="fa fa-line-chart"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- KPI 2: Pendapatan Hari Ini -->
    <div class="col-xl-4 col-md-6 mb-4">
      <div class="card card-soft h-100">
        <div class="card-body kpi" id="LoadingToday">
          <div>
            <div class="label">PENDAPATAN HARI INI</div>
            <div class="value load-now">0</div>
          </div>
          <div class="badge-icon" aria-hidden="true">
            <i class="fa fa-money"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- KPI 3: TOTAL SELURUH PIUTANG -->
    <div class="col-xl-4 col-md-6 mb-4">
      <div class="card card-soft h-100">
        <div class="card-body kpi" id="LoadingBaru">
          <div>
            <div class="label">TOTAL SELURUH PIUTANG</div>
            <div class="value load-baru">0</div>
          </div>
          <div class="badge-icon" aria-hidden="true">
            <i class="fa fa-credit-card"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- KPI 4: Omset Bulan Ini -->
    <div class="col-xl-4 col-md-6 mb-4">
      <div class="card card-soft h-100">
        <div class="card-body kpi" id="LoadingPending">
          <div>
            <div class="label">OMSET PENJUALAN BULAN INI</div>
            <div class="value load-pending">0</div>
          </div>
          <div class="badge-icon" aria-hidden="true">
            <i class="fa fa-line-chart"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- KPI 5: Pendapatan Bulan Ini -->
    <div class="col-xl-4 col-md-6 mb-4">
      <div class="card card-soft h-100">
        <div class="card-body kpi" id="LoadingBatal">
          <div>
            <div class="label">PENDAPATAN BULAN INI</div>
            <div class="value load-batal">0</div>
          </div>
          <div class="badge-icon" aria-hidden="true">
            <i class="fa fa-money"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- KPI 6: Piutang Bulan Ini -->
    <div class="col-xl-4 col-md-6 mb-4">
      <div class="card card-soft h-100">
        <div class="card-body kpi" id="LoadingPiutangBulan">
          <div>
            <div class="label">PIUTANG BULAN INI</div>
            <div class="value load-piutang-bulan">0</div>
          </div>
          <div class="badge-icon" aria-hidden="true">
            <i class="fa fa-credit-card"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- KPI 7: Kas Keluar / Pengeluaran Bulan Ini -->
    <div class="col-xl-4 col-md-6 mb-4">
      <div class="card card-soft h-100">
        <div class="card-body kpi" id="LoadingKasKeluar">
          <div>
            <div class="label">PENGELUARAN BULAN INI</div>
            <div class="value load-kaskeluar">0</div>
          </div>
          <div class="badge-icon" aria-hidden="true">
            <i class="fa fa-money"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- KPI 8: Pembelian Bulan Ini -->
    <div class="col-xl-4 col-md-6 mb-4">
      <div class="card card-soft h-100">
        <div class="card-body kpi" id="LoadingPembelian">
          <div>
            <div class="label">PEMBELIAN BULAN INI</div>
            <div class="value load-pembelian">0</div>
          </div>
          <div class="badge-icon" aria-hidden="true">
            <i class="fa fa-money"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- KPI 9: Konsumen Aktif -->
    <div class="col-xl-4 col-md-6 mb-4">
      <div class="card card-soft h-100">
        <div class="card-body kpi" id="LoadingKonsumenAktif">
          <div>
            <div class="label">KONSUMEN AKTIF</div>
            <div class="value load-konsumen-total">0</div>
          </div>
          <div class="badge-icon" aria-hidden="true">
            <i class="fa fa-users"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- =========================================================
   NEW: KAS OVERVIEW (Saldo + Timeline Mutasi)
   - Saldo: data dari logic kas/pengaturan (via endpoint kas/dashboard_saldo)
   - Mutasi: HTML timeline dari kas/cariMutasi (view kas/cari-mutasi.php)
   ========================================================= -->
<div class="col-12 mb-4">
  <div class="row">

    <!-- CARD 1: Saldo Kas Tunai & Bank -->
    <div class="col-lg-6 mb-4" id="LoadingSaldoKas">
      <div class="card card-soft h-100">
        <div class="card-header">
          <div class="header-wrap">
            <div>
              <h6 class="m-0">Saldo Kas (Tunai & Bank)</h6>
              <small class="text-muted-600">Rekap saldo kas aktif</small>
            </div>
            <div class="header-actions">
              <!--span class="badge badge-light" id="saldo-kas-total">Rp 0</span-->
              <a class="btn btn-light-soft btn-sm btn-pill" href="<?= base_url('kas/data'); ?>">Detail</a>
            </div>
          </div>
        </div>

        <div class="card-body p-0">
          <div class="kas-saldo-wrap">
            <table class="table table-sm mb-0 table-sticky kas-saldo-table">
              <thead class="thead-light">
                <tr>
                  <th>AKUN</th>
                  <th class="text-right">SALDO</th>
                </tr>
              </thead>
              <tbody id="load-saldo-kas">
                <tr>
                  <td colspan="2" class="text-center text-muted py-3">Memuat data…</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

      </div>
    </div>

    <!-- CARD 2: Timeline Mutasi Antar Kas -->
    <div class="col-lg-6 mb-4" id="LoadingMutasiKas">
      <div class="card card-soft h-100">
        <div class="card-header">
          <div class="header-wrap">
            <div>
              <h6 class="m-0">Timeline Mutasi Antar Kas</h6>
              <small class="text-muted-600">Default: minggu ini</small>
            </div>
            <div class="header-actions">
              <a class="btn btn-light-soft btn-sm btn-pill" href="<?= base_url('kas/mutasi'); ?>">Buka Mutasi</a>
            </div>
          </div>
        </div>

        <div class="card-body p-0">
          <div class="mutasi-wrap" id="load-mutasi-kas">
            <div class="text-center text-muted py-3">Memuat data…</div>
          </div>
        </div>

      </div>
    </div>

  </div>
</div>


    <!-- =========================================================
     DASHBOARD CHARTS (REPLACEMENT)
     - Pendapatan vs Beban (6 bulan)
     - Tren Arus Kas (6 bulan)
     - Produk Terlaris (Donut)
     - Pelanggan Terbesar (Bar Horizontal)
     - Komposisi Tipe Akun (Polar Area)
     ========================================================= -->

      <!-- ROW 1: 2 grafik utama -->
      <div class="col-12 mb-4">
        <div class="row">

          <div class="col-lg-6 mb-4" id="LoadingGrafikPendapatanBeban">
            <div class="card card-soft h-100">
              <div class="card-header">
                <div class="header-wrap">
                  <h6 class="m-0">Pendapatan vs Beban</h6>
                  <small class="text-muted-600">6 Bulan Terakhir</small>
                </div>
              </div>
              <div class="card-body">
                <div class="chart-area chart-fluid-2col">
                  <canvas id="chartPendapatanBeban"></canvas>
                </div>
              </div>
            </div>
          </div>

          <div class="col-lg-6 mb-4" id="LoadingGrafikArusKas">
            <div class="card card-soft h-100">
              <div class="card-header">
                <div class="header-wrap">
                  <h6 class="m-0">Tren Arus Kas Pendapatan</h6>
                  <small class="text-muted-600">6 Bulan Terakhir</small>
                </div>
              </div>
              <div class="card-body">
                <div class="chart-area chart-fluid-2col">
                  <canvas id="chartArusKas"></canvas>
                </div>
              </div>
            </div>
          </div>

        </div>
      </div>

      <!-- ROW 2: 3 grafik tambahan -->
      <div class="col-12 mb-4">
        <div class="row">

          <div class="col-lg-4 mb-4" id="LoadingProdukTerlaris">
            <div class="card card-soft h-100">
              <div class="card-header">
                <div class="header-wrap">
                  <h6 class="m-0">Produk Terlaris</h6>

                  <div class="header-actions">
                    <div class="btn-group btn-group-sm" role="group" aria-label="Mode Produk Terlaris">
                      <button type="button" class="btn btn-light-soft btn-pill btn-produk-mode active" data-mode="nilai">
                        Nilai (Rp)
                      </button>
                      <button type="button" class="btn btn-light-soft btn-pill btn-produk-mode" data-mode="qty">
                        Qty
                      </button>
                    </div>

                    <!-- Range dropdown (default: 3 Bulan Terakhir) -->
                    <div class="dropdown range-dd" data-scope="extra">
                      <button class="btn btn-light-soft btn-sm btn-pill dropdown-toggle btn-range" type="button"
                              data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" data-range="3m">
                        3 Bulan Terakhir
                      </button>
                      <div class="dropdown-menu dropdown-menu-right">
                        <a class="dropdown-item" href="#" data-range="month">Bulan Ini</a>
                        <a class="dropdown-item active" href="#" data-range="3m">3 Bulan Terakhir</a>
                        <a class="dropdown-item" href="#" data-range="6m">6 Bulan Terakhir</a>
                        <a class="dropdown-item" href="#" data-range="year">Tahun Ini</a>
                      </div>
                    </div>

                  </div>
                </div>
              </div>

              <div class="card-body">
                <div class="chart-area chart-fluid-3col">
                  <canvas id="chartProdukTerlaris"></canvas>
                </div>
              </div>
            </div>
          </div>

          <div class="col-lg-4 mb-4" id="LoadingPelangganTerbesar">
            <div class="card card-soft h-100">
              <div class="card-header">
                <div class="header-wrap">
                  <h6 class="m-0">Pelanggan Transaksi Terbesar</h6>

                  <!-- Range dropdown (default: 3 Bulan Terakhir) -->
                  <div class="dropdown range-dd" data-scope="extra">
                    <button class="btn btn-light-soft btn-sm btn-pill dropdown-toggle btn-range" type="button"
                            data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" data-range="3m">
                      3 Bulan Terakhir
                    </button>
                    <div class="dropdown-menu dropdown-menu-right">
                      <a class="dropdown-item" href="#" data-range="month">Bulan Ini</a>
                      <a class="dropdown-item active" href="#" data-range="3m">3 Bulan Terakhir</a>
                      <a class="dropdown-item" href="#" data-range="6m">6 Bulan Terakhir</a>
                      <a class="dropdown-item" href="#" data-range="year">Tahun Ini</a>
                    </div>
                  </div>
                </div>

              </div>
              <div class="card-body">
                <div class="chart-area chart-fluid-3col">
                  <canvas id="chartPelangganTerbesar"></canvas>
                </div>
              </div>
            </div>
          </div>

          <div class="col-lg-4 mb-4" id="LoadingKomposisiAkun">
            <div class="card card-soft h-100">
              <div class="card-header">
                <div class="header-wrap">
                  <div>
                    <h6 class="m-0">Stok Bahan Menipis</h6>
                    
                  </div>
                  <div class="header-actions">
                    <a class="btn btn-light-soft btn-sm btn-pill" href="<?= base_url('stok/data'); ?>">
                      Kelola Stok
                    </a>
                  </div>
                </div>
              </div>

              <div class="card-body p-0">
                <div class="lowstock-wrap">
                  <table class="table table-sm mb-0 table-sticky lowstock-table">
                    <thead class="thead-light">
                      <tr>
                        <th>NAMA BAHAN</th>
                        <th class="text-right">SISA STOK</th>
                      </tr>
                    </thead>
                    <tbody id="load-stok-menipis">
                      <tr>
                        <td colspan="2" class="text-center text-muted py-3">Memuat data…</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>


            </div>
          </div>


    <!-- =========================================================
         INVOICE: turun ke bawah (col-12), lebih lega
         ========================================================= -->
    <div class="col-12">
      <div class="card card-soft" id="LoadingInvoice">
        <div class="card-header">
          <div class="header-wrap">
            <h6 class="m-0">Data Transaksi Terbaru</h6>
            <a class="btn btn-light-soft btn-sm btn-pill" href="<?= base_url('penjualan/order'); ?>">View More</a>
          </div>
        </div>

        <div class="table-responsive invoice-wrap">
          <table class="table align-items-center table-flush table-sticky invoice-table">
            <thead class="thead-light">
              <tr>
                <th>ORDER ID</th>
                <th>PELANGGAN</th>
                <th class="text-right">TOTAL</th>
                <th class="text-right">BAYAR</th>
                <th class="text-right">PIUTANG</th>
                <th>STATUS</th>
                <th class="text-right">LUNAS</th>
              </tr>
            </thead>

            <tbody id="load-invoice"></tbody>
          </table>
        </div>

        <div class="card-footer"></div>
      </div>
    </div>

  </div>
</div>

<script>

  // =========================================================
  // GRAFIK DASHBOARD 6 BULAN TERAKHIR (BAR + LINE)
  // Endpoint: penjualan/grafik_dashboard_6bulan
  // =========================================================
  var _chartPendapatanBeban = null;
  var _chartArusKas = null;

  function _fmtRupiah(val){
    try {
      if (typeof number_format === 'function') {
        return 'Rp ' + number_format(val);
      }
      val = Number(val || 0);
      return 'Rp ' + val.toLocaleString('id-ID');
    } catch(e){
      return 'Rp ' + val;
    }
  }

  function _fmtShortRupiahAxis(value){
    value = Number(value || 0);
    var abs = Math.abs(value);
    if (abs >= 1000000000) return 'Rp ' + (value/1000000000).toFixed(0) + 'B';
    if (abs >= 1000000)    return 'Rp ' + (value/1000000).toFixed(0) + 'M';
    if (abs >= 1000)       return 'Rp ' + (value/1000).toFixed(0) + 'K';
    return 'Rp ' + value;
  }

  function load_dashboard_charts(){
    $.ajaxQueue({
      url: base_url + "penjualan/grafik_dashboard_6bulan",
      cache: false,
      dataType: "json",
      beforeSend: function(){
        $("#LoadingGrafikPendapatanBeban").loading();
        $("#LoadingGrafikArusKas").loading();
      },
      success: function(res){
        $("#LoadingGrafikPendapatanBeban").loading('stop');
        $("#LoadingGrafikArusKas").loading('stop');

        if (!res || !res.labels || !res.labels.length) return;

        renderPendapatanBeban(res);
        renderArusKas(res);
      },
      error: function(){
        $("#LoadingGrafikPendapatanBeban").loading('stop');
        $("#LoadingGrafikArusKas").loading('stop');
      }
    });
  }

  function renderPendapatanBeban(res){
    var el = document.getElementById('chartPendapatanBeban');
    if (!el || typeof Chart === 'undefined') return;

    if (_chartPendapatanBeban) { _chartPendapatanBeban.destroy(); }

    _chartPendapatanBeban = new Chart(el, {
      type: 'bar',
      data: {
        labels: res.labels,
        datasets: [
          {
            label: 'Pendapatan',
            data: res.pendapatan || [],
            backgroundColor: 'rgba(34,197,94,0.85)',
            borderColor: 'rgba(34,197,94,1)',
            borderWidth: 0,
            maxBarThickness: 34
          },
          {
            label: 'Beban',
            data: res.beban || [],
            backgroundColor: 'rgba(239,68,68,0.85)',
            borderColor: 'rgba(239,68,68,1)',
            borderWidth: 0,
            maxBarThickness: 34
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        tooltips: {
          mode: 'nearest',
          intersect: true,
          callbacks: {
            label: function(tooltipItem, data){
              var ds = data.datasets[tooltipItem.datasetIndex];
              var val = tooltipItem.yLabel;
              return (ds.label || 'Nilai') + ': ' + _fmtRupiah(val);
            }
          }
        },
        legend: {
          display: true,
          position: 'bottom',
          labels: { usePointStyle: true, boxWidth: 8 }
        },
        scales: {
          xAxes: [{
            gridLines: { display: false, drawBorder: false },
            ticks: { maxRotation: 0, autoSkip: true }
          }],
          yAxes: [{
            ticks: {
              beginAtZero: true,
              callback: function(value){ return _fmtShortRupiahAxis(value); }
            },
            gridLines: { color: "rgb(234, 236, 244)", drawBorder: false }
          }]
        }
      }
    });
  }

  
  // Dropdown bulan untuk grafik
  $('.dropdown-select').on('click', '.dropdown-menu a', function () {
    var target = $(this).html();
    var id     = $(this).attr('data-id');
    var tipe   = $(this).attr('data-tipe');

    if (tipe === 'omset') { load_chart(id); }

    $(this).closest('.dropdown-menu').find('.dropdown-item.active').removeClass('active');
    $(this).addClass('active');

    $(this).closest('.dropdown-select').find('.dropdown-toggle').html(target + ' <span class="caret"></span>');
  });

  // =========================================================
// NEW: SALDO KAS (Tunai & Bank) - JSON
// Endpoint: kas/dashboard_saldo
// =========================================================
function load_dashboard_saldo_kas(){
  $.ajaxQueue({
    url: base_url + "kas/dashboard_saldo",
    cache: false,
    dataType: "json",
    beforeSend: function(){
      $("#LoadingSaldoKas").loading();
    },
    success: function(res){
      $("#LoadingSaldoKas").loading('stop');

      if (!res || res.status !== 200){
        $('#load-saldo-kas').html(
          '<tr><td colspan="2" class="text-center text-muted py-3">Gagal memuat saldo kas.</td></tr>'
        );
        return;
      }

      $('#saldo-kas-total').text(_fmtKpiRp(res.total || 0));
      renderSaldoKas(res.items || []);
    },
    error: function(){
      $("#LoadingSaldoKas").loading('stop');
      $('#load-saldo-kas').html(
        '<tr><td colspan="2" class="text-center text-muted py-3">Gagal memuat saldo kas.</td></tr>'
      );
    }
  });
}

function renderSaldoKas(items){
  items = items || [];
  var $tbody = $('#load-saldo-kas');
  if (!$tbody.length) return;

  if (!items.length){
    $tbody.html('<tr><td colspan="2" class="text-center text-muted py-3">Belum ada data kas.</td></tr>');
    return;
  }

  var html = '';
  for (var i=0; i<items.length; i++){
    var it = items[i] || {};
    var label = _escHtml(it.label || '-');
    var saldo = _fmtKpiRp(it.saldo || 0);

    html += '<tr>' +
      '<td title="'+label+'">' + label + '</td>' +
      '<td class="text-right font-weight-bold">' + saldo + '</td>' +
    '</tr>';
  }
  $tbody.html(html);
}

// =========================================================
// NEW: TIMELINE MUTASI - HTML (view kas/cari-mutasi.php)
// Endpoint: kas/cariMutasi (default: minggu ini)
// =========================================================
function load_dashboard_mutasi_kas(){
  $.ajaxQueue({
    url: base_url + "kas/cariMutasi",
    type: "POST",
    dataType: "html",
    data: {}, // kosong -> controller akan default minggu ini
    beforeSend: function(){
      $("#LoadingMutasiKas").loading();
    },
    success: function(html){
      $("#LoadingMutasiKas").loading('stop');

      html = (html || '').toString();
      // kalau akses/login bermasalah, tampilkan pesan ringkas
      if (html.indexOf('Akses terbatas') !== -1 || html.indexOf('Login required') !== -1){
        $('#load-mutasi-kas').html('<div class="text-center text-muted py-3">Tidak ada akses ke data mutasi.</div>');
        return;
      }

      $('#load-mutasi-kas').html(html);
    },
    error: function(){
      $("#LoadingMutasiKas").loading('stop');
      $('#load-mutasi-kas').html('<div class="text-center text-muted py-3">Gagal memuat mutasi kas.</div>');
    }
  });
}


  $(document).ready(function () {
    $('[data-toggle="tooltip"]').tooltip();

    // KPI existing:
    loadcount();        // Omset Hari Ini
    hari_ini();         // Pendapatan Hari Ini
    baru();             // Piutang Hari Ini
    pending();          // Omset Bulan Ini
    batal();            // Pendapatan Bulan Ini
    piutang_bulan();    // Piutang Bulan Ini

    // KPI baru:
    kas_keluar_bulan(); // Pengeluaran Bulan Ini
    pembelian_bulan();  // Pembelian Bulan Ini
    konsumen_total();   // Konsumen Aktif

    //load_chart();
    loadinvoice();
  });

  function loadinvoice(){
    $.ajaxQueue({
      url:  base_url+"penjualan/list_invoice",
      cache: false,
      beforeSend: function(){ $("#LoadingInvoice").loading(); },
      success: function (data) {
        $("#LoadingInvoice").loading('stop');
        $('#load-invoice').html(data);
      }
    });
  }

  // ====== FORMAT KPI RUPIAH (AMAN UNTUK "3.175.500" / "3175500") ======
  function _fmtKpiRp(val){
    try{
      if (val === null || val === undefined) return 'Rp 0';

      var s = (typeof val === 'string') ? val : String(val);
      s = (s || '').trim();
      if (!s) return 'Rp 0';

      // kalau dari server sudah ada "Rp", jangan dobel
      if (/^rp[\s\.]*/i.test(s)) {
        return s.replace(/^rp[\s\.]*/i, 'Rp ').trim();
      }

      // ambil angka saja (aman untuk "3.175.500", "3,175,500", dsb)
      var num = parseInt(s.replace(/[^\d-]/g, ''), 10);
      if (isNaN(num)) return 'Rp ' + s; // fallback kalau format aneh

      return 'Rp ' + num.toLocaleString('id-ID');
    } catch(e){
      return 'Rp ' + val;
    }
  }


  // Omset Hari Ini
  function loadcount(){
    $.ajaxQueue({
      url:  base_url+"penjualan/totaltrx",
      cache: false,
      dataType:"json",
      beforeSend: function(){ $("#LoadingTotal").loading(); },
      success: function (data) {
        $("#LoadingTotal").loading("stop");
        $('.load-count').html(_fmtKpiRp(data));
      }
    });
  }

  // Pendapatan Hari Ini
  function hari_ini(){
    $.ajaxQueue({
      url:  base_url+"penjualan/hari_ini",
      cache: false,
      beforeSend: function(){ $("#LoadingToday").loading(); },
      success: function (data) {
        $("#LoadingToday").loading('stop');
        $('.load-now').html(_fmtKpiRp(data));
      }
    });
  }

  // Piutang Hari Ini
  function baru(){
    $.ajaxQueue({
      url:  base_url+"penjualan/baru",
      cache: false,
      beforeSend: function(){ $("#LoadingBaru").loading(); },
      success: function (data) {
        $("#LoadingBaru").loading('stop');
        $('.load-baru').html(_fmtKpiRp(data));
      }
    });
  }

  // Omset Bulan Ini
  function pending(){
    $.ajaxQueue({
      url:  base_url+"penjualan/pending",
      cache: false,
      beforeSend: function(){ $("#LoadingPending").loading(); },
      success: function (data) {
        $("#LoadingPending").loading('stop');
        $('.load-pending').html(_fmtKpiRp(data));
      }
    });
  }

  // Pendapatan Bulan Ini
  function batal(){
    $.ajaxQueue({
      url:  base_url+"penjualan/batal",
      cache: false,
      beforeSend: function(){ $("#LoadingBatal").loading(); },
      success: function (data) {
        $("#LoadingBatal").loading('stop');
        $('.load-batal').html(_fmtKpiRp(data));
      }
    });
  }

  // Piutang Bulan Ini
  function piutang_bulan(){
    $.ajaxQueue({
      url:  base_url+"penjualan/piutang_bulan",
      cache: false,
      beforeSend: function(){ $("#LoadingPiutangBulan").loading(); },
      success: function (data) {
        $("#LoadingPiutangBulan").loading('stop');
        $('.load-piutang-bulan').html(_fmtKpiRp(data));
      }
    });
  }

  // Pengeluaran Bulan Ini
  function kas_keluar_bulan(){
    $.ajaxQueue({
      url:  base_url+"penjualan/kas_keluar_bulan",
      cache: false,
      beforeSend: function(){ $("#LoadingKasKeluar").loading(); },
      success: function (data) {
        $("#LoadingKasKeluar").loading('stop');
        $('.load-kaskeluar').html(_fmtKpiRp(data));
      }
    });
  }

  // Pembelian Bulan Ini
  function pembelian_bulan(){
    $.ajaxQueue({
      url:  base_url+"penjualan/pembelian_bulan",
      cache: false,
      beforeSend: function(){ $("#LoadingPembelian").loading(); },
      success: function (data) {
        $("#LoadingPembelian").loading('stop');
        $('.load-pembelian').html(_fmtKpiRp(data));
      }
    });
  }

  // Konsumen Aktif
  function konsumen_total(){
    $.ajaxQueue({
      url:  base_url+"penjualan/konsumen_total",
      cache: false,
      beforeSend: function(){ $("#LoadingKonsumenAktif").loading(); },
      success: function (data) {
        $("#LoadingKonsumenAktif").loading('stop');
        $('.load-konsumen-total').html(data);
      }
    });
  }

  // Fallback searchFilter
  window.searchFilter = window.searchFilter || function(termOrInput, tableSelector) {
    try {
      var q = '';
      if (typeof termOrInput === 'string') {
        q = termOrInput;
      } else if (termOrInput && termOrInput.value !== undefined) {
        q = termOrInput.value;
      } else if (window.jQuery && termOrInput && termOrInput.jquery) {
        q = termOrInput.val();
      }
      q = (q || '').toString().toLowerCase();

      if (!window.jQuery) return;
      var $ = window.jQuery;
      var $table = tableSelector ? $(tableSelector) : $('.table:visible').first();
      if (!$table.length) return;

      $table.find('tbody tr').each(function () {
        var show = $(this).text().toLowerCase().indexOf(q) > -1;
        $(this).toggle(show);
      });
    } catch (err) {
      console.warn('searchFilter fallback warning:', err);
    }
  };
</script>

<script>
  var base_url = "<?= base_url(); ?>";

  // Pastikan base_url global
  window.base_url = window.base_url || "<?= base_url(); ?>";
  var base_url = window.base_url;

  // ---------- helpers ----------
  function _fmtRupiah(val){
    try {
      val = Number(val || 0);
      return 'Rp ' + val.toLocaleString('id-ID');
    } catch(e){ return 'Rp ' + val; }
  }
  function _fmtShortAxis(value){
    value = Number(value || 0);
    var abs = Math.abs(value);
    if (abs >= 1000000000) return 'Rp ' + (value/1000000000).toFixed(0) + 'B';
    if (abs >= 1000000)    return 'Rp ' + (value/1000000).toFixed(0) + 'M';
    if (abs >= 1000)       return 'Rp ' + (value/1000).toFixed(0) + 'K';
    return 'Rp ' + value;
  }

  // Chart instances
  var _chartPendapatanBeban = null;
  var _chartArusKas = null;
  var _chartProdukTerlaris = null;
  var _produkTerlarisData = null; // simpan payload produk_terlaris dari server
  var _produkTerlarisMode = 'nilai'; // default

  var _chartPelangganTerbesar = null;
  var _chartKomposisiAkun = null;

  // ====== RANGE FILTER (Produk Terlaris & Pelanggan Terbesar) ======
  var _extraRange = '3m'; // default ketika pertama kali dibuka

  function _rangeLabel(r){
    switch(String(r||'').toLowerCase()){
      case 'month': return 'Bulan Ini';
      case '6m':    return '6 Bulan Terakhir';
      case 'year':  return 'Tahun Ini';
      case '3m':
      default:      return '3 Bulan Terakhir';
    }
  }

  function _syncRangeDropdownUI(range){
    range = range || '3m';
    $('.range-dd .btn-range').each(function(){
      $(this).attr('data-range', range).text(_rangeLabel(range));
    });

    $('.range-dd .dropdown-item').removeClass('active');
    $('.range-dd .dropdown-item[data-range="'+range+'"]').addClass('active');
  }


  // Detect Chart.js v3+ (fallback)
  function _isChartV3(){
    try { return !!(Chart && Chart.version && parseInt(Chart.version.split('.')[0],10) >= 3); }
    catch(e){ return false; }
  }

  // =========================================================
  // 1) Pendapatan vs Beban + Arus Kas (6 bulan)
  // =========================================================
  function load_dashboard_charts(){
    $.ajaxQueue({
      url: base_url + "penjualan/grafik_dashboard_6bulan",
      cache: false,
      dataType: "json",
      beforeSend: function(){
        $("#LoadingGrafikPendapatanBeban").loading();
        $("#LoadingGrafikArusKas").loading();
      },
      success: function(res){
        $("#LoadingGrafikPendapatanBeban").loading('stop');
        $("#LoadingGrafikArusKas").loading('stop');
        if (!res || !res.labels) return;
        renderPendapatanBeban(res);
        renderArusKas(res);
      },
      error: function(){
        $("#LoadingGrafikPendapatanBeban").loading('stop');
        $("#LoadingGrafikArusKas").loading('stop');
      }
    });
  }

  function renderPendapatanBeban(res){
    var el = document.getElementById('chartPendapatanBeban');
    if (!el || typeof Chart === 'undefined') return;

    if (_chartPendapatanBeban) _chartPendapatanBeban.destroy();

    _chartPendapatanBeban = new Chart(el, {
      type: 'bar',
      data: {
        labels: res.labels,
        datasets: [
          { label: 'Pendapatan', data: res.pendapatan || [], backgroundColor: 'rgba(34,197,94,0.85)', maxBarThickness: 34 },
          { label: 'Beban',      data: res.beban || [],      backgroundColor: 'rgba(239,68,68,0.85)', maxBarThickness: 34 }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        legend: { display: true, position: 'bottom', labels:{ usePointStyle:true, boxWidth:8 } },
        tooltips: {
          callbacks: {
            label: function(tooltipItem, data){
              var ds = data.datasets[tooltipItem.datasetIndex];
              return (ds.label || 'Nilai') + ': ' + _fmtRupiah(tooltipItem.yLabel);
            }
          }
        },
        scales: {
          xAxes: [{ gridLines:{ display:false, drawBorder:false }, ticks:{ maxRotation:0, autoSkip:true } }],
          yAxes: [{ ticks:{ beginAtZero:true, callback:function(v){ return _fmtShortAxis(v); } },
                    gridLines:{ color:"rgb(234, 236, 244)", drawBorder:false } }]
        }
      }
    });
  }

  function renderArusKas(res){
    var el = document.getElementById('chartArusKas');
    if (!el || typeof Chart === 'undefined') return;

    if (_chartArusKas) _chartArusKas.destroy();

    _chartArusKas = new Chart(el, {
      type: 'line',
      data: {
        labels: res.labels,
        datasets: [{
          label: 'Arus Kas Pendapatan',
          data: res.arus_kas || [],
          lineTension: 0.25,
          borderColor: 'rgba(59,130,246,1)',
          backgroundColor: 'rgba(59,130,246,0.12)',
          pointRadius: 3,
          pointBackgroundColor: 'rgba(59,130,246,1)',
          fill: true
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        legend: { display: true, position: 'bottom', labels:{ usePointStyle:true, boxWidth:8 } },
        tooltips: {
          mode: 'index',
          intersect: false,
          callbacks: {
            label: function(tooltipItem){
              return 'Arus Kas: ' + _fmtRupiah(tooltipItem.yLabel); } } },
        scales: {
          xAxes: [{ gridLines:{ display:false, drawBorder:false }, ticks:{ maxRotation:0, autoSkip:true } }],
          yAxes: [{ ticks:{ beginAtZero:true, callback:function(v){ return _fmtShortAxis(v); } },
                    gridLines:{ color:"rgb(234, 236, 244)", drawBorder:false } }]
        },
        elements: { line: { borderWidth: 3 } }
      }
    });
  }

  // =========================================================
  // 2) Produk terlaris + Pelanggan terbesar + Komposisi akun
  // =========================================================
  function load_dashboard_extra_charts(range){
  range = range || _extraRange || '3m';

  $.ajaxQueue({
    url: base_url + "penjualan/dashboard_extra_charts",
    cache: false,
    dataType: "json",
    data: { range: range }, // <--- kirim pilihan range ke server
    beforeSend: function(){
      $("#LoadingProdukTerlaris").loading();
      $("#LoadingPelangganTerbesar").loading();
      $("#LoadingKomposisiAkun").loading();
    },
    success: function(res){
      $("#LoadingProdukTerlaris").loading('stop');
      $("#LoadingPelangganTerbesar").loading('stop');
      $("#LoadingKomposisiAkun").loading('stop');

      if (!res) return;

      _produkTerlarisData = res.produk_terlaris || null;
      renderProdukTerlaris(_produkTerlarisData, _produkTerlarisMode);

      renderPelangganTerbesar(res.pelanggan_terbesar || {});
      renderStokMenipis(res.stok_menipis || []);
    },
    error: function(){
      $("#LoadingProdukTerlaris").loading('stop');
      $("#LoadingPelangganTerbesar").loading('stop');
      $("#LoadingKomposisiAkun").loading('stop');
    }
  });
}


  function renderProdukTerlaris(obj, mode){
  var el = document.getElementById('chartProdukTerlaris');
  if (!el || typeof Chart === 'undefined') return;

  mode = mode || 'nilai';
  obj = obj || {};

  var payload = (mode === 'qty') ? (obj.qty || {}) : (obj.nilai || {});
  var labels = payload.labels || [];
  var values = payload.values || [];

  if (_chartProdukTerlaris) _chartProdukTerlaris.destroy();

  _chartProdukTerlaris = new Chart(el, {
    type: 'doughnut',
    data: {
      labels: labels,
      datasets: [{
        data: values,
        backgroundColor: [
          'rgba(59,130,246,0.9)','rgba(16,185,129,0.9)','rgba(245,158,11,0.9)',
    'rgba(239,68,68,0.9)','rgba(139,92,246,0.9)','rgba(14,165,233,0.9)',
    'rgba(100,116,139,0.9)','rgba(236,72,153,0.9)','rgba(34,197,94,0.9)','rgba(249,115,22,0.9)'
        ],
        borderWidth: 0
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      cutoutPercentage: 70,
      legend: { display: true, position: 'right', labels:{ boxWidth:10 } },
      tooltips: {
        callbacks: {
          label: function(t, data){
            var label = data.labels[t.index] || 'Produk';
            var val = data.datasets[0].data[t.index] || 0;

            if (mode === 'qty') {
              return label + ': ' + val + ' pcs';
            }
            return label + ': ' + _fmtRupiah(val);
          }
        }
      }
    }
  });
}

$(document).on('click', '.btn-produk-mode', function(){
  var mode = $(this).data('mode') || 'nilai';
  _produkTerlarisMode = mode;

  $('.btn-produk-mode').removeClass('active');
  $(this).addClass('active');

  if (_produkTerlarisData) {
    renderProdukTerlaris(_produkTerlarisData, _produkTerlarisMode);
  }
});


// klik range dropdown (Produk Terlaris & Pelanggan Terbesar)
$(document).on('click', '.range-dd .dropdown-item', function(e){
  e.preventDefault();
  var range = $(this).data('range') || '3m';

  _extraRange = range;
  _syncRangeDropdownUI(_extraRange);

  // reload data sesuai range
  load_dashboard_extra_charts(_extraRange);
});




  function renderPelangganTerbesar(obj){
    var el = document.getElementById('chartPelangganTerbesar');
    if (!el || typeof Chart === 'undefined') return;

    if (_chartPelangganTerbesar) _chartPelangganTerbesar.destroy();

    var v3 = _isChartV3();
    var cfg = {
      type: (v3 ? 'bar' : (Chart.controllers && Chart.controllers.horizontalBar ? 'horizontalBar' : 'bar')),
      data: {
        labels: obj.labels || [],
        datasets: [{
          label: 'Total Transaksi',
          data: obj.values || [],
          backgroundColor: 'rgba(59,130,246,0.75)',
          borderWidth: 0
        }]
      },
      options: v3 ? {
        indexAxis: 'y',
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: { display: false },
          tooltip: {
            callbacks: {
              label: function(ctx){ return 'Total: ' + _fmtRupiah(ctx.parsed.x); }
            }
          }
        },
        scales: {
          x: { ticks:{ callback:(v)=>_fmtShortAxis(v) } }
        }
      } : {
        responsive: true,
        maintainAspectRatio: false,
        legend: { display: false },
        tooltips: { callbacks:{ label:function(t){ return 'Total: ' + _fmtRupiah(t.xLabel); } } },
        scales: {
          xAxes: [{ ticks:{ callback:function(v){ return _fmtShortAxis(v); } } }],
          yAxes: [{ gridLines:{ display:false } }]
        }
      }
    };

    _chartPelangganTerbesar = new Chart(el, cfg);
  }

function _escHtml(s){
  return String(s || '')
    .replace(/&/g,'&amp;')
    .replace(/</g,'&lt;')
    .replace(/>/g,'&gt;')
    .replace(/"/g,'&quot;')
    .replace(/'/g,'&#39;');
}

function _unitNorm(u){
  u = String(u || '').trim();
  if (!u) return '';
  var k = u.toUpperCase();

  var map = {
    'MTR':'m','METER':'m','M':'m',
    'CM':'cm',
    'PCS':'pcs','PIECES':'pcs',
    'LBR':'lbr'
  };
  return map[k] || u.toLowerCase();
}

function _fmtStok(val){
  val = Number(val || 0);
  if (!isFinite(val)) val = 0;

  // integer tampil tanpa desimal, float max 2 desimal (buang nol belakang)
  var isInt = Math.abs(val - Math.round(val)) < 0.000000001;
  if (isInt) return Math.round(val).toLocaleString('id-ID');

  var s = val.toLocaleString('id-ID', { minimumFractionDigits: 0, maximumFractionDigits: 2 });
  return s;
}

function _lowBadge(total, minimum, status){
  total = Number(total || 0);
  if (!isFinite(total)) total = 0;

  minimum = Number(minimum || 0);
  if (!isFinite(minimum)) minimum = 0;

  status = String(status || '').toLowerCase();
  var label = '';
  if (status === 'stok_kosong' || total <= 0) {
    label = 'STOK KOSONG';
  } else if (status === 'low_stock' || (minimum > 0 && total <= minimum)) {
    label = 'LOW STOCK';
  }

  if (!label) return '';

  var badgeStyle = 'font-size:11px;letter-spacing:.2px;display:inline-flex;align-items:center;gap:4px;border-radius:6px;padding:3px 7px;background:#ff4d4f;border:1px solid #ff4d4f;color:#fff;';
  var icon = '<i class="fa fa-warning" style="color:#ffd43b;font-size:15px;line-height:1;text-shadow:-1px 0 #111,0 1px #111,1px 0 #111,0 -1px #111;"></i>';
  return '<span class="badge badge-danger lowstock-badge" style="'+badgeStyle+'">'+icon+'<span>'+label+'</span></span>';

  var u = (unitNorm || '').toLowerCase();
  var isLbrPcs = (u === 'lbr' || u === 'pcs');
  var isMeter  = (u === 'm' || u === 'meter');

  // merah (danger)
  var red = '<span class="badge badge-danger lowstock-badge">⚠️ LOW STOCK</span>';
  // orange (danger oren sesuai request)
  var org = '<span class="badge lowstock-badge badge-low-orange">⚠️ LOW STOCK</span>';

  if (isLbrPcs){
    if (total >= 0 && total <= 30) return red;
    if (total >= 31 && total <= 50) return org;
    return '';
  }

  if (isMeter){
    if (total >= 0 && total <= 50) return red;
    if (total >= 51 && total <= 100) return org;
    return '';
  }

  // fallback satuan lain (biar tetap ada indikator)
  if (total >= 0 && total <= 5) return red;
  if (total >= 6 && total <= 10) return org;
  return '';
}

function renderStokMenipis(list){
  list = list || [];
  var $tbody = $('#load-stok-menipis');
  if (!$tbody.length) return;

  if (!list.length){
    $tbody.html('<tr><td colspan="2" class="text-center text-muted py-3">Tidak ada stok kosong atau low stock</td></tr>');
    return;
    $tbody.html('<tr><td colspan="2" class="text-center text-muted py-3">Tidak ada stok menipis 🎉</td></tr>');
    return;
  }

  var html = '';
  for (var i=0; i<list.length; i++){
    var r = list[i] || {};
    var title = _escHtml(r.title || r.nama || '-');

    // dukung beberapa kemungkinan key dari server
    var totalNum = Number(
      (r.stok_total !== undefined) ? r.stok_total :
      (r.total !== undefined) ? r.total :
      (r.sisa !== undefined) ? r.sisa : 0
    );

    var unit = _unitNorm(r.satuan || r.unit || r.unit_name || '');
    var numText = _fmtStok(totalNum);
    var unitHtml = unit ? ('<small class="text-muted">'+_escHtml(unit)+'</small>') : '';
    var minimumNum = Number(
      (r.batas_minimum_stok !== undefined) ? r.batas_minimum_stok :
      (r.minimum !== undefined) ? r.minimum : 0
    );

    var badgeHtml = _lowBadge(totalNum, minimumNum, r.stok_status || '');
    if (!badgeHtml) continue;

    html += '<tr>' +
      '<td title="'+title+'">'+ title +'</td>' +
      '<td class="text-right">' +
        '<div class="lowstock-value">' +
          '<span class="font-weight-bold">'+ _escHtml(numText) +'</span>' +
          unitHtml +
          badgeHtml +
        '</div>' +
      '</td>' +
    '</tr>';
  }

  if (!html) {
    html = '<tr><td colspan="2" class="text-center text-muted py-3">Tidak ada stok kosong atau low stock</td></tr>';
  }

  $tbody.html(html);
}





  var _lastInvoiceHtml = '';

  function loadinvoice() {
    $.ajaxQueue({
      url:  base_url + "penjualan/list_invoice",
      cache: false,
      beforeSend: function () {
        if (_lastInvoiceHtml === '') {
          $("#LoadingInvoice").loading();
        }
      },
      success: function (data) {
        $("#LoadingInvoice").loading('stop');

        if (data !== _lastInvoiceHtml) {
          $('#load-invoice').html(data);
          _lastInvoiceHtml = data;
        }
      }
    });
  }

  $(document).ready(function () {

    loadinvoice();
    loadcount();
    hari_ini();
    baru();
    pending();
    batal();
    piutang_bulan();
    kas_keluar_bulan();
    pembelian_bulan();
    konsumen_total();
    load_dashboard_charts();
    _syncRangeDropdownUI(_extraRange);
    load_dashboard_extra_charts(_extraRange);
    load_dashboard_saldo_kas();
    load_dashboard_mutasi_kas();






    setInterval(function () {
      loadinvoice();
      loadcount();
      hari_ini();
      baru();
      pending();
      batal();
      piutang_bulan();
      kas_keluar_bulan();
      pembelian_bulan();
      konsumen_total();
      load_dashboard_charts();
      load_dashboard_extra_charts(_extraRange);
      load_dashboard_saldo_kas();
      load_dashboard_mutasi_kas();




    }, 120000);

  });
</script>
