<?php
if (!function_exists('harga_satuan_format')) {
	function harga_satuan_format($value) {
		$value = (string) $value;
		$parts = explode('.', $value, 2);
		$whole = preg_replace('/\D/', '', $parts[0]);
		$decimal = isset($parts[1]) ? rtrim(preg_replace('/\D/', '', $parts[1]), '0') : '';
		$formatted = number_format((int) ($whole === '' ? 0 : $whole), 0, ',', '.');
		return $decimal === '' ? $formatted : $formatted . ',' . $decimal;
	}
}
?>
<style>
	.satuan-price-toolbar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 16px;
		margin-bottom: 14px;
	}
	.satuan-price-toolbar__title {
		margin: 0 0 3px;
		color: #172033;
		font-size: 14px;
		font-weight: 700;
	}
	.satuan-price-toolbar__hint {
		margin: 0;
		color: #8290a7;
		font-size: 11px;
	}
	#add-satuan {
		flex: 0 0 auto;
		min-width: 106px;
		padding: 8px 14px;
		border: 1px solid #1769ed;
		border-radius: 8px;
		background: #1769ed;
		box-shadow: 0 4px 10px rgba(23, 105, 237, .18);
		color: #fff;
		font-size: 12px;
		font-weight: 700;
	}
	#add-satuan:hover {
		background: #0f5bd4;
		border-color: #0f5bd4;
		transform: translateY(-1px);
	}
	.satuan-table-shell {
		overflow: hidden;
		border: 1px solid #e4e9f1;
		border-radius: 10px;
		background: #fff;
	}
	.tbl-qa {
		width: 100%;
		margin: 0;
		background: #fff;
		font-size: 12px;
		table-layout: fixed;
	}
	.tbl-qa thead th {
		padding: 11px 12px;
		border: 0;
		border-bottom: 1px solid #e4e9f1;
		background: #f7f9fc;
		color: #657188;
		font-size: 10px;
		font-weight: 700;
		letter-spacing: .045em;
		text-transform: uppercase;
	}
	.tbl-qa th:nth-child(1) { width: 54px; }
	.tbl-qa th:nth-child(2) { width: 24%; }
	.tbl-qa th:nth-child(5) { width: 112px; }
	.tbl-qa td {
		padding: 10px 12px;
		border: 0;
		border-bottom: 1px solid #edf0f5;
		color: #344056;
		vertical-align: middle;
	}
	.tbl-qa tbody tr:last-child td { border-bottom: 0; }
	.tbl-qa tbody tr:not(.satuan-default-row):hover td { background-color: #f8fbff; }
	.satuan-row-number {
		color: #8a96aa !important;
		font-weight: 600;
		text-align: center;
	}
	.satuan-default-row td { background: #fbfcfe; }
	.satuan-unit-select {
		height: 35px;
		border-color: #dce3ed;
		border-radius: 7px !important;
		background-color: #fff;
		color: #344056;
		font-size: 12px;
	}
	.satuan-default-row .satuan-unit-select {
		background-color: #f1f4f8;
		color: #526078;
		opacity: 1;
	}
	.satuan-price-cell {
		position: relative;
		padding-left: 34px !important;
		font-weight: 700;
		font-variant-numeric: tabular-nums;
	}
	.satuan-price-cell::before {
		content: "Rp";
		position: absolute;
		left: 12px;
		top: 50%;
		color: #9aa5b7;
		font-size: 10px;
		font-weight: 600;
		transform: translateY(-50%);
	}
	.satuan-price-cell[contenteditable="true"] {
		cursor: text;
		transition: background-color .18s ease, box-shadow .18s ease;
	}
	.satuan-price-cell[contenteditable="true"]:hover {
		background: #f2f7ff !important;
		box-shadow: inset 0 0 0 1px #d5e4ff;
	}
	.satuan-price-cell[contenteditable="true"]:focus {
		outline: 0;
		background: #fff !important;
		box-shadow: inset 0 0 0 2px #1769ed;
	}
	.satuan-status {
		display: inline-flex;
		align-items: center;
		gap: 6px;
		padding: 5px 9px;
		border-radius: 999px;
		background: #eaf8f0;
		color: #258557;
		font-size: 10px;
		font-weight: 700;
	}
	.satuan-status::before {
		width: 6px;
		height: 6px;
		border-radius: 50%;
		background: #35b675;
		content: "";
	}
	.satuan-delete-btn {
		width: 34px;
		height: 34px;
		padding: 0;
		border: 1px solid #ffd9df;
		border-radius: 7px !important;
		background: #fff5f6;
		color: #e23d55;
	}
	.satuan-delete-btn:hover {
		border-color: #e23d55;
		background: #e23d55;
		color: #fff;
	}
	.satuan-row-actions {
		display: flex;
		justify-content: flex-start;
		gap: 6px;
	}
	@media (max-width: 760px) {
		.satuan-price-toolbar { align-items: flex-start; }
		.satuan-table-shell { overflow-x: auto; }
		.tbl-qa { min-width: 680px; }
	}
</style>

<div class="table-wrapper">
	<div class="satuan-price-toolbar">
		<div>
			<p class="satuan-price-toolbar__title">Daftar harga per satuan</p>
			<p class="satuan-price-toolbar__hint">Klik nilai harga untuk mengubahnya secara langsung.</p>
		</div>
		<button class="btn btn-info btn-sm" id="add-satuan" onClick="createNew();">
			<i class="fa fa-plus" aria-hidden="true"></i> Tambah Satuan
		</button>
	</div>
	<div class="satuan-table-shell">
	<table class="table tbl-qa" id="table_satuan">
		<thead>
			<tr>
				<th class="align-middle text-center">No.</th>
				<th class="align-middle">Satuan</th>
				<th class="align-middle">Harga Beli</th>
				<th class="align-middle">Harga Jual</th>
				<th class="align-middle text-left">Status / Aksi</th>
			</tr>
		</thead>
		<tbody id="table-satuan">
			<tr class="satuan-default-row">
				<td class="satuan-row-number">—</td>
				<td>
					<select class="form-control form-control-sm satuan-unit-select" disabled>
						<option><?=get_satuan($bahan->id_satuan);?></option>
					</select>
				</td>
				<td class="satuan-price-cell"><?=harga_satuan_format($bahan->harga_modal);?></td>
				<td class="satuan-price-cell"><?=harga_satuan_format($bahan->harga_jual);?></td>
				<td><span class="satuan-status">Utama</span></td>
			</tr>
			
			<?php 
				$a = 0;
				$no = 1;
				foreach($result AS $row) {
					$id=$row->id; 
					$satuan=$row->id_satuan; 
					$harga_pokok=harga_satuan_format($row->harga_pokok); 
					$harga_jual=harga_satuan_format($row->harga_jual); 
					
				?>
				<tr class="table-row" id="table-satuan-<?php echo $id; ?>" data-id="<?php echo $satuan; ?>" data-row="<?php echo $a; ?>">
					<td class="satuan-row-number"><?=$no;?></td>
					<td onChange="getData(<?=$a;?>,<?=$id;?>)">
						<select name="load_satuan_edit" id="load_satuan_<?=$a;?>" class="form-control form-control-sm satuan-unit-select" data-valueKey="id" data-displayKey="name" required>
							<option value="">Pilih</option>
							<?php foreach ($satuan_options as $option): ?>
								<option value="<?=$option->id;?>" <?=((string) $option->id === (string) $satuan) ? 'selected' : '';?>><?=$option->satuan;?></option>
							<?php endforeach; ?>
						</select>
					</td>
					<td class="satuan-price-cell" contenteditable="true" title="Klik untuk mengubah harga beli" onBlur="saveToDatabase(this,'harga_pokok','<?php echo $id; ?>')" onClick="editRow(this);"><?php echo $harga_pokok; ?></td>
					<td class="satuan-price-cell" contenteditable="true" title="Klik untuk mengubah harga jual" onBlur="saveToDatabase(this,'harga_jual','<?php echo $id; ?>')" onClick="editRow(this);"><?php echo $harga_jual; ?></td>
					<td><button class="btn btn-sm satuan-delete-btn" title="Hapus satuan" aria-label="Hapus satuan" onclick="deleteRecord(<?php echo $id; ?>);"><i class="fa fa-trash"></i></button></td>
				</tr>
			<?php $a++;$no++;} ?>     
		</tbody>
	</table>
	</div>
	
	<input type="hidden" id="id_bahan" value="<?=$id_bahan;?>">
</div>

<script type="text/javascript">
	var satuan_add = "<?=$bahan->id_satuan;?>";
	var harga_modal = "<?=rp($bahan->harga_modal);?>";
	function createNew() {
		$("#add-satuan").hide();
		no = $('#table_satuan > tbody tr.table-row').length+1;
		i = $('#table_satuan > tbody tr.table-row').length;
		var data = '<tr class="table-row" id="new_row_satuan">' +
		'<td class="satuan-row-number">'+no+'</td><td><select name="load_satuan_add" id="load_satuan_'+i+'" class="form-control form-control-sm satuan-unit-select" data-valueKey="id" data-displayKey="name" required></select></td>'
		data +='<td class="satuan-price-cell" contenteditable="true" id="txt_harga_pokok" title="Klik untuk mengubah harga beli" onBlur="addToHiddenField(this,\'harga_pokok\')" onClick="editRow(this);">'+harga_modal+'</td>';
		data +='<td class="satuan-price-cell" contenteditable="true" id="txt_harga_jual_add" title="Masukkan harga jual" onBlur="addToHiddenField(this,\'harga_jual\')" onClick="editRow(this);"></td>';
		data +='<td><div class="satuan-row-actions">';
		data +='<div class="input-group-append" id="confirmAdd">';
		data +='<button onClick="addToDatabase('+i+')" class="btn btn-success btn-sm" title="Simpan satuan" type="button"><i class="fa fa-check"></i></button>';
		data +='<button onclick="cancelAdd();" class="btn btn-light btn-sm" title="Batal" type="button"><i class="fa fa-remove"></i></button><input type="hidden" id="id_satuan" /> <input type="hidden"  id="harga_pokok" /><input type="hidden" id="harga_jual" />';
		data +='</div></div></td>';
		data +='</tr>';
		$("#table-satuan").append(data);
		satuan_harga_load(i,satuan_add)
	}
	
	function cancelAdd() {
		$("#add-satuan").show();
		$("#new_row_satuan").remove();
	}
	function editRow(editableObj) {
		$(editableObj).css("background","#FFF");
	}
	
	function addToDatabase(i) {
		var satuan = $("#load_satuan_"+i).val();
		var harga_pokok = typeof hargaPrepareValue === 'function' ? hargaPrepareValue('harga_pokok', $("#harga_pokok").val() || $("#txt_harga_pokok").text()) : angka($("#harga_pokok").val());
		var harga_jual = typeof hargaPrepareValue === 'function' ? hargaPrepareValue('harga_jual', $("#harga_jual").val() || $("#txt_harga_jual_add").text()) : angka($("#harga_jual").val());
		var id_bahan = $("#id_bahan").val();
		if(satuan==''){
			return;
		}
		var no = i+1;
		$("#confirmAdd").html('<img src="'+base_url+'assets/img/ajax-loader.gif" />');
		$.ajax({
			url: base_url+"produk/add_satuan_harga",
			type: "POST",
			data:{id:id_bahan,satuan:satuan,harga_pokok:harga_pokok,harga_jual:harga_jual,no:no,row:i},
			success: function(data){
				$("#new_row_satuan").remove();
				$("#add-satuan").show();		  
				$("#table-satuan").append(data);
				satuan_harga_load(i,satuan);
			}
		});
	}
	function addToHiddenField(addColumn,hiddenField) {
		var columnValue = typeof hargaPrepareValue === 'function' ? hargaPrepareValue(hiddenField, $(addColumn).text()) : $(addColumn).text();
		$("#"+hiddenField).val(columnValue);
		if(typeof hargaUpdateCellDisplay === 'function'){
			hargaUpdateCellDisplay(addColumn, hiddenField, columnValue);
		}
	}
	function getData(a,id) {
		// console.log(id);
		var id_satuan = $("#load_satuan_"+a).val();
		saveToDatabase(id_satuan,'id_satuan',id)
	}
	function saveToDatabase(editableObj,column,id) {
		$(editableObj).css("background","#FFF url("+base_url+"assets/img/ajax-loader.gif) no-repeat right");
		if($.isNumeric(editableObj)){
			var editval = editableObj;
			}else{
			var editval = typeof hargaPrepareValue === 'function' ? hargaPrepareValue(column, $(editableObj).text()) : $(editableObj).text();
		}
		$.ajax({
			url: base_url+"produk/edit_harga_satuan",
			type: "POST",
			data:'column='+column+'&editval='+editval+'&id='+id,
			success: function(data){
				if(!$.isNumeric(editableObj)){
					if(typeof hargaUpdateCellDisplay === 'function'){
						hargaUpdateCellDisplay(editableObj, column, editval);
					}
					$(editableObj).css("background","");
				}
			}
		});
	}
	
	function deleteRecord(id) {
		show_Confirm(id);
	}
	
	function show_Confirm(id) {
		confirm.show({
			title: 'Hapus Item',
			content: 'Item akan di hapus, Anda Yakin?',
			btns: [{
				callback: function(instance){
					instance.close = true;
					$.ajax({
						url: base_url+"produk/delete_harga_satuan",
						type: "POST",
						data:'id='+id,
						success: function(data){
							$("#table-satuan-"+id).remove();
						}
					});
				}
				}, {
				text: 'Tidak',
				callback: function(){
					console.log('Hapus item dibatalkan');
				}
			}] 
		})
	}
	
	function satuan_harga_load(tipe,idjenis){
		var $select = $("#load_satuan_harga").find("#load_satuan_"+tipe);
		
		$.ajax({
			url: base_url + "produk/load_satuan_range",
			type: 'POST',
			data: {id:idjenis},
			dataType: 'json',
			beforeSend: function () {
				$select.empty().append("<option value='loading'>loading</option>");
			},
			success: function (response) {
				$select.empty().append("<option value=''>Pilih</option>");
				var len = response.length;
				for (var i = 0; i < len; i++) {
					var id = response[i]['id'];
					var name = response[i]['name'];
					if(id==idjenis){
						$select.append("<option value='" + id + "' selected>" + name + "</option>");
						}else{
						$select.append("<option value='" + id + "'>" + name + "</option>");
					}
					
				}
			},
			error: function (xhr, ajaxOptions, thrownError) {
				sweet('Peringatan!!!',thrownError,'warning','warning');
			}
		});
	}
</script>

