<?php
/* =========================
 * PRE-COMPUTE TOTALS untuk Ringkasan Header
 * ========================= */
$H_total_order   = 0;
$H_total_pajak   = 0;
$H_total_bayar   = 0;
$H_total_diskon  = 0;
$H_total_piutang = 0;

if (!empty($result)) {
  foreach ($result as $row) {

    $rows         = bayar($row['id_invoice']);
    $H_Totalbayar = isset($rows) ? $rows['Totalbayar'] : 0;

    $H_t_omset     = sumOrder($row['id_invoice']);
    $H_totalDiskon = totalDiskon($row['id_invoice']);
    $H__diskon     = $row['potongan_harga'];
    $H_t_omset     = $H_t_omset - $H_totalDiskon;

    $H_piutang_arr = sumPiutang($row['id_invoice']); // bisa array
    $H_sub_tpajak  = 0;

    if ($row['pajak'] > 0) {
      $H_sub_tpajak  = ($H_t_omset * $row['pajak']) / 100;
      $H_piutang     = $H_t_omset + $H_sub_tpajak - $H_Totalbayar - $H__diskon;
    } else {
      $H_sub_tpajak  = 0;
      $H_piutang     = $H_t_omset - (is_array($H_piutang_arr) ? $H_piutang_arr[0]['piutang'] : (float)$H_piutang_arr) - $H__diskon;
    }

    if ($row['status'] == 'batal') {
      $H_Totalbayar = 0;
      $H_t_omset    = 0;
      $H_sub_tpajak = 0;
      $H_piutang    = 0;
      $H__diskon    = 0;
    }

    $H_total_order   += $H_t_omset;
    $H_total_pajak   += $H_sub_tpajak;
    $H_total_bayar   += $H_Totalbayar;
    $H_total_diskon  += $H__diskon;
    $H_total_piutang += $H_piutang;
  }
}
?>

<!-- =========================
     HEADER RINGKASAN (DESKTOP & MOBILE) — TANPA WARNA/GLASS & TANPA EXPORT
     ========================= -->
<div class="container-fluid kpi-header d-print-none">
  <div class="row gx-tight">
    <div class="col-6 col-md-4 col-lg-2-4">
      <div class="kpi-card kpi-blue">
        <div class="kpi-icon"><i class="fa fa-money"></i></div>
        <div class="kpi-copy"><div class="kpi-label">Total Transaksi</div><div class="kpi-value"><?= rp($H_total_order); ?></div></div>
      </div>
    </div>
    <div class="col-6 col-md-4 col-lg-2-4">
      <div class="kpi-card kpi-cyan">
        <div class="kpi-icon"><i class="fa fa-credit-card"></i></div>
        <div class="kpi-copy"><div class="kpi-label">Total Bayar</div><div class="kpi-value"><?= rp($H_total_bayar); ?></div></div>
      </div>
    </div>
    <div class="col-6 col-md-4 col-lg-2-4 mt-2 mt-md-0">
      <div class="kpi-card kpi-indigo">
        <div class="kpi-icon"><i class="fa fa-file-text-o"></i></div>
        <div class="kpi-copy"><div class="kpi-label">Total Piutang</div><div class="kpi-value"><?= rp($H_total_piutang); ?></div></div>
      </div>
    </div>
    <div class="col-6 col-md-4 col-lg-2-4 mt-2 mt-lg-0">
      <div class="kpi-card kpi-teal">
        <div class="kpi-icon"><i class="fa fa-percent"></i></div>
        <div class="kpi-copy"><div class="kpi-label">Total Pajak</div><div class="kpi-value"><?= rp($H_total_pajak); ?></div></div>
      </div>
    </div>
    <div class="col-12 col-md-4 col-lg-2-4 mt-2 mt-lg-0">
      <div class="kpi-card kpi-orange">
        <div class="kpi-icon"><i class="fa fa-tag"></i></div>
        <div class="kpi-copy"><div class="kpi-label">Total Diskon</div><div class="kpi-value"><?= rp($H_total_diskon); ?></div></div>
      </div>
    </div>
  </div>
</div>

<div class="table-responsive-sm table-shell">
  <table class="table table-modern">
    <!-- HEADER UTAMA — hanya 1x di paling atas -->
    <thead class="thead-section thead-dark">
      <tr>
        <th class="text-center col-no">No</th>
        <th class="text-center col-trx">No Trx</th>
        <th class="text-center col-tanggal">Tanggal Order</th>
        <th class="text-center col-kasir">Kasir</th>
        <th class="text-center col-pelanggan">Pelanggan</th>
        <th class="text-center col-rincian">Rincian Penjualan Barang</th>
        <th class="text-center col-money">Pajak</th>
        <th class="text-center col-money">Total Transaksi</th>
        <th class="text-center col-money">Total Bayar</th>
        <th class="text-center col-money">Diskon</th>
        <th class="text-center col-money">Piutang</th>
      </tr>
    </thead>

    <tbody>
      <?php 
        $omset_ppajak=0;
        $piutang=0;
        $t_omset=0;
        $totalDiskon=0;
        $total_pajak=0;     // <- total pajak footer
        $total_order=0;
        $total_diskon=0;
        $total_piutang=0;
        $total_bayar=0;
        $sub_tpajak=0;
        $Totalbayar=0;
        $diskon=0;

        if(!empty($result)) {
          $no=1;
          foreach($result AS $row){

            $rows = bayar($row['id_invoice']);
            $Totalbayar = isset($rows) ? $rows['Totalbayar'] : 0;

            $t_omset      = sumOrder($row['id_invoice']);
            $totalDiskon  = totalDiskon($row['id_invoice']);
            $_diskon      = $row['potongan_harga'];
            $t_omset      = $t_omset - $totalDiskon;
            $piutang      = sumPiutang($row['id_invoice']);

            // Pajak rupiah
            if($row['pajak'] > 0){
              $sub_tpajak = ($t_omset * $row['pajak']) / 100;
              $piutang    =  $t_omset + $sub_tpajak - $Totalbayar - $_diskon;
            }else{
              $sub_tpajak = 0;
              $piutang    = $t_omset - (is_array($piutang) ? $piutang[0]['piutang'] : (float)$piutang) - $_diskon;
            }

            if($row['status']=='batal'){ 
              $Totalbayar = 0; 
              $t_omset    = 0; 
              $sub_tpajak = 0;
              $_diskon    = 0;
              $piutang    = 0;
            }

            if($row["oto"]==0){ $status='Buka'; $view='edit';
            }elseif($row["oto"]==1){ $status='Edit Order'; $view='edit';
            }elseif($row["oto"]==2){ $status='Hapus Pembayaran'; $view='view';
            }elseif($row["oto"]==3){ $status='Edit Order Lunas'; $view='edit';
            }elseif($row["oto"]==4){ $status='Pending'; $view='view';
            }elseif($row["oto"]==5){ $status='Batal'; $view='view';
            }else{ $status='Kunci'; $view='view'; }

            $nama_full = ($row['tampil']==0) ? $row['nama'] : $row['perusahaan'];
            $id_invoice = encrypt_url($row['id_invoice']);
            $row_state  = ($row['status']=='batal') ? 'row-cancelled' : '';
      ?>

      <tr class="row-master <?=$row_state;?>">
        <td data-label="No" class="text-center"><?=$no++;?></td>

        <td data-label="No Trx" class="text-center nowrap col-trx-cell">
          <?php echo $row["id_transaksi"]; ?>
        </td>

        <td data-label="Tanggal" class="text-center nowrap col-tanggal-cell"><?=dtimes($row['tgl_trx'],false,false);?></td>

        <td class="text-center col-kasir-cell" data-label="Kasir"><?=$row['kasir'];?></td>

        <td class="text-left col-pelanggan-cell" data-label="Pelanggan">
          <a data-toggle="tooltip"
             data-original-title="Kirim Ke <?php echo $nama_full.' : '.phone_number($row['no_hp']); ?>"
             data-placement="left" class="text-success kirim_wa"
             data-id="<?php echo $id_invoice; ?>"
             data-nomor="<?php echo $row['no_hp']; ?>"
             data-trx="<?php echo $row['id_transaksi']; ?>"
             data-tgl="<?php echo $row['tgl_trx']; ?>"
             href="javascript:void(0)">
            <i class="fa fa-whatsapp"></i> &nbsp;<?php echo $nama_full; ?>
          </a>
        </td>

        <td data-label="Rincian" class="p-0 cell-rincian">
          <table class="table nested-table w-100 mb-0">
            <colgroup>
              <col style="width:50%">
              <col style="width:18%">
              <col style="width:10%">
              <col style="width:22%">
            </colgroup>
            <thead>
              <tr>
                <th>Nama Barang</th>
                <th>Harga</th>
                <th>Qty</th>
                <th>Total</th>
              </tr>
            </thead>
            <tbody>
              <?php 
                $detail = detail_order($row['id_invoice'],'semua');
                if(!empty($detail)){
                  foreach($detail AS $val){ 
                    $subtotal = $val->jumlah * $val->harga;
                    if($val->diskon > 0){
                      $diskon = ($subtotal * $val->diskon) /100;
                      $subtotal = $subtotal - $diskon;
                    }else{
                      $diskon = 0;
                    }
                    $bahan =  getDetailBahan($val->id_bahan)->title;
              ?>
              <tr class="row-detail">
                <td class="text-left col-nama" title="<?=$bahan;?>"><?=$bahan;?></td>
                <td class="text-center nowrap"><?=rp($val->harga);?></td>
                <td class="text-center nowrap"><?=$val->jumlah;?></td>
                <td class="text-center nowrap"><?=rp($subtotal);?></td>
              </tr>
              <?php } } else { ?>
              <tr><td colspan="4" class="text-center text-muted">Tidak ada item</td></tr>
              <?php } ?>
            </tbody>
          </table>
        </td>

        <td class="text-right nowrap cell-money" data-label="Pajak"><?=rp($sub_tpajak);?></td>
        <td class="text-right nowrap cell-money" data-label="Total Transaksi"><?=rp($t_omset);?></td>
        <td class="text-right nowrap cell-money" data-label="Total Bayar"><?=rp($Totalbayar);?></td>
        <td class="text-right nowrap cell-money" data-label="Diskon"><?=rp($_diskon);?></td>
        <td class="text-right nowrap cell-money" data-label="Piutang"><?=rp($piutang);?></td>
      </tr>

      <?php
        $total_order  += $t_omset;
        $total_pajak  += $sub_tpajak;
        $total_bayar  += $Totalbayar;
        $total_diskon += $_diskon;
        $total_piutang+= $piutang;
      }} else { ?>
      <tr><td colspan="11" class="text-center py-4">Data belum ada</td></tr>
      <?php } ?>
    </tbody>

    <tfoot>
      <tr class="row-total">
        <th class="text-left" colspan="6">
          <div class="d-flex gap-2 align-items-center">
            <span class="text-muted small d-none d-md-inline-block">Total keseluruhan</span>
          </div>
        </th>
        <th class="text-center"><?=rp($total_pajak);?></th>
        <th class="text-center"><?=rp($total_order);?></th>
        <th class="text-center"><?=rp($total_bayar);?></th>
        <th class="text-center"><?=rp($total_diskon);?></th>
        <th class="text-center"><?=rp($total_piutang);?></th>
      </tr>
    </tfoot>
  </table>

  <nav aria-label="Page navigation" class="p-2">
    <?php echo $this->ajax_pagination->create_links(); ?>
  </nav>
</div>

<div class="omset-result-count">Menampilkan: <?= !empty($result) ? count($result) : 0; ?></div>

<script>
  // HAPUS: mirror tombol export di header (sudah tidak ada tombol di ringkasan)

  $('.cek_transaksi').click(function(e){
    e.preventDefault();
    var id  = $(this).data("id");
    var mod = $(this).data('modedit');

    $.ajax({
      type: 'POST',
      url: base_url + "main/cek_akses",
      data: {id:id,mod:mod},
      dataType: "json",
      beforeSend: function () {
        $.LoadingOverlay("show", { background: "rgba(165, 190, 100, 0.7)", fade:500, zIndex:100 });
      },
      success: handleCart,
      error: function (xhr, ajaxOptions, thrownError) {
        sweet('Peringatan!!!',thrownError,'warning','warning');
      }
    });
  });

  $(".kirim_wa").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) { sweet('Server!!!', xhr.responseText, 'error', 'danger'); $('body').loading('stop'); }
    });
  });

  function getLinkWhastapp(number, message) {
    return 'https://wa.me/' + number + '?text=' + message;
  }
</script>

<style>
  /* ========= Util ========= */
  .nowrap{white-space:nowrap}
  .col-no{width:44px; min-width:44px}
  .col-trx{width:92px; min-width:92px}
  .col-tanggal{width:120px; min-width:120px}
  .col-kasir{width:90px; min-width:90px}
  .col-pelanggan{width:130px; min-width:130px}
  .col-rincian{width:34%; min-width:360px}
  .col-money{width:86px; min-width:86px}

  /* ====== HEADER KPI ====== */
  .kpi-header{
    padding:0;
    margin-bottom:16px;
    background:transparent;
  }
  .gx-tight{ margin-left:-8px; margin-right:-8px; }
  .gx-tight>[class^="col-"]{ padding-left:8px; padding-right:8px; }

  /* kolom 2.4 untuk 5 kolom sebaris di >=1200px */
  @media (min-width: 1200px){
    .col-lg-2-4{ flex:0 0 20%; max-width:20%; }
  }

  .kpi-card{
    min-height:76px;
    display:flex;
    align-items:center;
    gap:13px;
    padding:12px 14px;
    border:1px solid #e4e9f1;
    border-radius:10px;
    background:#fff;
    color:#344054;
    box-shadow:0 5px 15px rgba(15,23,42,.07);
  }
  .kpi-icon{
    width:42px;
    height:42px;
    flex:0 0 42px;
    display:flex;
    align-items:center;
    justify-content:center;
    border-radius:8px;
    color:#fff;
    font-size:18px;
    box-shadow:0 5px 11px rgba(15,23,42,.12);
  }
  .kpi-blue .kpi-icon{ background:#5b4df1; }
  .kpi-cyan .kpi-icon{ background:#2196e8; }
  .kpi-indigo .kpi-icon{ background:#8b4be8; }
  .kpi-teal .kpi-icon{ background:#18c5c0; }
  .kpi-orange .kpi-icon{ background:#ff8738; }
  .kpi-copy{ min-width:0; }

  .kpi-label{
    color:#667085;
    font-size:11px;
    font-weight: 600;
    letter-spacing:0;
    margin-bottom:4px;
    white-space:nowrap;
  }
  .kpi-value{
    color:#1d2939;
    font-size:17px;
    font-weight: 800;
    font-variant-numeric: tabular-nums;
    line-height: 1.1;
    white-space:nowrap;
  }

  /* ====== WRAPPER ====== */
  .table-shell{
    padding:12px;
    border:1px solid #e4e9f1;
    border-radius:11px;
    background:#fff;
    box-shadow:0 6px 18px rgba(15,23,42,.07);
    overflow-x:auto;
    overflow-y:hidden;
  }

  /* ====== TABEL UTAMA ====== */
  .table-modern{
    width:100%;
    min-width:1240px;
    margin-bottom:0;
    border:1px solid #e4e9f1;
    border-collapse:collapse;
    background:#fff;
    color:#475467;
    font-size:12px;
  }
  .table-modern th, .table-modern td{
    border:1px solid #e7ebf2;
    padding:.5rem .55rem;
    vertical-align:middle;
    font-variant-numeric: tabular-nums;
    line-height:1.3;
  }

  .thead-section th{
    font-weight:800;
    font-size:11px;
    background:#f3f6fb;
    color:#344054;
    text-align:center;
    vertical-align:middle !important;
  }
  .thead-dark.sticky-top th{ position:sticky; top:0; z-index:3; }

  
  /* HOVER + STATE */
  .table-modern tbody tr:hover{ background:#f8fbff; }
  .table-modern tbody tr:nth-child(even){ background:#fcfdff; }
  .row-cancelled td{ background:#ffe5e5 !important; color:#9b1c1c; }
  .trx-chip{
    padding:4px 8px;
    border:1px solid #cfe0f8;
    border-radius:4px;
    background:#eaf3ff;
    color:#1769e8;
    box-shadow:none;
    font-size:11px;
    font-weight:800;
  }
  /* ====== NESTED TABLE ====== */
  .nested-table{
    table-layout:auto;
    min-width:100%;
    border-collapse:collapse;
    border:0;
    background:#fff;
  }
  .nested-table th, .nested-table td{
    border:1px solid #e7ebf2;
    padding:.36rem .45rem;
    text-align:center;
    vertical-align:middle;
  }
  .nested-table thead th{
    background:#f8fafc;
    color:#475467;
    font-weight:700;
    font-size:10.5px;
    white-space:nowrap;
  }
  .nested-table td{ white-space:nowrap; }
  .nested-table .col-nama{
    white-space:normal !important;
    word-break:break-word;
    overflow-wrap:anywhere;
    min-width:180px;
    padding-right:.8rem;
  }
  .nested-table th:nth-child(2),
  .nested-table td:nth-child(2){ min-width:70px; }
  .nested-table th:nth-child(3),
  .nested-table td:nth-child(3){ min-width:60px; }
  .nested-table th:nth-child(4),
  .nested-table td:nth-child(4){ min-width:82px; }

  .cell-rincian{ background:#fff; }
  .cell-money{
    text-align:right !important;
    padding-right:.85rem !important;
  }

  /* ====== FOOTER TOTAL ====== */
  tfoot .row-total th{
    background:#f8fafc;
    color:#344054;
    font-weight:800;
    border-top:1px solid #dfe5ee;
  }
  .omset-result-count{
    padding:12px 2px 2px;
    color:#667085;
    font-size:12px;
    font-weight:600;
  }
  tfoot .row-total th:not(:first-child){
    text-align:right;
    padding-right:.85rem;
  }

  /* ====== RESPONSIVE ====== */
  @media (max-width: 1399.98px){
    .table-modern{ min-width:1220px; }
    .col-rincian{min-width:340px}
  }
  @media (max-width: 1199.98px){ .col-rincian{min-width:320px} }
  @media (max-width: 991.98px){
    .table-modern th, .table-modern td{ font-size:11px; }
    .nested-table th, .nested-table td{ font-size:10.5px; }
    .table-modern{ min-width:1180px; }
    .col-rincian{min-width:300px}
  }
  @media (max-width: 767.98px){
    .table-modern{ min-width:1000px; }
    .kpi-header{ padding: 10px 10px 8px; }
    .kpi-card{ padding:.65rem .75rem; }
    .kpi-value{ font-size: 1rem; }
  }

  /* Samakan ukuran font seluruh isi tabel penjualan */
  .table-shell .table-modern > thead > tr > th,
  .table-shell .table-modern > tbody > tr > td,
  .table-shell .table-modern > tfoot > tr > th,
  .table-shell .nested-table th,
  .table-shell .nested-table td,
  .table-shell .trx-chip,
  .table-shell .col-pelanggan-cell a{
    font-size:12px!important;
    line-height:1.35;
  }

  @media (max-width:767.98px){
    .table-shell .table-modern > thead > tr > th,
    .table-shell .table-modern > tbody > tr > td,
    .table-shell .table-modern > tfoot > tr > th,
    .table-shell .nested-table th,
    .table-shell .nested-table td,
    .table-shell .trx-chip,
    .table-shell .col-pelanggan-cell a{
      font-size:11px!important;
    }
  }

  /* Cetak */
  @media print{
    .d-print-none{ display:none !important; }
    .table-modern{ border-color:#999; }
  }
</style>
