<?php
	$summary_payments = array();
	$summary_outstanding = array();
	if(!empty($result)){
		foreach($result as $summary_row){
			$summary_total = (float)$summary_row['total_bayar'];
			$summary_paid = (float)sum_bayar_pembelian($summary_row['id_pembelian']);
			$summary_paid = min($summary_paid, $summary_total);
			$summary_payments[$summary_row['id_pembelian']] = $summary_paid;
			$summary_outstanding[$summary_row['id_pembelian']] = max($summary_total - $summary_paid, 0);
		}
	}
?>

<div class="hutang-list-panel">
	<div class="hutang-list-heading">
		<div><h2>Rincian Hutang</h2><p>Daftar transaksi pembelian yang masih memiliki tagihan.</p></div>
	</div>
	<div class="hutang-results">
	<div class="hutang-table-scroll">
		<table class="table hutang-table" id="jsonuser">
			<thead>
				<tr>
					<th>No.</th>
					<th>No. Transaksi</th>
					<th>Tanggal</th>
					<th class="text-left">Kode Akun</th>
					<th class="text-left">Keterangan</th>
					<th class="text-center">Status</th>
					<th class="text-right">Aksi</th>
				</tr>
			</thead>
			<tbody>
				<?php 
					$total_all=isset($total_outstanding) ? (float)$total_outstanding : 0;
					$button='';
					if(!empty($result)){
						$no=$this->uri->segment(3)+1;
						foreach($result AS $aRow){ 
							$display_no = $no++;
							
							$button ='';
							$Cetak = '<a href="'.base_url().'pembelian/cetak_pembelian/'.encrypt_url($aRow['id_pembelian']).'" target="_blank" class="btn hutang-action-btn hutang-action-print"><i class="fa fa-print"></i> Cetak</a>';
							$edit = 'view';
							$btn = 'btn btn-success btn-sm';
							
							if($aRow['pos']=='N'){
								$edit = 'edit';
							}

							// ====== TOMBOL NOTA (BARU) ======
							// ambil dari beberapa kemungkinan nama kolom agar aman
							$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)) {
								// default folder: uploads/lampiran/
								$url_nota = base_url('uploads/bukti_pembelian/'.$lampiran_nota);
								$btnNota = '<a href="'.$url_nota.'" target="_blank" class="btn hutang-action-btn hutang-action-note" title="Lihat Bukti Nota"><i class="fa fa-file-text-o"></i> Nota</a>';
							} else {
								$btnNota = '<button type="button" class="btn hutang-action-btn hutang-action-note" disabled title="Tidak ada lampiran"><i class="fa fa-file-text-o"></i> Nota</button>';
							}
							// ====== /TOMBOL NOTA (BARU) ======

							$sum_bayar_pembelian = isset($summary_payments[$aRow['id_pembelian']]) ? $summary_payments[$aRow['id_pembelian']] : sum_bayar_pembelian($aRow['id_pembelian']);
							$sisa_hutang = isset($summary_outstanding[$aRow['id_pembelian']])
								? $summary_outstanding[$aRow['id_pembelian']]
								: max((float)$aRow['total_bayar'] - (float)$sum_bayar_pembelian, 0);
							if($sisa_hutang > 0){
								
								$lunas ='<button class="btn hutang-action-btn hutang-action-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>';
							?>
							
			<tr class="hutang-main-row">
								<td class="hutang-index-cell"><?=$display_no;?></td>
								<td class="text-left hutang-transaction-cell">
					<a href='#' data-info="<?=$edit;?>" class="tambah_pembelian hutang-trx-link" data-id="<?=encrypt_url($aRow['id_pembelian']);?>" data-idtrans="<?=encrypt_url($aRow['no_transaksi']);?>">
										<?=$aRow['no_transaksi'];?>
									</a>
								</td>
								<td class="hutang-date-cell" data-label="Tanggal"><?=dtime($aRow['tgl_pembelian']);?></td>
								<td class="text-left hutang-account-cell" data-label="Kode Akun"><?=getAkun($aRow["id_akun"]); ?></td>
								<td class="text-left hutang-description-cell" data-label="Keterangan"><?=($aRow["keterangan"]); ?></td>
								<td class="text-center hutang-status-cell" data-label="Status"><?=$lunas;?></td>
								<td class="text-right hutang-actions-cell" data-label="Aksi">
					<div class="hutang-action-group">
										<?=$btnNota;?>
										<?=$Cetak;?>
									</div>
								</td>
							</tr>
			<tr data-parent="#table-guest" class="hutang-detail-row">
								<td colspan="7" class="p-0">
					<table class="table hutang-detail-table">
										<thead>
											<tr>
												<td style="width:3%!important" class="text-center">No.</td>
												<td style="width:15%!important">Item</td>
												<td class="w-5">Supplier</td>
												<td class="w-20">Keterangan Uraian</td>
												<td class="w-5 text-right">Jumlah</td>
												<td class="w-5 text-right">Harga</td>
												<td class="w-5 text-right">Subtotal</td>
											</tr>
										</thead>
										<?php
											if(!empty($search)){
												// (biarkan pola lama agar tidak merusak flow)
												$sql= $this->db->query("SELECT 
												`supplier`.`nama_perusahaan`,
												`pembelian_detail`.`no`,
												`pembelian_detail`.`id_bahan`,
												`pembelian_detail`.`id_pembelian`,
												`pembelian_detail`.`id_biaya`,
												`pembelian_detail`.`id_supplier`,
												`pembelian_detail`.`no_invo`,
												`pembelian_detail`.`keterangan`,
												`pembelian_detail`.`jumlah`,
												`pembelian_detail`.`harga`,
												`pembelian_detail`.`satuan`,
												`pembelian_detail`.`id_pemesan`,
												`pembelian_detail`.`no_order`,
												`pembelian_detail`.`create_date`
												FROM
												`pembelian_detail`
												INNER JOIN `supplier` ON (`pembelian_detail`.`id_supplier` = `supplier`.`id_supplier`)
												WHERE
												`supplier`.`nama_perusahaan` LIKE '%$search%'")->result_array();
											}else{
												$sql= $this->db->query("SELECT * from pembelian_detail where id_pembelian=".$aRow['id_pembelian'])->result_array();
											}
											
											$total = 0;
											$b=1;
											foreach ($sql as $rr){
												
												$tothar = $rr['harga'] * $rr['jumlah'];
												$_title = getItem($rr['id_bahan']);
												$getSupplier = getSupplier($rr['id_supplier']);
											?>
											<tr>
												<td class="text-center"><?=$b++;?></td>
												<td><?=$_title;?></td>
												<td><?=$getSupplier;?></td>
												<td><?=$rr['keterangan'];?></td>
												<td class="text-right"><?=$rr['jumlah'];?></td>
												<td class="text-right"><?=rp($rr['harga']);?></td>
												<td class="text-right"><?=rp($tothar);?></td>
											</tr>
											
											<?php 
												$total = $total + $tothar;
											} ?>
											
								<tr class="hutang-purchase-total">
												<td colspan="6" class="text-left"><strong>Total Rincian</strong></td>
												<td class="text-right">
													<b><?=rp($total);?></b>
											<input type="hidden" class="form-control form-control-sm text-right" value="<?=$total;?>" id="subtotal" readonly>
										</td>
									</tr>
									<tr class="hutang-purchase-total">
										<td colspan="6" class="text-left"><strong>Total Bayar</strong></td>
										<td class="text-right"><b><?=rp($sum_bayar_pembelian);?></b></td>
									</tr>
									<tr class="hutang-purchase-total">
										<td colspan="6" class="text-left"><strong>Sub Total</strong></td>
										<td class="text-right"><b><?=rp($sisa_hutang);?></b></td>
									</tr>
									</table>
								</td>
			</tr>
						<?php } } ?>
						<?php }else{ ?>
						<tr class="hutang-empty-row">
							<td colspan="7" class="text-center">Belum ada pembelian</td>
						</tr>
				<?php } ?>
				
			</tbody>
			<tfoot>
				<tr>
					<th colspan="6" class="text-info">Total Hutang Pembelian</th>
					<th class="text-right text-info" data-role="hutang-total" data-total="<?=$total_all;?>"><?=rp($total_all);?></th>
				</tr>
			</tfoot>
			
		</table>
		<nav aria-label="Page navigation" class="mt-3">
			<?php echo $this->ajax_pagination->create_links(); ?>
		</nav>
		
	</div><!-- /.hutang-table-scroll -->
</div><!-- /.hutang-results -->
</div><!-- /.hutang-list-panel -->
<script>
	$(".hapus_pembelian").on('click', function(e) {
		var no = $(this).attr("data-id");
		var idtrans = $(this).attr("data-idtrans");
		showConfirm(no,idtrans)
	});
	$(".rekap").on('click', 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){
			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) {
				console.log(data);
				if(data.ok=='ok'){
					sweet('Rekap data!!!','Data berhasil direkap','success','success');
					FilterPengeluaran();
					}else{
					sweet('Rekap data!!!','Data telah direkap','warning','warning');
				}
			}
		})
	});
</script>
