<div class="keranjang" id="tambah-pembelian">
	<form autocomplete="off" class="form-add" id="form-add-beli" enctype="multipart/form-data">
		<div class="row">
			<div class="col-sm">
				<div class="form-group">
					<label for="formGroupExampleInput">No. Transaksi</label>
					<input type="text" class="form-control form-control-sm flat" name="no_trans" id="no_trans" value="<?=$no_trans;?>" readonly>
				</div>
			</div>
			<div class="col-sm">
				<div class="form-group">
					<label for="jenis_bayar">Jenis Bayar</label>
					<select name="jenis_bayar" id="jenis_bayar"  class="custom-select form-control-sm flat" required>
						<option value="1">Kas</option>
						<option value="2">Hutang Usaha</option>
					</select>
				</div>
			</div>
			<div class="col-sm">
				<div class="form-group">
					<label for="dari_kas">Keluar dari akun</label>
					<select name="dari_kas" id="dari_kas"  class="custom-select form-control-sm flat"  data-valueKey="id" data-displayKey="name" required>
					</select>
				</div>
			</div>
			<div class="col-sm">
				<div class="form-group text-right">
					<label for="saldo_kas">Saldo Kas</label>
					<input type="text" class="form-control form-control-sm flat text-right" name="saldo_kas" id="saldo_kas" readonly>
				</div>
			</div>
		</div>
		<div class="row">
			<div class="col-sm">			 
				<label for="tanggal_beli">Tanggal</label>
				<div class="input-group input-group-sm flat">
					<div class="input-group-prepend">
						<button class="btn btn-outline-secondary" type="button"><i class="fa fa-calendar"></i></button>
					</div>
					<input type="text" class="form-control flat" name="tanggal_beli" id="tanggal_beli" value="<?=$tanggal;?>" required>
				</div>
			</div>
			<div class="col-sm">
				<div class="form-group">
					<label for="keterangan_kas">Keterangan</label>
					<input type="text" class="form-control form-control-sm flat" name="keterangan_kas" id="keterangan_kas" required>
				</div>
			</div>
			<div class="col-sm">
				<div class="form-group text-right">
					<label for="jumlah_kas">Jumlah Kas</label>
					<input type="text" class="form-control form-control-sm flat text-right" name="jumlah_kas"  id="jumlah_kas" required readonly>
				</div>
			</div>
			<div class="col-sm">
				<div class="form-group">
					<label for="bukti_nota">Bukti Nota (opsional)</label>
					<div class="pembelian-nota-upload" id="pembelian-nota-upload">
						<input type="file" name="bukti_nota" id="bukti_nota" accept=".jpg,.jpeg,.png,.webp,.pdf">
						<label class="pembelian-nota-dropzone" for="bukti_nota">
							<span class="pembelian-nota-upload-icon"><i class="fa fa-cloud-upload"></i></span>
							<span class="pembelian-nota-upload-copy">
								<strong>Klik atau drop file</strong>
								<small>JPG, PNG, WEBP, PDF &bull; Maks. 6MB</small>
							</span>
						</label>
						<div class="pembelian-nota-selected" aria-live="polite">
							<button type="button" class="pembelian-nota-preview-btn" title="Lihat bukti nota">
								<span class="pembelian-nota-thumb-wrap">
									<img class="pembelian-nota-thumb" alt="Preview bukti nota">
									<i class="fa fa-file-pdf-o pembelian-nota-pdf-icon"></i>
								</span>
								<span class="pembelian-nota-file-info">
									<strong class="pembelian-nota-file-name"></strong>
									<small>Klik untuk melihat</small>
								</span>
							</button>
							<button type="button" class="pembelian-nota-remove" title="Hapus file" aria-label="Hapus bukti nota"><i class="fa fa-times"></i></button>
						</div>
					</div>
				</div>
			</div>

		</div>
		<div class='row'>
			<div class="col-md-12">
				<div class="font-weight-bold mb-2">Daftar Item Beli</div>
				<table class="table table-striped table-sm" id="table-beli">
					<thead>
						<tr>
							<td width="10" class="p-0 align-middle text-center"><button class="btn btn-primary flat add-more" type="button" id="add-more" readonly><i class="fa fa-plus"></i></button></td>
							<td class="w-20 pl-2">Item Beli</td>
							<td class="w-10 text-left">Supplier</td>
							<td>Keterangan Rincian</td>
							<td class="w-10 text-right">Jumlah</td>
							<td class="w-20 text-right">Harga</td>
							<td class="w-20 text-right">Total Pembelian</td>
						</tr>
					</thead>
					<tbody id="insert-form-kas">
						<tr id='rowCount' class="rowCount" >
							<td align="center">
								<button type="button" data-no=''
								class='btn btn-light bg-white btn-sm text-danger shadow-none flat' data-id="0" disabled><i class="fa fa-times"></i></button>
							</td>
							
							<td>
								<select type="text" class="form-control bootstrap-select input-sm flat" id="idAkun_0" name="idAkun[]" title="Item Beli" data-container="body" data-live-search="true" required>
									<option value="" selected hidden>Item Beli</option>
									<option value="__add_item__" data-content="<span class='add-item-cta'>+ Tambah Item</span>">+ Tambah Item</option>
									<?php foreach ($item->result_array() as $ak) : ?>
									<option value="<?= $ak['id']; ?>"><?= $ak['title']; ?></option>
									<?php endforeach; ?>
								</select>
							</td>
							<td>
								<select type="text" class="form-control bootstrap-select input-sm flat" id="supplier_0" name="supplier[]" title="Supplier" data-container="body" data-live-search="true" required>
									<option value="" selected hidden>Supplier</option>
									<option value="__add_supplier__" data-content="<span class='add-supplier-cta'>+ Tambah Supplier</span>">+ Tambah Supplier</option>
									<?php foreach ($supplier->result_array() as $ak) : ?>
									<option value="<?= $ak['id_supplier']; ?>"><?= $ak['nama_perusahaan']; ?></option>
									<?php endforeach; ?>
								</select>
							</td>
							
							<td>
								<div class="form-group p-0 m-0">
									<input type="text" id="keterangan_0" name="keterangan[]" class="form-control input-sm flat" required />
								</div>
							</td>
							
							<td>
								<div class="form-group p-0 m-0">
									<input type="text" id="jumlah_0" name="jumlah[]" class="form-control input-sm flat text-right" onkeyup="Math_Kas()" required />
								</div>
							</td>
							
							<td>
								<div class="form-group p-0 m-0">
									<input type="text" id="harga_0" name="harga[]" class="form-control input-sm flat text-right jumlah" onkeyup="Math_Kas()" required />
								</div>
							</td>
							
							<td>
								<div class="form-group p-0 m-0">
									<input type="text" id="total_0" name="total[]" class="form-control input-sm flat text-right jumlah" required readonly />
								</div>
							</td>
							
						</tr>
						
					</tbody>
				</table>
			</div>
		</div>
	</form>
</div>

<div class="pembelian-nota-viewer" id="pembelian-nota-viewer" aria-hidden="true">
	<div class="pembelian-nota-viewer-toolbar">
		<div>
			<strong>Preview Bukti Nota</strong>
			<span class="pembelian-nota-viewer-name"></span>
		</div>
		<button type="button" class="pembelian-nota-viewer-close" aria-label="Tutup preview"><i class="fa fa-times"></i></button>
	</div>
	<div class="pembelian-nota-viewer-content">
		<img class="pembelian-nota-viewer-image" alt="Bukti nota pembelian">
		<iframe class="pembelian-nota-viewer-pdf" title="Bukti nota PDF"></iframe>
	</div>
</div>

<div class="modal fade" id="ModalItemPembelianInline" tabindex="-1" role="dialog" aria-hidden="true">
	<div class="modal-dialog modal-md modal-dialog-centered modal-dialog-scrollable" id="save-item-inline" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title">Item pembelian</h5>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<div class="modal-body">
				<input type="hidden" id="item_inline_id" value="0">
				<input type="hidden" id="item_inline_type" value="add">
				<div class="form-group">
					<label for="item_inline_akun_id">Nama Akun</label>
					<select id="item_inline_akun_id" class="form-control custom-select">
						<option value="">Pilih Akun Jika Ada</option>
					</select>
				</div>
				<div class="form-group">
					<label for="item_inline_judul">Nama Item</label>
					<input type="text" id="item_inline_judul" class="form-control" required>
				</div>
				<div class="form-group">
					<label for="item_inline_kelompok">Kelompok akun</label>
					<select id="item_inline_kelompok" class="form-control custom-select" required>
						<option value="8">Persediaan</option>
						<option value="2">Peralatan</option>
					</select>
				</div>
				<div class="form-group">
					<label for="item_inline_aktif">Aktif</label>
					<select id="item_inline_aktif" class="form-control custom-select" required>
						<option value="Y" selected>Ya</option>
						<option value="N">Tidak</option>
					</select>
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-info save_item_inline_pembelian">Simpan</button>
				<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
			</div>
		</div>
	</div>
</div>

<div class="modal fade" id="ModalSupplierPembelianInline" tabindex="-1" role="dialog" aria-hidden="true">
	<div class="modal-dialog modal-md modal-dialog-centered modal-dialog-scrollable" id="save-supplier-inline" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title">Supplier</h5>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<div class="modal-body">
				<input type="hidden" id="supplier_inline_id" value="0">
				<input type="hidden" id="supplier_inline_type" value="add">
				<div class="form-group">
					<label for="supplier_inline_nama">Nama Perusahaan</label>
					<input type="text" id="supplier_inline_nama" class="form-control" required>
				</div>
				<div class="form-group">
					<label for="supplier_inline_atas_nama">Atas Nama</label>
					<input type="text" id="supplier_inline_atas_nama" class="form-control">
				</div>
				<div class="form-group">
					<label for="supplier_inline_jabatan">Jabatan</label>
					<input type="text" id="supplier_inline_jabatan" class="form-control">
				</div>
				<div class="form-group">
					<label for="supplier_inline_no_hp">No. HP</label>
					<input type="text" id="supplier_inline_no_hp" class="form-control">
				</div>
				<div class="form-group">
					<label for="supplier_inline_email">Email</label>
					<input type="text" id="supplier_inline_email" class="form-control">
				</div>
				<div class="form-group">
					<label for="supplier_inline_jenis_usaha">Jenis Usaha</label>
					<input type="text" id="supplier_inline_jenis_usaha" class="form-control">
				</div>
				<div class="form-group">
					<label for="supplier_inline_no_rekening">No. Rekening</label>
					<input type="text" id="supplier_inline_no_rekening" class="form-control">
				</div>
				<div class="form-group">
					<label for="supplier_inline_alamat">Alamat</label>
					<textarea id="supplier_inline_alamat" class="form-control" rows="2"></textarea>
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-info save_supplier_inline_pembelian">Simpan</button>
				<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
			</div>
		</div>
	</div>
</div>

<style>
	.pembelian-nota-upload {
		position: relative;
		min-height: 66px;
		border: 1px dashed #4c91df;
		border-radius: 8px;
		background: #fff;
		transition: border-color .2s ease, background .2s ease, box-shadow .2s ease;
	}
	.pembelian-nota-upload:hover,
	.pembelian-nota-upload.is-dragging {
		border-color: #1e6fc7;
		background: #f2f7fd;
		box-shadow: 0 0 0 3px rgba(40, 120, 208, .1);
	}
	.pembelian-nota-upload > input[type="file"] {
		position: absolute;
		width: 1px;
		height: 1px;
		opacity: 0;
		pointer-events: none;
	}
	.pembelian-nota-dropzone {
		display: flex !important;
		align-items: center;
		gap: 10px;
		min-height: 64px;
		margin: 0 !important;
		padding: 10px 12px;
		cursor: pointer;
	}
	.pembelian-nota-upload-icon {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		width: 36px;
		height: 36px;
		flex: 0 0 36px;
		border-radius: 9px;
		color: #2878d0;
		background: #eaf3fd;
		font-size: 19px;
	}
	.pembelian-nota-upload-copy {
		display: flex;
		min-width: 0;
		flex-direction: column;
		line-height: 1.25;
	}
	.pembelian-nota-upload-copy strong {
		color: #344256;
		font-size: 12px;
		font-weight: 600;
	}
	.pembelian-nota-upload-copy small {
		margin-top: 3px;
		color: #748197;
		font-size: 10px;
	}
	.pembelian-nota-selected {
		display: none;
		align-items: center;
		gap: 6px;
		min-height: 64px;
		padding: 7px;
	}
	.pembelian-nota-upload.has-file .pembelian-nota-dropzone {
		display: none !important;
	}
	.pembelian-nota-upload.has-file .pembelian-nota-selected {
		display: flex;
	}
	.pembelian-nota-preview-btn {
		display: flex;
		align-items: center;
		min-width: 0;
		flex: 1 1 auto;
		gap: 9px;
		padding: 0;
		border: 0;
		color: #29374a;
		text-align: left;
		background: transparent;
	}
	.pembelian-nota-thumb-wrap {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		width: 48px;
		height: 48px;
		flex: 0 0 48px;
		overflow: hidden;
		border-radius: 7px;
		background: #edf3fa;
	}
	.pembelian-nota-thumb {
		display: none;
		width: 100%;
		height: 100%;
		object-fit: cover;
	}
	.pembelian-nota-pdf-icon {
		display: none;
		color: #dc3545;
		font-size: 25px;
	}
	.pembelian-nota-upload.is-image .pembelian-nota-thumb,
	.pembelian-nota-upload.is-pdf .pembelian-nota-pdf-icon {
		display: block;
	}
	.pembelian-nota-file-info {
		display: flex;
		min-width: 0;
		flex-direction: column;
	}
	.pembelian-nota-file-info strong {
		overflow: hidden;
		font-size: 11px;
		font-weight: 600;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.pembelian-nota-file-info small {
		color: #2878d0;
		font-size: 10px;
	}
	.pembelian-nota-remove {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		width: 30px;
		height: 30px;
		flex: 0 0 30px;
		border: 0;
		border-radius: 7px;
		color: #cf4e4e;
		background: #fff0f0;
		transition: color .2s ease, background .2s ease;
	}
	.pembelian-nota-remove:hover {
		color: #fff;
		background: #dc5454;
	}
	.pembelian-nota-viewer {
		position: fixed;
		z-index: 2200;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		display: none;
		flex-direction: column;
		background: rgba(5, 12, 23, .94);
		backdrop-filter: blur(4px);
	}
	.pembelian-nota-viewer.is-open {
		display: flex;
	}
	.pembelian-nota-viewer-toolbar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		min-height: 68px;
		padding: 12px 22px;
		border-bottom: 1px solid rgba(255, 255, 255, .1);
		color: #fff;
	}
	.pembelian-nota-viewer-toolbar > div {
		display: flex;
		min-width: 0;
		flex-direction: column;
	}
	.pembelian-nota-viewer-toolbar strong {
		font-size: 15px;
	}
	.pembelian-nota-viewer-name {
		overflow: hidden;
		max-width: 70vw;
		color: rgba(255, 255, 255, .66);
		font-size: 12px;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.pembelian-nota-viewer-close {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		width: 42px;
		height: 42px;
		border: 1px solid rgba(255, 255, 255, .15);
		border-radius: 10px;
		color: #fff;
		background: rgba(255, 255, 255, .08);
		font-size: 20px;
		transition: background .2s ease, transform .2s ease;
	}
	.pembelian-nota-viewer-close:hover {
		background: rgba(255, 255, 255, .16);
		transform: rotate(90deg);
	}
	.pembelian-nota-viewer-content {
		display: flex;
		min-height: 0;
		flex: 1 1 auto;
		align-items: center;
		justify-content: center;
		padding: 24px;
	}
	.pembelian-nota-viewer-image {
		display: none;
		max-width: 94vw;
		max-height: calc(100vh - 116px);
		border-radius: 4px;
		box-shadow: 0 18px 50px rgba(0, 0, 0, .35);
		object-fit: contain;
	}
	.pembelian-nota-viewer-pdf {
		display: none;
		width: min(1100px, 94vw);
		height: calc(100vh - 116px);
		border: 0;
		border-radius: 6px;
		background: #fff;
	}
	.pembelian-nota-viewer.is-image .pembelian-nota-viewer-image,
	.pembelian-nota-viewer.is-pdf .pembelian-nota-viewer-pdf {
		display: block;
	}
	#ModalItemPembelianInline .modal-dialog {
		max-width: 680px;
	}
	#ModalSupplierPembelianInline .modal-dialog {
		max-width: 640px;
	}
	#ModalItemPembelianInline {
		z-index: 2000;
	}
	#ModalSupplierPembelianInline {
		z-index: 2000;
	}
	.modal-backdrop.modal-backdrop-item-inline {
		z-index: 1990;
	}
	.bootstrap-select .dropdown-menu li a .add-item-cta,
	.bootstrap-select .dropdown-menu li a .add-supplier-cta {
		display: block;
		padding: 4px 8px;
		background: #0d6efd;
		color: #fff;
		font-weight: 700;
		border-radius: 4px;
		text-align: center;
	}
</style>

<script>
	var dari_kas = ''
	// Menangani tambah data transakdi +
	var parent = $("#tambah-pembelian");
	var form = parent.find($("form"));
	var table = form.find($("table"));
	var index = 1;
	var akun = <?php echo json_encode( $item->result_array() ) ?>;
	var supplier = <?php echo json_encode( $supplier->result_array() ) ?>;
	var $modalItemInline = $('#ModalItemPembelianInline');
	var $modalSupplierInline = $('#ModalSupplierPembelianInline');
	var $activeSupplierSelect = null;
	var $notaUpload = $('#pembelian-nota-upload');
	var $notaInput = $('#bukti_nota');
	var $notaViewer = $('#pembelian-nota-viewer');
	var notaPreviewUrl = '';
	var notaPreviewType = '';

	// Viewer dipindahkan ke body agar tampil penuh di atas modal pembelian.
	$('body > #pembelian-nota-viewer').not($notaViewer).remove();
	if (!$notaViewer.parent().is('body')) {
		$notaViewer.appendTo('body');
	}

	function closePembelianNotaViewer() {
		$notaViewer.removeClass('is-open is-image is-pdf').attr('aria-hidden', 'true');
		$notaViewer.find('.pembelian-nota-viewer-image').attr('src', '');
		$notaViewer.find('.pembelian-nota-viewer-pdf').attr('src', '');
	}

	function resetPembelianNota() {
		closePembelianNotaViewer();
		if (notaPreviewUrl && window.URL && URL.revokeObjectURL) {
			URL.revokeObjectURL(notaPreviewUrl);
		}
		notaPreviewUrl = '';
		notaPreviewType = '';
		$notaInput.val('');
		$notaUpload.removeClass('has-file is-image is-pdf is-dragging');
		$notaUpload.find('.pembelian-nota-thumb').attr('src', '');
		$notaUpload.find('.pembelian-nota-file-name').text('');
	}

	function setPembelianNotaFile(file) {
		if (!file) {
			resetPembelianNota();
			return false;
		}

		var extension = String(file.name || '').split('.').pop().toLowerCase();
		var isImage = /^(jpe?g|png|webp)$/.test(extension) && (!file.type || /^image\//i.test(file.type));
		var isPdf = extension === 'pdf' && (!file.type || file.type === 'application/pdf');

		if (!isImage && !isPdf) {
			showNotif('top-center', 'Bukti Nota', 'Format file harus JPG, PNG, WEBP, atau PDF', 'warning');
			resetPembelianNota();
			return false;
		}
		if (file.size > (6 * 1024 * 1024)) {
			showNotif('top-center', 'Bukti Nota', 'Ukuran file maksimal 6MB', 'warning');
			resetPembelianNota();
			return false;
		}

		if (notaPreviewUrl && window.URL && URL.revokeObjectURL) {
			URL.revokeObjectURL(notaPreviewUrl);
		}
		notaPreviewUrl = URL.createObjectURL(file);
		notaPreviewType = isPdf ? 'pdf' : 'image';
		$notaUpload
			.removeClass('is-image is-pdf is-dragging')
			.addClass('has-file is-' + notaPreviewType);
		$notaUpload.find('.pembelian-nota-file-name').text(file.name);
		if (isImage) {
			$notaUpload.find('.pembelian-nota-thumb').attr('src', notaPreviewUrl);
		}
		return true;
	}

	$notaInput.off('change.pembelianNota').on('change.pembelianNota', function() {
		setPembelianNotaFile(this.files && this.files[0]);
	});

	$notaUpload.off('.pembelianNota');
	$notaUpload.on('dragenter.pembelianNota dragover.pembelianNota', function(e) {
		e.preventDefault();
		e.stopPropagation();
		$notaUpload.addClass('is-dragging');
	});
	$notaUpload.on('dragleave.pembelianNota drop.pembelianNota', function(e) {
		e.preventDefault();
		e.stopPropagation();
		$notaUpload.removeClass('is-dragging');
	});
	$notaUpload.on('drop.pembelianNota', function(e) {
		var files = e.originalEvent.dataTransfer && e.originalEvent.dataTransfer.files;
		if (!files || !files.length) {
			return;
		}
		if (setPembelianNotaFile(files[0])) {
			try {
				var transfer = new DataTransfer();
				transfer.items.add(files[0]);
				$notaInput[0].files = transfer.files;
			} catch (dropError) {
				showNotif('top-center', 'Bukti Nota', 'Silakan pilih file melalui tombol upload', 'warning');
				resetPembelianNota();
			}
		}
	});
	$notaUpload.on('click.pembelianNota', '.pembelian-nota-preview-btn', function() {
		if (!notaPreviewUrl) {
			return;
		}
		$notaViewer.find('.pembelian-nota-viewer-name').text($notaUpload.find('.pembelian-nota-file-name').text());
		$notaViewer.removeClass('is-image is-pdf').addClass('is-open is-' + notaPreviewType).attr('aria-hidden', 'false');
		if (notaPreviewType === 'image') {
			$notaViewer.find('.pembelian-nota-viewer-image').attr('src', notaPreviewUrl);
		} else {
			$notaViewer.find('.pembelian-nota-viewer-pdf').attr('src', notaPreviewUrl);
		}
	});
	$notaUpload.on('click.pembelianNota', '.pembelian-nota-remove', function() {
		resetPembelianNota();
	});
	$notaViewer.off('.pembelianNota').on('click.pembelianNota', '.pembelian-nota-viewer-close', closePembelianNotaViewer);
	$notaViewer.on('click.pembelianNota', function(e) {
		if (e.target === this) {
			closePembelianNotaViewer();
		}
	});
	$(document).off('keydown.pembelianNota').on('keydown.pembelianNota', function(e) {
		if (e.key === 'Escape' && $notaViewer.hasClass('is-open')) {
			e.preventDefault();
			closePembelianNotaViewer();
		}
	});
	$('#pembelian').off('hidden.bs.modal.pembelianNota').on('hidden.bs.modal.pembelianNota', function() {
		resetPembelianNota();
	});

	// Pastikan modal item inline berada di body agar tidak mewarisi style fullscreen parent.
	$('body > #ModalItemPembelianInline').not($modalItemInline).remove();
	if (!$modalItemInline.parent().is('body')) {
		$modalItemInline.appendTo('body');
	}
	$('body > #ModalSupplierPembelianInline').not($modalSupplierInline).remove();
	if (!$modalSupplierInline.parent().is('body')) {
		$modalSupplierInline.appendTo('body');
	}

	$modalItemInline.on('show.bs.modal', function() {
		setTimeout(function() {
			$('.modal-backdrop').last().addClass('modal-backdrop-item-inline');
		}, 0);
	});
	$modalSupplierInline.on('show.bs.modal', function() {
		setTimeout(function() {
			$('.modal-backdrop').last().addClass('modal-backdrop-item-inline');
		}, 0);
	});

	$modalItemInline.on('shown.bs.modal', function() {
		$('#item_inline_judul').focus();
	});
	$modalSupplierInline.on('shown.bs.modal', function() {
		$('#supplier_inline_nama').focus();
	});

	function loadAkunItemPembelianInline() {
		$.ajax({
			url: base_url + "produk/load_jenis",
			type: 'GET',
			dataType: 'json',
			beforeSend: function() {
				$("#item_inline_akun_id").prop("disabled", true).html("<option value=''>Loading...</option>");
			},
			success: function(response) {
				var $akun = $("#item_inline_akun_id");
				$akun.prop("disabled", false).empty();
				$akun.append("<option value=''>Pilih Akun Jika Ada / Boleh di kosongkan</option>");
				for (var i = 0; i < response.length; i++) {
					$akun.append("<option value='" + response[i].id + "'>" + response[i].name + "</option>");
				}
			},
			error: function(xhr, ajaxOptions, thrownError) {
				$("#item_inline_akun_id").prop("disabled", false).html("<option value=''>Pilih Akun Jika Ada</option>");
				sweet('Peringatan!!!', thrownError, 'warning', 'warning');
			}
		});
	}

	function resetItemPembelianInlineModal() {
		$("#item_inline_id").val("0");
		$("#item_inline_type").val("add");
		$("#item_inline_akun_id").val("");
		$("#item_inline_judul").val("").removeClass("is-invalid");
		$("#item_inline_kelompok").val("8");
		$("#item_inline_aktif").val("Y");
	}

	function appendNewItemToPembelianSelect(itemId, itemTitle) {
		if (!itemId || !itemTitle) {
			return;
		}

		var existsInCache = false;
		for (var i = 0; i < akun.length; i++) {
			if (String(akun[i].id) === String(itemId)) {
				existsInCache = true;
				break;
			}
		}

		if (!existsInCache) {
			akun.unshift({ id: itemId, title: itemTitle });
		}

		$('select[name="idAkun[]"]').each(function() {
			if ($(this).find('option[value="' + itemId + '"]').length === 0) {
				var $newOpt = $('<option>', { value: itemId, text: itemTitle });
				var $addOpt = $(this).find('option[value="__add_item__"]');
				if ($addOpt.length > 0) {
					$newOpt.insertAfter($addOpt.first());
				} else {
					$(this).prepend($newOpt);
				}
			}
		});

		$(".bootstrap-select").selectpicker('refresh');
	}

	function resetSupplierPembelianInlineModal() {
		$("#supplier_inline_id").val("0");
		$("#supplier_inline_type").val("add");
		$("#supplier_inline_nama").val("").removeClass("is-invalid");
		$("#supplier_inline_atas_nama").val("");
		$("#supplier_inline_jabatan").val("");
		$("#supplier_inline_no_hp").val("");
		$("#supplier_inline_email").val("");
		$("#supplier_inline_jenis_usaha").val("");
		$("#supplier_inline_no_rekening").val("");
		$("#supplier_inline_alamat").val("");
	}

	function appendNewSupplierToPembelianSelect(supplierId, supplierName) {
		if (!supplierId || !supplierName) {
			return;
		}

		var existsInCache = false;
		for (var i = 0; i < supplier.length; i++) {
			if (String(supplier[i].id_supplier) === String(supplierId)) {
				existsInCache = true;
				break;
			}
		}

		if (!existsInCache) {
			supplier.unshift({ id_supplier: supplierId, nama_perusahaan: supplierName });
		}

		$('select[name="supplier[]"]').each(function() {
			if ($(this).find('option[value="' + supplierId + '"]').length === 0) {
				var $newOpt = $('<option>', { value: supplierId, text: supplierName });
				var $addOpt = $(this).find('option[value="__add_supplier__"]');
				if ($addOpt.length > 0) {
					$newOpt.insertAfter($addOpt.first());
				} else {
					$(this).prepend($newOpt);
				}
			}
		});

		if ($activeSupplierSelect && $activeSupplierSelect.length) {
			$activeSupplierSelect.val(supplierId);
		}

		$(".bootstrap-select").selectpicker('refresh');
	}

	function openTambahItemModalFromSelect() {
		resetItemPembelianInlineModal();
		loadAkunItemPembelianInline();
		$('#ModalItemPembelianInline').modal({backdrop: 'static', keyboard: false});
	}

	function openTambahSupplierModalFromSelect($select) {
		$activeSupplierSelect = $select;
		resetSupplierPembelianInlineModal();
		$('#ModalSupplierPembelianInline').modal({backdrop: 'static', keyboard: false});
	}

	$(document).on('shown.bs.select', 'select[name="idAkun[]"]', function() {
		$(this).data('prev-value', $(this).val());
	});
	$(document).on('shown.bs.select', 'select[name="supplier[]"]', function() {
		$(this).data('prev-value', $(this).val());
	});

	$(document).on('change', 'select[name="idAkun[]"]', function() {
		var currentValue = $(this).val();
		if (currentValue === '__add_item__') {
			var prevValue = $(this).data('prev-value') || '';
			$(this).val(prevValue);
			$(this).selectpicker('refresh');
			openTambahItemModalFromSelect();
		}
	});

	$(document).on('change', 'select[name="supplier[]"]', function() {
		var currentValue = $(this).val();
		if (currentValue === '__add_supplier__') {
			var prevValue = $(this).data('prev-value') || '';
			$(this).val(prevValue);
			$(this).selectpicker('refresh');
			openTambahSupplierModalFromSelect($(this));
		}
	});

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

		var id = $("#item_inline_id").val();
		var type = $("#item_inline_type").val();
		var id_akun = $("#item_inline_akun_id").val();
		var judul = $.trim($("#item_inline_judul").val());
		var kelompok = $("#item_inline_kelompok").val();
		var aktif = $("#item_inline_aktif").val();

		if (judul === '') {
			$("#item_inline_judul").addClass('is-invalid').focus();
			return;
		}

		$.ajax({
			url: base_url + 'pembelian/save_item',
			data: {id: id, type: type, judul: judul, kelompok: kelompok, id_akun: id_akun, aktif: aktif},
			method: 'POST',
			dataType: 'json',
			beforeSend: function() {
				$('#save-item-inline').loading({zIndex: 1060});
			},
			success: function(data) {
				if (data.status === true) {
					appendNewItemToPembelianSelect(data.id, (data.title ? data.title : judul));
					showNotif('bottom-right', 'Simpan data', data.msg, 'success');
					$('#ModalItemPembelianInline').modal('hide');
				} else {
					sweet('Peringatan!!!', (data.msg ? data.msg : 'Gagal menyimpan item'), 'warning', 'warning');
				}
				$('#save-item-inline').loading('stop');
			},
			error: function(xhr, ajaxOptions, thrownError) {
				$('#save-item-inline').loading('stop');
				sweet('Peringatan!!!', thrownError, 'warning', 'warning');
			}
		});
	});

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

		var namaSupplier = $.trim($("#supplier_inline_nama").val());
		if (namaSupplier === '') {
			$("#supplier_inline_nama").addClass('is-invalid').focus();
			return;
		}

		$.ajax({
			url: base_url + 'supplier/simpan',
			data: {
				id: $("#supplier_inline_id").val(),
				type: $("#supplier_inline_type").val(),
				nama_perusahaan: namaSupplier,
				atas_nama: $.trim($("#supplier_inline_atas_nama").val()),
				jabatan: $.trim($("#supplier_inline_jabatan").val()),
				no_hp: $.trim($("#supplier_inline_no_hp").val()),
				email: $.trim($("#supplier_inline_email").val()),
				jenis_usaha: $.trim($("#supplier_inline_jenis_usaha").val()),
				no_rekening: $.trim($("#supplier_inline_no_rekening").val()),
				alamat: $.trim($("#supplier_inline_alamat").val())
			},
			method: 'POST',
			dataType: 'json',
			beforeSend: function() {
				$('#save-supplier-inline').loading({zIndex: 1060});
			},
			success: function(data) {
				if (data.status == 200) {
					appendNewSupplierToPembelianSelect(data.id, (data.nama_perusahaan ? data.nama_perusahaan : namaSupplier));
					showNotif('bottom-right', 'Simpan data', data.msg, 'success');
					$('#ModalSupplierPembelianInline').modal('hide');
				} else {
					sweet('Peringatan!!!', (data.msg ? data.msg : 'Gagal menyimpan supplier'), 'warning', 'warning');
				}
				$('#save-supplier-inline').loading('stop');
			},
			error: function(xhr, ajaxOptions, thrownError) {
				$('#save-supplier-inline').loading('stop');
				sweet('Peringatan!!!', thrownError, 'warning', 'warning');
			}
		});
	});

	$('#ModalItemPembelianInline').on('hidden.bs.modal', function() {
		if ($('#pembelian').hasClass('show')) {
			$('body').addClass('modal-open');
		}
	});
	$('#ModalSupplierPembelianInline').on('hidden.bs.modal', function() {
		if ($('#pembelian').hasClass('show')) {
			$('body').addClass('modal-open');
		}
	});

	$('#pembelian').on('hide.bs.modal', function() {
		$('#ModalItemPembelianInline').modal('hide');
		$('#ModalSupplierPembelianInline').modal('hide');
	});

	table.find($(".add-more")).click(function() {
		
		let optionAkun = '';
		let optionNamaAkun = '';
		let optionPerkiraan = '';
		$.each( akun, function( index, row ) {
			optionAkun += `
		<option value="${row.id}">${row.title}</option>
		`;
		});
		$.each( akun, function( index, row ) {
		optionNamaAkun += `
		<option value="${row.title}">${row.title}</option>
		`;
		});
		
		
		let option = '';
		
		$.each( supplier, function( index, row ) {
		option += `
		<option value="${row.id_supplier}">${row.nama_perusahaan}</option>
		`;
		});
		
		
		let el = `<tr id="data${index}">
			<td class="text-center">
				<button type="button"data-position="${index}"
				class='btn btn-light bg-white btn-sm text-danger shadow-none flat' id="hapus-tab-input"><i class="fa fa-times"></i></button>
			</td>
			<td>
				<select type="text" class="form-control bootstrap-select input-sm flat" id="idAkun_${index}" name="idAkun[]" title="Item Beli" data-container="body" data-live-search="true" required>
					<option value="" selected hidden>Item Beli</option>
					<option value="__add_item__" data-content="<span class='add-item-cta'>+ Tambah Item</span>">+ Tambah Item</option>
					${optionAkun}
				</select>
			</td>
			<td>
				<select type="text" class="form-control bootstrap-select input-sm flat" id="supplier_${index}" name="supplier[]" title="Supplier" data-container="body" data-live-search="true" required>
					<option value="" selected hidden>Supplier</option>
					<option value="__add_supplier__" data-content="<span class='add-supplier-cta'>+ Tambah Supplier</span>">+ Tambah Supplier</option>
					${option}
				</select>
			</td>
			
			<td>
				<input type="text" class="form-control input-sm flat" id="keterangan_${index}" name="keterangan[]"  autocomplete="off" required>
			</td>
			
			<td>
				<input type="text" class="form-control input-sm text-right flat" id="jumlah_${index}" name="jumlah[]" onkeyup="formatNumber(this);Math_Kas()" autocomplete="off" required>
			</td>
			
			<td>
				<input type="text" class="form-control input-sm text-right flat jumlah" id="harga_${index}" name="harga[]" onkeyup="Math_Kas()" autocomplete="off" required>
			</td>
			
			<td>
				<input type="text" class="form-control input-sm text-right flat jumlah" id="total_${index}" name="total[]" onkeyup="Math_Kas()" autocomplete="off" required>
			</td>
			
		</tr>`;
		table.find($("#insert-form-kas")).append(el);
		
		index++;
		$(".bootstrap-select").selectpicker();
		});
		
		// Menangani hapus row
		$(document).on("click", "#hapus-tab-input", function() {
        let id = $(this).attr("data-position");
		table.find($("tr#data"+id)).remove();
		Math_Kas();
		});
		
		// menangani otomatis nomor akun dan nama akun
		$(document).ready(function(){
		$(".bootstrap-select").selectpicker();
		
		$(document).on("keyup input", ".jumlah", function() {
		//Menangani Input otomatis Format Ribuan
		let rupiah = $(this).val();
		
		$(this).val(formatRupiah(rupiah, 'Rp. '));
		Math_Kas();
		
		/* Fungsi formatRupiah */
		function formatRupiah(angka, prefix){
		let number_string = angka.replace(/[^,\d]/g, '').toString(),
		split   		= number_string.split(','),
		sisa     		= split[0].length % 3,
		rupiah     		= split[0].substr(0, sisa),
		ribuan     		= split[0].substr(sisa).match(/\d{3}/gi);
		
		// tambahkan titik jika yang di input sudah menjadi angka ribuan
		if(ribuan){
		separator = sisa ? '.' : '';
		rupiah += separator + ribuan.join('.');
		}
		
		rupiah = split[1] != undefined ? rupiah + ',' + split[1] : rupiah;
		return prefix == undefined ? rupiah : (rupiah ? 'Rp. ' + rupiah : '');
		}
	    });
		});
	</script>
	<script>
		$("#dari_kas").filter(function() {
			$.ajax({
				url : base_url + "pembelian/akun_kas",
				type : "post",
				data : {
					id : dari_kas
				},
				dataType : "json",
				success : function(response) {
					var msize = response.length;
					$(".dari_kas").attr("disabled", false);
					$("#dari_kas").append("<option value=''>Pilih</option>");
					/** @type {number} */
					var i = 0;
					for (; i < msize; i++) {
						var teg = response[i]["id"];
						var last_supr = response[i]["name"];
						
						$("#dari_kas").append("<option value='" + teg + "'>" + last_supr + "</option>");
					}
				}
			});
		});
		
		$("#jenis_bayar" ).change(function() {
			var id = $("#jenis_bayar").val();
			if(id==1){
				$("#dari_kas").attr('required',true);
				$("#dari_kas").attr('disabled',false);
				}else{
				$("#dari_kas").attr('required',false);
				$("#dari_kas").attr('disabled',true);
				$("#dari_kas").val('').change();
			}
			
		});
		
		$("#dari_kas" ).change(function() {
			var id = $("#dari_kas").val();
			
			$("#saldo_kas").empty();
			$.ajax({
				url: base_url + "kas/load_kas",
				type: 'post',
				data: {id:id,type:'cari'},
				dataType: 'json',
				success: function (response) {
					// console.log(response)
					$('#saldo_kas').val(formatMoney(response.nilai,0,"Rp."));
				},
				error: function (xhr, ajaxOptions, thrownError) {
					sweet('Peringatan!!!',thrownError,'warning','warning');
				}
			});
			
		});
		
		
		$('#tanggal_beli').datepicker({        
			format: 'dd/mm/yyyy', 
			autoclose: true,     
			todayHighlight: true,   
			endDate: "today",
			todayBtn: 'linked',
		});    
		$('.simpan_pembelian').attr('disabled',false).show();
	</script>
