<div class="container-fluid omset-report-page" id="container-wrapper">
  <div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-gray-800">Rincian penjualan</h1>
    <ol class="breadcrumb omset-breadcrumb mb-0">
      <li class="breadcrumb-item"><a href="./">Laporan</a></li>
      <li class="breadcrumb-item active" aria-current="page">Rincian penjualan</li>
    </ol>
  </div>
  <div class="row">
    <div class="col-md-12">
      <div class="card omset-report-card">
        <!-- ============ FILTER BAR (REPLACEMENT) ============ -->
        <div class="card-header pb-2">
  <div class="filter-bar filter-bar--2rows">

    <!-- ================= ROW 1 (FILTER UTAMA) ================= -->
    <div class="fb-row fb-row-1">
      <!-- SORT -->
      <div class="fb-item">
        <span class="chip-label">SORT</span>
        <select id="sortBy" class="form-control form-control-sm custom-select fb-input" onchange="search_Omset()">
          <option value="ASC">ASC</option>
          <option value="DESC" selected>DESC</option>
        </select>
      </div>

      <!-- LIMIT -->
      <div class="fb-item">
        <span class="chip-label">LIMIT</span>
        <select id="limits" name="limits" class="form-control form-control-sm custom-select fb-input" onchange="search_Omset()">
          <option value="10">10</option>
          <option value="20">20</option>
          <option value="50">50</option>
          <option value="100">100</option>
          <option value="500" selected>500</option>
          <option value="1000">1000</option>
        </select>
      </div>

      <!-- KASIR -->
      <div class="fb-item fb-grow">
        <span class="chip-label">KASIR</span>
        <select name="user" id="user" class="form-control form-control-sm custom-select fb-input" onchange="search_Omset()">
          <option value="0">Semua</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>

      <!-- PELANGGAN -->
      <div class="fb-item fb-grow fb-pelanggan">
        <span class="chip-label">PELANGGAN</span>
        <input type="text" class="form-control form-control-sm fb-input" name="pelanggan" id="pelanggan" placeholder="Ketik nama pelanggan">
        <input type="hidden" class="form-control form-control-sm" name="id_pelanggan" id="id_pelanggan">
      </div>
    </div>

    <!-- ================= ROW 2 (TANGGAL + PRESET + AKSI) ================= -->
    <div class="fb-row fb-row-2">
      <!-- TANGGAL -->
      <div class="fb-item fb-daterange">
        <span class="chip-label">TANGGAL</span>
        <div id="date-omset" class="w-100">
          <div class="input-daterange input-group input-group-sm">
            <input type="text" onchange="search_Omset()" value="<?=$dari;?>" class="form-control form-control-sm fb-input" name="dari" id="dari" placeholder="Dari">
            <span class="date-sep">–</span>
            <input type="text" onchange="search_Omset()" value="<?=$sampai;?>" class="form-control form-control-sm fb-input" name="sampai" id="sampai" placeholder="Sampai">
          </div>
        </div>
      </div>

      <!-- PRESET -->
      <div class="fb-item fb-presets">
        <div class="preset-group">
          <button type="button" class="btn btn-light btn-sm preset" data-preset="hari_ini">Hari ini</button>
          <button type="button" class="btn btn-light btn-sm preset" data-preset="kemarin">Kemarin</button>
          <button type="button" class="btn btn-light btn-sm preset" data-preset="minggu_ini">Minggu ini</button>
          <button type="button" class="btn btn-light btn-sm preset" data-preset="minggu_kemarin">Minggu kemarin</button>
        </div>
      </div>

      <!-- ACTIONS -->
      <div class="fb-actions">
        <button type="button" data-toggle="tooltip" class="btn btn-ghost-danger btn-sm clear" id="awal"
                data-original-title="Clear" onclick="clearSearch('<?=$dari;?>')">
          <i class="fa fa-times"></i><span class="d-none d-sm-inline">&nbsp;Clear</span>
        </button>

        <button type="button" data-info="harian" class="btn btn-primary btn-sm" data-id="0" onclick="search_Omset()">
          <i class="fa fa-search"></i><span class="d-none d-sm-inline">&nbsp;Lihat</span>
        </button>

        <button type="button" class="btn btn-success btn-sm flat" id="export_omset">
          <i class="fa fa-file-excel-o"></i><span class="d-none d-sm-inline">&nbsp;Export</span>
        </button>

        <button type="button" class="btn btn-danger btn-sm flat" id="export_omset_pdf">
          <i class="fa fa-file-pdf-o"></i><span class="d-none d-sm-inline">&nbsp;PDF</span>
        </button>
      </div>
    </div>

  </div>
</div>

        <!-- ============ /FILTER BAR ============ -->


        
        <div class="card-body table-responsive">
          <div class="card-block">
            <!--div id="data_omset"></div-->
            <div class="post-list pt-0" id="dataListOmset">
            </div>
          </div><!-- /.card-body -->
        </div><!-- /.card-body -->
      </div><!-- /.card -->
    </div>
  </div>
</div>
<div aria-hidden="true" aria-labelledby="myModalLabel" class="modal left fade" id="OpenModalWa" role="dialog" tabindex="-1">
  <div class="modal-dialog" id="kirim-pesan">
    <div class="modal-content flat">
      <div class="modal-header pt-1 pb-1">
        <h4 class="modal-title" id="WaLabel">Kirim Invoice</h4>
        <button aria-hidden="true" class="close" data-dismiss="modal" type="button">&times;</button>
      </div>
      <div class="modal-body">
        <div class="load-data-wa"></div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-success btn-sm flat kirim_pesan" type="button"><i class="fa fa-send"></i>&nbsp;Kirim</button> 
        <button class="btn btn-danger btn-sm flat" data-dismiss="modal" type="button">Batal</button> 
      </div>
    </div>
  </div>
</div>
<form id="form_export" action="<?=url_https();?>pembukuan/export_omset" method="post" target="_blank">
  <input type="hidden" name="dari" id="cetak_dari" value="<?=$dari;?>">
  <input type="hidden" name="sampai" id="cetak_sampai" value="<?=$sampai;?>">
  <input type="hidden" name="id_user" id="id_user_dari" value="0">
  <input type="hidden" name="limit" id="limit_export">
  <input type="hidden" name="sort" id="sort_export" value="DESC">
  <input type="hidden" name="cetak_pelanggan" id="cetak_pelanggan">
</form>
<form id="form_export_pdf" action="<?=url_https();?>pembukuan/export_omset_pdf" method="post" target="_blank">
  <input type="hidden" name="dari" id="pdf_dari" value="<?=$dari;?>">
  <input type="hidden" name="sampai" id="pdf_sampai" value="<?=$sampai;?>">
  <input type="hidden" name="id_user" id="pdf_id_user" value="0">
  <input type="hidden" name="limit" id="pdf_limit">
  <input type="hidden" name="sort" id="pdf_sort" value="DESC">
  <input type="hidden" name="cetak_pelanggan" id="pdf_pelanggan">
</form>
<!-- ============ CSS (REPLACEMENT/MERGE) ============ -->
<style>
  /* --- Reset kecil agar tampilan kompak --- */
  .form-control-sm, .custom-select.form-control-sm { height: 36px; padding: 4px 8px; font-size: .875rem; }
  .input-group-sm > .form-control { height: 36px; }
  button, input, select, textarea { font: inherit; }

  /* ====== WRAPPER FILTER 2 BARIS ====== */
  .filter-bar.filter-bar--2rows{
    display:flex;
    flex-direction:column;
    gap:12px;             /* jarak antar baris */
  }

  /* Baris */
  .fb-row{
    display:flex;
    flex-wrap:wrap;
    gap:10px;
    align-items:center;
  }

  /* Item */
  .fb-item{ display:flex; align-items:center; gap:8px; min-width: 0; }
  .fb-input{ min-width:0; width:100%; }

  /* Chip label biru */
  .chip-label{
    display:inline-flex; align-items:center; justify-content:center;
    height:36px; padding:0 12px; border-radius:8px;
    background:#3b57c7; color:#fff; font-weight:600; letter-spacing:.3px;
    white-space:nowrap;
    box-shadow:inset 0 -1px 0 rgba(255,255,255,.15);
  }

  /* Ukuran fleksibel per item (biar rapi di scaling 150%) */
  .fb-row-1 .fb-item{ flex: 0 1 210px; }
  .fb-row-1 .fb-grow{ flex: 1 1 260px; }
  .fb-row-1 .fb-pelanggan{ flex: 1 1 360px; }

  /* Row 2: tanggal lebih prioritas lebar */
  .fb-row-2 .fb-daterange{ flex: 1 1 340px; }
  .fb-row-2 .fb-presets{ flex: 0 1 auto; }
  .fb-row-2 .fb-actions{ flex: 0 0 auto; margin-left:auto; }

  /* Date range separator */
  .date-sep{
    display:inline-flex; align-items:center; padding:0 6px;
    color:#64748b; font-weight:600;
  }

  /* Tombol preset */
  .preset-group{ display:flex; gap:8px; flex-wrap:wrap; }
  .preset.btn{
    border:1px solid #d1d5db; background:#fff; color:#111827;
    padding:4px 10px; border-radius:8px; height:36px; line-height:1;
    box-shadow:inset 0 -1px 0 rgba(0,0,0,.03);
  }
  .preset.btn:hover{ background:#f3f4f6; }
  .preset.btn.active{ background:#4b5563; color:#fff; border-color:#4b5563; }

  /* Tombol aksi */
  .fb-actions{ display:flex; align-items:center; gap:8px; }
  .btn-ghost-danger{
    background:#fff; border:1px solid #e5e7eb; color:#ef4444;
  }
  .btn-ghost-danger:hover{ background:#fee2e2; border-color:#fecaca; color:#b91c1c; }

  /* Custom select caret */
  .custom-select{
    display:inline-block; width:100%;
    padding:4px 30px 4px 8px;
    appearance:none; background-clip:padding-box;
    background-image:
      linear-gradient(45deg, transparent 50%, #6b7280 50%),
      linear-gradient(135deg, #6b7280 50%, transparent 50%);
    background-position: calc(100% - 16px) 50%, calc(100% - 12px) 50%;
    background-size: 6px 6px, 6px 6px;
    background-repeat:no-repeat;
    border:1px solid #e5e7eb; border-radius:8px;
  }
  .custom-select:focus{
    border-color:#a5b4fc;
    box-shadow:0 0 0 .2rem rgba(99,102,241,.15);
  }

  /* ================== RESPONSIVE ================== */
  @media (max-width: 992px){
    /* Row2: actions turun kanan bawah kalau sempit */
    .fb-row-2 .fb-actions{ margin-left:0; }
  }

  @media (max-width: 576px){
    /* Tetap 2 grup baris, tapi isi di dalamnya jadi full width */
    .fb-row-1 .fb-item,
    .fb-row-2 .fb-item{ flex: 1 1 100%; }

    /* Tanggal: 2 input jadi grid 2 kolom */
    .fb-daterange .input-group{
      display:grid;
      grid-template-columns: 1fr 1fr;
      gap:8px;
      width:100%;
    }
    .fb-daterange .date-sep{ display:none; }

    /* Preset: grid 2 kolom */
    .preset-group{
      display:grid;
      grid-template-columns: 1fr 1fr;
      gap:8px;
      width:100%;
    }
    .preset-group .preset{ width:100%; }

    /* Actions: 2 tombol full */
    .fb-actions{
      width:100%;
      display:grid;
      grid-template-columns: 1fr 1fr;
      gap:8px;
    }
    .fb-actions .btn{ width:100%; }
  }

  /* ====== FIX & POLISH BOOTSTRAP DATEPICKER ====== */
  .datepicker-dropdown,
  .datepicker.datepicker-dropdown {
    z-index: 2055 !important;
    border: 1px solid #e5e7eb;
    border-radius: 10px;
    box-shadow: 0 10px 30px rgba(2,6,23,.15);
    font-size: 13px;
    padding: 6px;
    background: #ffffff;
  }
  .datepicker-dropdown table tr td,
  .datepicker-dropdown table tr th{
    width: 34px; height: 30px; line-height: 30px; border-radius: 6px;
  }
  .datepicker-dropdown table tr td.active,
  .datepicker-dropdown table tr td.active:hover{
    background: #4b5563 !important; color:#fff !important; border-color:#4b5563 !important;
  }
  .datepicker-dropdown table tr td.day:hover{ background:#f3f4f6; color:#111827; }
  .datepicker-dropdown table tr td.today,
  .datepicker-dropdown table tr td.today:hover{ background:#eef2ff; color:#111827; border-color:#c7d2fe; }

  /* ===== Tampilan modern khusus halaman Rincian Penjualan ===== */
  .omset-report-page{
    color:#344054;
  }
  .omset-report-page > .d-sm-flex{
    margin-bottom:16px!important;
  }
  .omset-report-page .h3{
    color:#1d2939!important;
    font-size:24px;
    line-height:1.3;
    font-weight:750;
    letter-spacing:-.2px;
  }
  .omset-report-page .omset-breadcrumb{
    padding:0;
    background:transparent;
    color:#667085;
    font-size:12px;
    font-weight:600;
  }
  .omset-report-page .omset-breadcrumb a{
    color:#1769e8;
  }
  .omset-report-page .omset-report-card{
    border:0;
    background:transparent;
    box-shadow:none;
  }
  .omset-report-page .omset-report-card > .card-header{
    padding:18px 20px!important;
    border:1px solid #e4e9f1;
    border-radius:11px;
    background:#fff;
    box-shadow:0 6px 18px rgba(15,23,42,.07);
  }
  .omset-report-page .omset-report-card > .card-body{
    padding:18px 0 0;
    overflow:visible;
  }
  .omset-report-page .filter-bar--2rows{
    gap:16px;
  }
  .omset-report-page .fb-row{
    gap:18px;
    align-items:center;
  }
  .omset-report-page .fb-row-1{
    display:grid;
    grid-template-columns:190px 190px minmax(300px,1fr) minmax(360px,1.15fr);
  }
  .omset-report-page .fb-row-2{
    display:grid;
    grid-template-columns:minmax(510px,1fr) auto auto;
  }
  .omset-report-page .fb-row-1 .fb-item,
  .omset-report-page .fb-row-1 .fb-grow,
  .omset-report-page .fb-row-1 .fb-pelanggan,
  .omset-report-page .fb-row-2 .fb-daterange,
  .omset-report-page .fb-row-2 .fb-presets,
  .omset-report-page .fb-row-2 .fb-actions{
    width:100%;
    min-width:0;
    margin:0;
  }
  .omset-report-page .chip-label{
    height:40px;
    min-width:auto;
    padding:0;
    border-radius:0;
    background:transparent;
    color:#344054;
    box-shadow:none;
    font-size:11px;
    line-height:1;
    font-weight:800;
    letter-spacing:.02em;
  }
  .omset-report-page .fb-item{
    gap:10px;
  }
  .omset-report-page .fb-input,
  .omset-report-page .custom-select,
  .omset-report-page .form-control-sm{
    height:40px;
    border:1px solid #dfe5ee;
    border-radius:6px;
    background-color:#fff;
    color:#344054;
    font-size:13px;
    font-weight:600;
    box-shadow:none;
  }
  .omset-report-page .custom-select:focus,
  .omset-report-page .form-control:focus{
    border-color:#1769e8;
    box-shadow:0 0 0 3px rgba(23,105,232,.12);
  }
  .omset-report-page .fb-daterange .input-group{
    display:grid;
    grid-template-columns:minmax(0,1fr) 20px minmax(0,1fr);
    align-items:center;
    width:100%;
  }
  .omset-report-page .fb-daterange{
    display:grid;
    grid-template-columns:auto minmax(0,1fr);
    align-items:center;
  }
  .omset-report-page .fb-daterange #date-omset{
    width:100%;
    min-width:0;
  }
  .omset-report-page .fb-daterange .input-group > .form-control{
    width:100%!important;
    min-width:0!important;
    max-width:none!important;
    flex:none!important;
  }
  .omset-report-page .fb-daterange input{
    text-align:left;
    padding-left:12px;
  }
  .omset-report-page .date-sep{
    justify-content:center;
    padding:0;
  }
  .omset-report-page .preset-group{
    display:grid;
    grid-template-columns:repeat(4,minmax(92px,1fr));
    gap:9px;
  }
  .omset-report-page .preset.btn{
    height:40px;
    padding:0 12px;
    border:1px solid #dfe5ee;
    border-radius:6px;
    background:#fff;
    color:#344054;
    box-shadow:0 2px 5px rgba(15,23,42,.05);
    font-size:12px;
    font-weight:700;
  }
  .omset-report-page .preset.btn:hover,
  .omset-report-page .preset.btn.active{
    border-color:#b9cce9;
    background:#eef5ff;
    color:#1769e8;
  }
  .omset-report-page .fb-actions{
    display:grid;
    grid-template-columns:82px 86px 94px 72px;
    gap:9px;
  }
  .omset-report-page .fb-actions .btn{
    height:40px;
    border-radius:6px;
    font-size:12px;
    font-weight:700;
    box-shadow:0 4px 9px rgba(15,23,42,.10);
  }
  .omset-report-page .fb-actions .btn-primary{
    border-color:#1769e8;
    background:#1769e8;
  }
  .omset-report-page #export_omset{
    border:1px solid #b9cce9;
    background:#fff;
    color:#1769e8;
    font-weight:800;
  }
  .omset-report-page #export_omset_pdf{
    border:1px solid #f0b8bd;
    background:#fff;
    color:#dc3545;
    font-weight:800;
  }
  .omset-report-page .btn-ghost-danger{
    border-color:#f0d3d6;
    color:#ef4444;
    box-shadow:none!important;
  }

  /* Lima filter desktop mengikuti gaya halaman Kategori Produk */
  @media (min-width:768px){
    .omset-report-page .fb-row-1{
      gap:.5rem;
    }

    .omset-report-page .fb-row-1 .fb-item,
    .omset-report-page .fb-daterange{
      gap:0;
      align-items:stretch;
    }

    .omset-report-page .fb-row-1 .chip-label,
    .omset-report-page .fb-daterange > .chip-label{
      display:inline-flex;
      align-items:center;
      justify-content:center;
      height:36px;
      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;
      letter-spacing:0;
      white-space:nowrap;
      box-shadow:0 .125rem .25rem rgba(58,59,69,.2);
    }

    .omset-report-page .fb-row-1 .fb-input,
    .omset-report-page .fb-row-1 .custom-select,
    .omset-report-page .fb-daterange .fb-input{
      height:36px;
      min-height:36px;
      border-color:#d1d3e2;
      border-radius:0 .2rem .2rem 0;
      color:#344054;
      font-size:.875rem;
      font-weight:500;
      box-shadow:none;
    }

    .omset-report-page .fb-row-1 .fb-input,
    .omset-report-page .fb-row-1 .custom-select{
      border-left:0;
    }

    .omset-report-page .fb-row-1 .custom-select{
      padding-right:1.75rem;
    }

    .omset-report-page .fb-daterange #date-omset,
    .omset-report-page .fb-daterange .input-group{
      height:36px;
    }

    .omset-report-page .fb-daterange .input-group > .form-control:first-child{
      border-left:0;
      border-radius:0 .2rem .2rem 0;
    }

    .omset-report-page .fb-row-1 .fb-input:focus,
    .omset-report-page .fb-row-1 .custom-select:focus,
    .omset-report-page .fb-daterange .fb-input:focus{
      position:relative;
      z-index:2;
      border-color:var(--app-theme-color, #3f51b5);
      box-shadow:0 0 0 .15rem rgba(63,81,181,.18);
    }
  }

  @media (max-width:1400px){
    .omset-report-page .fb-row-1{
      grid-template-columns:repeat(2,minmax(220px,1fr));
    }
    .omset-report-page .fb-row-2{
      grid-template-columns:1fr;
      gap:12px;
    }
    .omset-report-page .preset-group{
      grid-template-columns:repeat(4,minmax(0,1fr));
    }
    .omset-report-page .fb-actions{
      width:100%;
      grid-template-columns:repeat(4,minmax(0,1fr));
    }
  }
  @media (max-width:767.98px){
    .omset-report-page .omset-breadcrumb{ display:none; }
    .omset-report-page .omset-report-card > .card-header{ padding:14px; }
    .omset-report-page .fb-row-1{ grid-template-columns:1fr; }
    .omset-report-page .fb-item{ align-items:flex-start; }
    .omset-report-page .chip-label{ min-width:72px; }
    .omset-report-page .preset-group{ grid-template-columns:repeat(2,minmax(0,1fr)); }
  }
</style>


<script>
  var date2 = new Date();
  $('#date-omset .input-daterange').datepicker({        
        format: 'dd/mm/yyyy',        
    "endDate": date2,
        autoclose: true,     
        todayHighlight: true,   
        todayBtn: 'linked',
  }); 
  
  search_Omset();
  function search_Omset(page_num){
    page_num = page_num?page_num:0;
    var user = $('#user').val();
    var dari = $('#dari').val();
    var sampai = $('#sampai').val();
    var sortBy = $('#sortBy').val();
    var limits = $('#limits').val();
    var id_pelanggan = $('#id_pelanggan').val();
    $('#limit_export').val(limits);
    var urlnya = base_url+"pembukuan/harian/"+page_num
    $.ajax({
      type: 'POST',
      url: urlnya,
      data:{page:page_num,user:user,dari:dari,sampai:sampai,sortBy:sortBy,limits:limits,id_pelanggan:id_pelanggan},
      beforeSend: function(){
        $('body').loading();
      },
      success: function(html){
        $('#dataListOmset').html(html);
        $('body').loading('stop');
      },
      error: function (xhr, ajaxOptions, thrownError) {
        sweet('Peringatan!!!',thrownError,'warning','warning');
        $('body').loading('stop');
      }
    });
  }
  
  function clearSearch(tgl){
    $('#dari').val(tgl);
    $('#pelanggan').val('');
    $('#id_pelanggan').val('');
    // set default limit 1000 saat halaman pertama kali dibuka
    $('#limits').val('1000');
    $('#limit_export').val('1000');
    search_Omset();

  }
  function search_omset(){
    $(".harian").click();
  }
  $(document).on('click','#export_omset',function(e){
    e.preventDefault();
    
    var total_u = $("#total_u").val();
    var dari = $("#dari").val();
    var sampai = $("#sampai").val();
    var iduser = $("#id_user").val();
    var pelanggan = $("#id_pelanggan").val();
    var sort = $("#sortBy").val();
    $("#cetak_dari").val(dari);
    $("#cetak_sampai").val(sampai);
    $("#id_user_dari").val(iduser);
    $("#cetak_pelanggan").val(pelanggan);
    $("#sort_export").val(sort);
    // console.log(total_u);return
    if(total_u==0){
      sweet('Peringatan!!!','Maaf total masih kosong','warning','warning');
      }else{
      $("#form_export").submit();
    }
  });

  $(document).on('click','#export_omset_pdf',function(e){
    e.preventDefault();

    $("#pdf_dari").val($("#dari").val());
    $("#pdf_sampai").val($("#sampai").val());
    $("#pdf_id_user").val($("#id_user").val());
    $("#pdf_pelanggan").val($("#id_pelanggan").val());
    $("#pdf_limit").val($("#limits").val());
    $("#pdf_sort").val($("#sortBy").val());
    $("#form_export_pdf").submit();
  });
  
  $("#pelanggan").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("|");
      id_arr = $(this).attr("id");
      id = id_arr.split("_");
      $("#pelanggan").val(names[0]);
      $("#id_pelanggan").val(names[1]);
      
    },
    change: function (event, ui) {
      if (ui.item == null) {
        id_arr = $(this).attr("id");
        id = id_arr.split("_");
        $("#pelanggan").val("-");
        $("#id_pelanggan").val("-");
        } else {
        var names = ui.item.data.split("|");
        id_arr = $(this).attr("id");
        id = id_arr.split("_");
        if (names[0] == "NONE") {
          $("#pelanggan").val("-");
          $("#id_pelanggan").val("-");
        }
      }
      search_Omset()
    },
  });
  
  $(".kirimwa").click(function(e) {
        e.preventDefault();
        var id = $(this).attr('data-id');
        var nomor = $(this).attr('data-nomor');
        var trx = $(this).attr('data-trx');
        var tgl = $(this).attr('data-tgl');
        
        $('#WaLabel').html('Kirim ' + trx);
        $('#OpenModalWa').modal({
            backdrop: 'static',
            keyboard: false
    })
        $.ajax({
            url: base_url + 'whatsapp/get_form_wa',
            data: {
                id: id,
                nomor: nomor,
                tgl: tgl
      },
            method: 'POST',
            dataType: 'html',
            beforeSend: function() {
                $('body').loading();
      },
            success: function(data) {
                $(".load-data-wa").html(data);
                $('body').loading('stop');
      },
            error: function(xhr, status, error) {
                var err = xhr.responseText;
                sweet('Server!!!', err, 'error', 'danger');
                $('body').loading('stop');
      }
    });
  });
    $(".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 () {
                $('#kirim-pesan').loading({zIndex:1070,message:'kirim pesan...'});
      },
            success: handleKirim
      ,error: function(xhr, status, error) {
                showNotif('top-right','Kirim pesan',error,'error');
                $('#kirim-pesan').loading('stop');
      }
    });
    
  });
  
  function handleKirim(data) {
    
    $('#kirim-pesan').loading('stop');
    $('#OpenModalWa').modal('hide'); 
    if(data.status=='offline'){
      showNotif('bottom-right','Kirim pesan',data.msg.detail,'danger');
      }else if(data.status==true){
      showNotif('bottom-right','Kirim pesan',data.msg.detail,'success');
      }else{
      var number = data.target; 
      var message = encodeURIComponent(data.msg);
      var url_wa = getLinkWhastapp(number,message)
      window.open(url_wa, '_blank');
    }
  }
  
  function getLinkWhastapp(number, message) {
    var url = 'https://wa.me/' 
    + number 
    + '?text='
    + message
    return url
  }


  // helper format dd/mm/yyyy
  function fmt(d){
    const dd = String(d.getDate()).padStart(2,'0');
    const mm = String(d.getMonth()+1).padStart(2,'0');
    const yy = d.getFullYear();
    return dd+'/'+mm+'/'+yy;
  }
  // start Monday
  function startOfWeek(d){
    const day = d.getDay(); // 0=Sun .. 6=Sat
    const diff = (day === 0 ? -6 : 1 - day); // Monday
    const s = new Date(d); s.setDate(d.getDate()+diff); s.setHours(0,0,0,0);
    return s;
  }
  function endOfWeek(d){
    const s = startOfWeek(d);
    const e = new Date(s); e.setDate(s.getDate()+6); e.setHours(0,0,0,0);
    return e;
  }

  // apply preset -> set #dari/#sampai -> trigger search
  function applyPreset(kind){
    const today = new Date(); today.setHours(0,0,0,0);
    let d1 = today, d2 = today;

    if(kind==='hari_ini'){
      d1 = today; d2 = today;
    }else if(kind==='kemarin'){
      d1 = new Date(today); d1.setDate(today.getDate()-1);
      d2 = new Date(d1);
    }else if(kind==='minggu_ini'){
      d1 = startOfWeek(today);
      d2 = today;
    }else if(kind==='minggu_kemarin'){
      const thisStart = startOfWeek(today);
      d2 = new Date(thisStart); d2.setDate(thisStart.getDate()-1);
      d1 = new Date(d2); d1.setDate(d2.getDate()-6);
    }

    const v1 = fmt(d1), v2 = fmt(d2);
    // jika pakai bootstrap-datepicker, cukup set .val lalu trigger change
    $('#dari').val(v1).trigger('change');
    $('#sampai').val(v2).trigger('change');

    // state tombol aktif
    $('.preset').removeClass('active');
    $('.preset[data-preset="'+kind+'"]').addClass('active');
  }

  // inisialisasi datepicker (tetap milikmu, hanya dirapikan dikit)
  var date2 = new Date();
  var date2 = new Date();
$('#date-omset .input-daterange').datepicker({
  format: 'dd/mm/yyyy',
  endDate: date2,
  autoclose: true,
  todayHighlight: true,
  todayBtn: 'linked',
  container: 'body',              // << penting: hindari ketutup overflow/z-index
  orientation: 'auto bottom'      // << muncul di bawah input bila cukup ruang
});


  // klik preset
  $(document).on('click', '.preset', function(){
    applyPreset($(this).data('preset'));
    // otomatis muat data
    search_Omset();
  });

  // panggil pertama kali agar data tampil
  search_Omset();

</script>     

<script>
  // Hanya membuat jika belum ada (tidak menimpa implementasi asli, jika ada)
  window.searchFilter = window.searchFilter || function(termOrInput, tableSelector) {
    try {
      // Fallback sederhana: filter baris tabel mengandung teks
      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; // tidak ada jQuery, cukup diam
      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) {
      // Jangan biarkan error menghentikan script lain
      console.warn('searchFilter fallback warning:', err);
    }
  };
</script>
