
<!---- 
    Author 	: Wahyu
    Tanggal : 12-08-2014	
    Revisi 	:
-->
<?php
//---------Untuk privellege jika dia ada tombol save----------
	if($group_user->SavePrivillage == 1){
		$cek_autority_save  = "";
	}
	else{
		$cek_autority_save 	= "disabled";
	}
//-------------end----------------------------
?>
<div class="easyui-layout" data-options="fit:true,border:false">
	<!-- top view-->
	<div id="form-header" data-options="region:'north',border:false" >
		 <div id="form-header-wrapper">
				<table cellpadding="0" cellspacing="0" width="100%" height="100%" border="0">
					<tr>
						<td align="left" valign="middle">
							<a href="#" class="easyui-linkbutton" iconCls="icon-document" plain="true" onclick="location.reload()">New</a>
							<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-reload" plain="true" onclick="location.reload()">Refresh</a>
							<!-- <a href="#" class="easyui-linkbutton" iconCls="icon-journal" plain="true" onclick="" disabled>Journal</a> -->
						</td>							
						<td height="25" align="right" valign="middle">								
							<span class="form-title">
								<?= $menu_label; ?>
							</span>
						</td>
					</tr>
				</table>		     	
		 </div>			
	</div>
	<!-- end top view -->	
	<!-- center view -->
	<div id="form-body" data-options="region:'center',border:false">
		<div id="form-wrapper" class="easyui-panel"  style="width:1180px;height:526px;padding:5px;" fit='true'>
			<form id="fm_loan_payment_journal" name="fm_loan_payment_journal" method="post">
                <table cellpadding="0" cellspacing="3" width="100%" height="100%" border="0">
					<tr>
						<td valign="middle" height="22" width="180" align="left"><b>Payment for</b></td>
                        <td><b>:</b></td>
						<td valign="top" align="left" width="800">
							<input name="txt_payment_for" id="txt_payment_for" type="text" style="width:246px;background-color:#E3E2E2;" readonly />
							<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-sales" onclick="modal_open('Payment List','dialog-payment-list')" style="width:110px;" plain="true">List Funding</a>
						</td>
						
						<td align="left" valign="middle">&nbsp;</td>
						<td rowspan="6" align="left" valign="top">
							<table cellpadding="0" cellspacing="0" width="100%" height="100%" border="0">
								<tr>
									<td align="right" valign="top">
										<table cellpadding="0" cellspacing="1" width="100%" border="0">
											<tr>
												<td height="20">&nbsp;</td>
												<!-- <td width="190" align="center" valign="middle" bgcolor="#333399"><span style="color: #fff">Payment Afiliasi No.</span></td> -->
												<td width="122" align="center" valign="middle" bgcolor="#333399"><span style="color:#fff;">Payment Loan Date</span></td>
											</tr>
											<tr>
												<td>&nbsp;</td>
												<!-- <td height="20" align="left" valign="top"> -->
												<!-- <input type="hidden" name="payment_karyawan_no" id="payment_karyawan_no" class="easyui-validatebox" style="width:190px;background-color:#E3E2E2;text-align:center;" required readonly /> -->
												<!-- </td> -->
												<td align="right" valign="top"><input name="txt_payment_date" id="txt_payment_date" type="text" class="easyui-datebox validBackward" style="width:122px;height:20px" required editable="false" value='<?= $date_now;?>'/></td>
											</tr>
										</table>
									</td>
								</tr>
							</table>
						</td>
					</tr>					
					<tr>
						<td valign="top" height="51" align="left" style="padding-top:4px;"><b>Memo</b></td>
                        <td valign="top" style="padding-top:4px;"><b>:</b></td>
						<td valign="top" align="left">
							<textarea class="textbox" name="txa_memo" id="txa_memo" rows="4" style="width:362px;resize:none;white-space:normal;"></textarea>
						</td>
						<td valign="top" align="left">&nbsp;</td>
					</tr>
					<tr>
						<td height="22" valign="top" align="left"><b>Rate</b></td>
                        <td width="10"><b>:</b></td>
						<td valign="top" height="22" align="left">
							<input name="txt_rate" id="txt_rate" type="text" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.'" autoComplete="off" style="width:200px;" required="required" />
							<strong>Currency :</strong> <span id="from_currency"></span> <span>TO</span> <span id="to_currency"></span>
						</td>
						<td valign="top" align="left">&nbsp;</td>
					</tr>
					<tr>
						<td height="22" valign="top" align="left"><b>Outstanding Amount</b></td>
                        <td width="10"><b>:</b></td>
						<td valign="top" height="22" align="left">
							<input name="loan_amount" id="loan_amount" type="text" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.',disabled:true" autoComplete="off" style="width:362px;" required="required" />
							<input name="txt_amount" id="txt_amount" type="hidden" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.',disabled:true" autoComplete="off" style="width:362px;" />
							<input type="hidden" id="detail" name="detail" />
							<input type="hidden" id="hutang_code" name="hutang_code" />
							<input type="hidden" id="hutang_name" name="hutang_name" />
							<input type="hidden" id="rate_funding" name="rate_funding" />
							<input type="hidden" id="currency_funding" name="currency_funding" />
						</td>
						<td valign="top" align="left">&nbsp;</td>
					</tr>
					<tr height="20" style="display:none">
                        <td width="150" align="left"><b>Bank Balance (<span class='bank_balance_currency'></span>)</b></td>
                        <td width="10"><b>:</b></td>
                        <td >
                            <input name="txt_bank_balance" id="txt_bank_balance" type="text" class="easyui-numberbox" data-options="precision:2,decimalSeparator:',',groupSeparator:'.',prefix:''" style="text-align:right;width:362px" readonly />
                        </td>
                    </tr>					
				</table>
                
                <!-- Item Grid -->
                <div class="easyui-tabs" data-options="tabHeight:18" style="margin:5px 0px;">
                    <div title="Item">
                        <table toolbar="#tb_dtg_payment_afiliasi" id="dtg_payment_history" 
                        class="easyui-edatagrid" title="Payment History" idField="id" rownumbers="true" fitColumns="true" singleSelect="true" style="height:250px;"
                        data-options = "
                        	onBeginEdit:function(rowIndex){
								save_button_begendedit('<?=$group_user->SavePrivillage;?>');

								editors = $('#dtg_payment_history').datagrid('getEditors',rowIndex);
								var account_name	= $(editors[0].target);
								var payment_amount	= $(editors[1].target);
								var memo			= $(editors[2].target);

								account_name.combobox().next().children(':text').blur(function(){
									var txt_value 	= $(this).val();
									clearComboBoxInGrid(txt_value,account_name);
								});
					          
							},
							onEndEdit:function(){
								save_button_endedit('<?=$group_user->SavePrivillage;?>');
							}
                        "
                        >
                            <thead>
                                <tr>
                                	<th data-options="field:'AccountHutang',halign:'center',align:'left',width:200">Account Hutang</th>
                                	<th align="center" valign="middle" data-options="
		                                field:'GLAccount',
		                                width:150,									
		                                align:'left',
		                                editor:{
			                                type:'combobox',
			                                options:{
			                                    valueField:'AccountName',
			                                    textField:'AccountName',
			                                    width:290,
			                                    url: '',
			                                    editable:true,
			                           			required:true
		                            	   	 }
		                            	} 
		                      		">Gain Account</th>
                                    <th data-options="field:'PaymentAmount',width:150,halign:'center',align:'right',editor:{type:'numberbox',options:{precision:2,decimalSeparator:',',groupSeparator:'.',required:true,min:0}}" formatter="formatRp">Payment Amount</th>
                                    <th data-options="field:'Memo',halign:'center',align:'left',width:150,editor:{type:'text'}">Memo</th>
                                </tr>
                            </thead>
                        </table>
                        
                        <div id="tb_dtg_payment_afiliasi">
                            <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="addNewRow()">New</a>	
                            <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="remove_row()">Delete</a>							
                        </div>
                    </div>
                </div>
                <!-- End of item grid -->
            </form>
		</div>
	</div>
    <div id="form-footer" data-options="region:'south',border:false">
        <table cellpadding="0" cellspacing="0" width="100%" height="100%" border="0">
             <tr>
               <td align="left">
               </td>
                <td align="right">                              
                      <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-help" onclick="" plain="true">Help</a>
                     <a href="javascript:void(0)" class="easyui-linkbutton form-button save-button" iconCls="icon-save" onclick="save_me()" <?= $cek_autority_save;?>>Save</a>
                     <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-cancel" onclick="parent.tab_close('tt')">Cancel</a>
                </td>
             </tr>
        </table>				
    </div>	
</div>

<!-- Dialog Payment List -->
<div id="dialog-payment-list" class="easyui-dialog" style="width:940px; left:150px; top:50px; background-color:#F8F8F8; height:500px; padding: 0 0px 0 0px" closed="true" data-options="modal:true" buttons="#dialog-buttons">
	<table id="tb_piutang_list" class="easyui-datagrid"  style="width:900px;height:500px"
        url="<?= base_url().$menu_link; ?>/get_piutang"
        singleSelect="true"
        idField="" data-options="
        	rowStyler: function(index,row){
				if (row.LFIsLock=='Locked'){					
					return 'background-color:#FF6666;color:#fff;';
				}					
			}
        ">
		<thead>
			<tr>
				<th field="BranchName" width="120" align="center">Branch</th>
				<th field="AccountName" width="180" align="left">Loan Account</th>
				<th field="LFNumber" width="150" align="center">No Hutang</th>
				<th field="LFAmount" formatter="formatRp" width="135" align="right" halign="center">Amount</th>
                <th field="outstanding" width="130" formatter="formatRp" align="right" halign="center">Sisa Hutang</th>	
                <th field="CurrencyCode" width="80" align="right" halign="center">Currency Code</th>	
                <th field="LFIsLock" align="right" width="90"  halign="center" >Status</th>
                <th field="LFDesc" align="right" width="90"  halign="center" hidden="true">Memo</th>
                <th field="BranchCode" hidden="true" width="120" align="center">Branch Code</th>	
                <th field="LFAccount" hidden="true" width="120" align="center">LFAccount</th>
                <th field="CurrencyRate" hidden="true" width="120" align="center">CurrencyRate</th>			
			</tr>
		</thead>
	</table>
	<div id="dialog-buttons">
		<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onClick="get_piutang()">OK</a>
		<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onClick="modal_close('dialog-payment-list')">Cancel</a>
	</div>
</div>

<script type="text/javascript">

	var SavePrivillage 	= '<?=$group_user->SavePrivillage;?>';

	$(document).ready(function(){

		$('#fm_loan_payment_journal').click(function(){
			calculate_amount();
			var rownumbers = $('.datagrid-cell-rownumber').length;
			for(var x = 0; x < rownumbers; x++){
				$('.datagrid-cell-rownumber').eq(x).html(x+1);
				
			}
	    });

	});

	function get_piutang(){
		var rows = $('#tb_piutang_list').datagrid('getSelected');
		if(rows.LFIsLock=='Locked'){
			$.messager.alert('Info','Tidak bisa memilih Transaksi yang di-Lock');
		}
		else{
			
			var BranchName 		= rows.BranchName;
			var AccountName 	= rows.AccountName;
			var LFNumber 		= rows.LFNumber;
			var LFAmount 		= rows.LFAmount;
			var outstanding 	= rows.outstanding;
			var LFDesc 			= rows.LFDesc;
			var BranchCode 		= rows.BranchCode;
			var LFAccount 		= rows.LFAccount;
			var CurrencyRate 	= rows.CurrencyRate;
			var CurrencyCode 	= rows.CurrencyCode;

			var url_gl_Account 				= '<?= base_url().$menu_link; ?>/get_gl_account/'+CurrencyCode;

			var dg 							= $('#dtg_payment_history');

			var revenue 					= dg.datagrid('getColumnOption','GLAccount');
			revenue.editor.options.url 		= url_gl_Account;
			revenue.editor.options.required = true;
			
			$('#dtg_payment_history').datagrid('loadData',{'total':0,'rows':[]});
			$('#dtg_payment_history').datagrid('reload');

			get_master_rate(CurrencyCode);
			$('#rate_funding').val(CurrencyRate);
			$('#hutang_code').val(LFAccount);
			$('#hutang_name').val(AccountName);
			$('#txt_payment_for').val(LFNumber);
		   	$('#txa_memo').html(LFDesc);
		   	$('#currency_funding').val(CurrencyCode);

		   	$('#txt_amount').numberbox('setValue',0);
		   	$('#loan_amount').numberbox('setValue',outstanding);

		   	if(CurrencyCode == 'IDR'){
		   		 $('#txt_rate').numberbox({disabled:true});
		   		 $('#from_currency').html(CurrencyCode);
		   		 $('#to_currency').html('IDR');
		   	}else{
		   		 $('#txt_rate').numberbox({disabled:false});
		   		 $('#from_currency').html(CurrencyCode);
		   		 $('#to_currency').html('IDR');
		   	}

			modal_close('dialog-payment-list');
		}
	}

	function addNewRow(){

		var no_piutang 			= $('#txt_payment_for').val();
		var hutang_name 		= $('#hutang_name').val();
		var row 				= $('#dtg_payment_history').datagrid('getRows');
		$('#dtg_payment_history').datagrid('endEdit', (row.length - 1));

		/*======================== tambahkan 1 row ke datagrid payment history ===============================*/
		if(no_piutang == ''){
			$.messager.alert('Warning','Silahkan pilih Funding terlebih dahulu','Warning');
		}else{
			 $('#dtg_payment_history').datagrid('appendRow',{
				AccountHutang		: hutang_name,
				PaymentAmount 		: 0,
				GainAccount 		: ''
			});

			$('#dtg_payment_history').datagrid('beginEdit', (row.length - 1));
		}

	}

	function remove_row(){
		var row 			= $('#dtg_payment_history').datagrid('getRows');
		$('#dtg_payment_history').datagrid('endEdit', (row.length - 1));

	    $('#dtg_payment_history').edatagrid('saveRow');  

	    var selectedrow         = $('#dtg_payment_history').datagrid('getSelected');
	    var row_index           = $('#dtg_payment_history').datagrid('getRowIndex', selectedrow);
	    
	    $.messager.confirm('Confirmation :', 'Anda yakin, Anda ingin menghapus item "' + selectedrow.GainAccount + '"?',  
	        function(r){
	            if (r){

	                $('#dtg_payment_history').datagrid('deleteRow', row_index);
	                calculate_amount();
	            }
	        }
	    );
	}

	function calculate_amount(){

		var row 			= $('#dtg_payment_history').datagrid('getRows');
		$('#dtg_payment_history').datagrid('endEdit', (row.length - 1));

		/*===================== save row & get all rows =======================*/
		$('#dtg_payment_history').edatagrid('saveRow');	
		var row_payment 	= $('#dtg_payment_history').datagrid('getRows');

		var total_piutang  	= parseFloat($('#loan_amount').numberbox('getValue'));
		var total_payment 	= 0;

		/*============== looing item datagrid payment history ===================*/
		$.each(row_payment, function( index,value) {
	        total_payment 	+= parseFloat(value.PaymentAmount);
	    });

	    if(total_payment > total_piutang){
	    	$.messager.alert('Warning','Pembayaran melebihi sisa nilai pinjaman','error',function(){
				$('#txt_amount').numberbox('setValue',0);
			});
	    }else{
	    	$('#txt_amount').numberbox('setValue',total_payment);
	    }
	}

	function save_me(){

		/*===================== save row & get all rows =======================*/
		$('#dtg_payment_history').edatagrid('saveRow');	

		var row_payment 	= $('#dtg_payment_history').datagrid('getRows');
		$('#dtg_payment_history').datagrid('endEdit', (row_payment.length - 1));

		var total_payment  	= 0;
		var loan_amount 	= parseFloat($('#loan_amount').numberbox('getValue'));

		/*============== looing item datagrid payment history ===================*/
		$.each(row_payment, function( index,value) {
	        total_payment 	+= parseFloat(value.PaymentAmount);
	    });

	    if(loan_amount < total_payment){
	    	$.messager.alert('Unseccessfull','Pembayaran melebihi sisa nilai pinjaman','error',function(){
				$('#txt_amount').numberbox('setValue',0);
				$('#dtg_payment_history').datagrid('reload'); 
			});
	    }else{

	    	var amount_payment 	= parseFloat($('#txt_amount').numberbox('getValue'));
	    	var amount_piutang 	= parseFloat($('#loan_amount').numberbox('getValue'));

	    	var detail 			= JSON.stringify($('#dtg_payment_history').datagrid('getRows'));
	    	$('#detail').val(detail);

	    	if(amount_payment > 0){
	    		if(amount_payment == amount_piutang){
					save_transaction('<?= $menu_link?>','#fm_loan_payment_journal');	
				}else{
					$.messager.alert('Unseccessfull','Total Payment Amount harus sama dengan Loan Amount.','error',function(){
					
					});
				}
			}else{
				$.messager.alert('Unseccessfull','Belum ada detail transaksi payment.','error',function(){

				});
			}
	    }
	}

</script>
