<div class="pg-pembelian-list">
  <?php
    $total_all = 0;
    $displayed = 0;

    if (!empty($result)) {
      $no = $this->uri->segment(3) + 1;
      foreach ($result as $aRow) {
        $display_no = $no++;
        $displayed++;

        $Cetak = '<a href="'.base_url().'pembelian/cetak_pembelian/'.encrypt_url($aRow['id_pembelian']).'" target="_blank" class="pg-btn pg-btn-print"><i class="fa fa-print"></i> Cetak</a>';
        $edit  = ($aRow['pos'] == 'N') ? 'edit' : 'view';
        $hapus = '<button class="pg-btn pg-btn-delete hapus_pembelian" data-id="'.encrypt_url($aRow['id_pembelian']).'" data-idtrans="'.encrypt_url($aRow['no_transaksi']).'"><i class="fa fa-trash"></i> Hapus</button>';

        $lampiran_nota = '';
        if (isset($aRow['bukti_nota']) && !empty($aRow['bukti_nota'])) {
          $lampiran_nota = $aRow['bukti_nota'];
        } elseif (isset($aRow['bukti']) && !empty($aRow['bukti'])) {
          $lampiran_nota = $aRow['bukti'];
        } elseif (isset($aRow['lampiran']) && !empty($aRow['lampiran'])) {
          $lampiran_nota = $aRow['lampiran'];
        }

        if (!empty($lampiran_nota)) {
          $url_nota = base_url('uploads/bukti_pembelian/'.$lampiran_nota);
          $btnNota = '<button type="button" class="pg-btn pg-btn-note lihat_nota_pembelian" data-url="'.$url_nota.'" title="Lihat Bukti Nota"><i class="fa fa-file-text-o"></i> Nota</button>';
        } else {
          $btnNota = '<button type="button" class="pg-btn pg-btn-note" disabled title="Tidak ada lampiran"><i class="fa fa-file-text-o"></i> Nota</button>';
        }

        $sum_bayar_pembelian = sum_bayar_pembelian($aRow['id_pembelian']);
        if ($sum_bayar_pembelian > 0 && $sum_bayar_pembelian == $aRow['total_bayar']) {
          $lunas = '<span class="pg-status-badge">LUNAS</span>';
        } else {
          $lunas = '<button class="pg-btn pg-btn-pay bayar_hutang" data-info="bayarh" data-total="'.$aRow['total_bayar'].'" data-trx="'.$aRow['no_transaksi'].'" data-id="'.encrypt_url($aRow['id_pembelian']).'">Bayar</button>';
        }

        $total_all += floatval($aRow['total_bayar']);
        $stockSummary = isset($stok_sync_summaries[(int)$aRow['id_pembelian']]) ? $stok_sync_summaries[(int)$aRow['id_pembelian']] : null;
        $stockAction = '';
        if ($stockSummary) {
          if ((int)$stockSummary['pending'] > 0) {
            $stockAction = '<span class="pg-btn" style="background:#fff7ed;color:#c2410c;border:1px solid #fed7aa;cursor:default"><i class="fa fa-clock-o"></i> Menunggu ACC Stock</span>';
            if (!empty($boleh_acc_stok)) {
              $stockAction .= '<button type="button" class="pg-btn acc-stok-pembelian" style="background:#16a34a;color:#fff;border:1px solid #16a34a" data-id="'.encrypt_url($aRow['id_pembelian']).'"><i class="fa fa-check"></i> ACC Stok</button>';
            }
          } elseif ((int)$stockSummary['approved'] > 0) {
            $stockAction = '<span class="pg-btn" style="background:#ecfdf5;color:#15803d;border:1px solid #bbf7d0;cursor:default"><i class="fa fa-check-circle"></i> Stok Disetujui</span>';
          }
        } elseif (!empty($sinkron_stok_aktif)) {
          $stockAction = '<span class="pg-btn" style="background:#f8fafc;color:#64748b;border:1px solid #e2e8f0;cursor:default"><i class="fa fa-minus-circle"></i> Tidak terkait stok</span>';
        }
  ?>

    <div class="pg-invoice-card">
      <div class="pg-invoice-summary">
        <div class="pg-index-col">
          <span><?= $display_no; ?></span>
        </div>

        <div class="pg-trans-col">
          <a href="#" data-info="<?= $edit; ?>" class="pg-trans-link tambah_pembelian"
             data-id="<?= encrypt_url($aRow['id_pembelian']); ?>"
             data-idtrans="<?= encrypt_url($aRow['no_transaksi']); ?>">
            <?= $aRow['no_transaksi']; ?>
          </a>
        </div>

        <div class="pg-info-col">
          <div class="pg-info-label">Tanggal</div>
          <div class="pg-info-value"><?= dtime($aRow['tgl_pembelian']); ?></div>
        </div>

        <div class="pg-info-col">
          <div class="pg-info-label">Kode Akun</div>
          <div class="pg-info-value"><?= getAkun($aRow["id_akun"]); ?></div>
        </div>

        <div class="pg-info-col">
          <div class="pg-info-label">Keterangan</div>
          <div class="pg-info-value"><?= ($aRow["keterangan"]); ?></div>
        </div>

        <div class="pg-info-col pg-money">
          <div class="pg-info-label">Total</div>
          <div class="pg-info-value"><?= rp($aRow["total_bayar"]); ?></div>
        </div>

        <div class="pg-info-col text-center">
          <div class="pg-info-label">Status</div>
          <div class="pg-info-value"><?= $lunas; ?></div>
        </div>

        <div class="pg-info-col">
          <div class="pg-info-label">Aksi</div>
          <div class="pg-actions">
            <?= $btnNota; ?>
            <?= $stockAction; ?>
            <?= $Cetak; ?>
            <?= $hapus; ?>
          </div>
        </div>
      </div>

      <div class="pg-detail-wrap">
        <div class="table-responsive m-0">
          <table class="pg-detail-table">
            <thead>
              <tr>
                <th class="text-center" style="width:60px;">No</th>
                <th style="min-width:240px;">Item</th>
                <th style="min-width:180px;">Supplier</th>
                <th style="min-width:240px;">Keterangan Uraian</th>
                <th class="text-center" style="width:95px;">Jumlah</th>
                <th class="text-right" style="width:140px;">Harga</th>
                <th class="text-right" style="width:150px;">Subtotal</th>
              </tr>
            </thead>
            <tbody>
              <?php
                if (!empty($search)) {
                  $like = $this->db->escape_like_str($search);
                  $sql  = $this->db->query(
                    "SELECT * FROM pembelian_detail
                     WHERE id_pembelian = ? AND keterangan LIKE '%{$like}%' ESCAPE '!'",
                    [$aRow['id_pembelian']]
                  )->result_array();
                } else {
                  $sql  = $this->db->query(
                    "SELECT * FROM pembelian_detail WHERE id_pembelian = ?",
                    [$aRow['id_pembelian']]
                  )->result_array();
                }

                $total_detail = 0;
                $b=1;

                foreach ($sql as $rr) {
                  $tothar  = floatval($rr['harga']) * floatval($rr['jumlah']);
                  $total_detail += $tothar;
                  $_title = getItem($rr['id_bahan']);
              ?>
                <tr>
                  <td class="text-center"><?= $b++; ?></td>
                  <td class="nowrap"><?= $_title; ?></td>
                  <td class="nowrap"><?= getSupplier($rr['id_supplier']); ?></td>
                  <td><?= $rr['keterangan']; ?></td>
                  <td class="text-center"><?= $rr['jumlah']; ?></td>
                  <td class="text-right"><?= rp($rr['harga']); ?></td>
                  <td class="text-right"><?= rp($tothar); ?></td>
                </tr>
              <?php } ?>
            </tbody>
            <tfoot>
              <tr>
                <td colspan="6" class="text-left">Total Rincian</td>
                <td class="text-right"><?= rp($total_detail); ?></td>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>
    </div>

  <?php
      }
    } else {
  ?>
    <div class="pg-empty">Belum ada pembelian</div>
  <?php } ?>

  <input type="hidden" id="subtotal" value="<?= $total_all; ?>">

  <div class="pg-grand-total">
    <span>TOTAL PEMBELIAN</span>
    <strong><?= rp($total_all); ?></strong>
  </div>

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

<script>
  $(document).on('click', '.hapus_pembelian', function(e) {
    var no = $(this).attr("data-id");
    var idtrans = $(this).attr("data-idtrans");
    showConfirm(no, idtrans);
  });

  $(document).on('click', '.rekap', function(e) {
    e.preventDefault();
    var id = $(this).attr('data-id');
    var tgl = $("#dari").val();
    var user = $('#user').val();
    var subtotal = $('#subtotal').val();

    if (subtotal == 0 || subtotal === undefined) {
      sweet('Peringatan!!!','Maaf Data masih kosong','warning','warning');
      return;
    }

    $.ajax({
      url: base_url + 'pembukuan/save_rekap_pengeluaran',
      method: 'POST',
      dataType: 'json',
      data: { tgl: tgl, id: id, user: user, subtotal: subtotal },
      success: function(data) {
        if (data.ok == 'ok') {
          sweet('Rekap data!!!','Data berhasil direkap','success','success');
          FilterPengeluaran();
        } else {
          sweet('Rekap data!!!','Data telah direkap','warning','warning');
        }
      }
    });
  });
</script>
