<!---- 
    Author 	: Herpan
    Tanggal : 12-08-2014	
    Revisi 	: Daswan
-->
<?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="parent.tab_add('New Payment Afiliasi Journal','<?=$menu_link?>','icon-add','add')">New</a>
							<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-reload" plain="true" onclick="location.reload()">Refresh</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_payment_afiliasi" name="fm_payment_afiliasi" method="post">
            <input type="hidden" name="txt_status_new" id="txt_status_new" />
                <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('List Piutang','dialog_piutang_list')" style="width:110px;" plain="true">List Piutang</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 Afiliasi Date</span></td>
											</tr>
											<tr>
												<td>&nbsp;</td>
												<!-- <td height="20" align="left" valign="top"> -->
													<input type="hidden" name="payment_afiliasi_no" id="payment_afiliasi_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_afiliasi_date" id="txt_payment_afiliasi_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="22" align="left"><b>Loss Account</b></td>
                        <td><b>:</b></td>
						<td valign="top" align="left">
							<select name="loss_account" id="loss_account" editable='true' class="combo-grid"
									style="width:365px;" required="true" 
									data-options="
										panelWidth:350,
                                        idField: 'AccountNumber',
                                        textField: 'AccountName',
                                        method : 'get',
                                        url:'',
                                        columns: [[
                                            {field:'AccountNumber',title:'Account Number',width:110,halign:'center',hidden:true}, 
                                            {field:'AccountName',title:'Bank Name',width:190,halign:'center'}, 
                                            {field:'CurrencyCode',title:'Bank Currency',width:80,halign:'center',align:'center'}
                                        ]],
                                        fitColumns: true,
										onSelect:function(rowIndex,rowData){
                                            get_bank_balance(rowData.AccountNumber,rowData.CurrencyCode);
										}
									">
							</select>
						</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>Loan 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="comp_from" name="comp_from" />
							<input type="hidden" id="comp_to" name="comp_to" />
							<input type="hidden" id="comp_to_name" name="comp_to_name" />
						</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:'PaymentCompany',halign:'center',align:'left',width:200">Payment Company</th>
                                	<th align="center" valign="middle" data-options="
		                                field:'GainAccount',
		                                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:',',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 piutang List -->
<div id="dialog_piutang_list" class="easyui-dialog" style="width:900px;background-color:#F8F8F8;height:550px;padding: 0 0px 0 0px" closed="true" 
	data-options="modal:true,fitColumns:true" buttons="#dialog-buttons">
	<table id="tb_piutang_list" class="easyui-datagrid"  
        url="<?= base_url().$menu_link;?>/list_piutangafiliasi"
        idField="ADebtNumber" singleSelect="true"
        fitColumns="true" fit="true"
        data-options = "
        	rowStyler: function(index,row){
				if (row.IsLock=='Locked'){					
					return 'background-color:#FF6666;color:#fff;';
				}					
			}
        "
    >
		<thead>
			<tr>
				<th rowspan="2" field="ADebtNumber" width="180" align="center"><b>ADebtNumber</b></th>	
				<th colspan="2"><b>Dari</b></th>
				<th colspan="2"><b>Ke</b></th>
				<th rowspan="2" field="BalanceAmount" width="135" align="center" formatter="formatRp"><b>Sisa Amount</b></th>				
				<th rowspan="2" field="ADebtAmount" width="135" align="center" formatter="formatRp"><b>Amount</b></th>
                <th rowspan="2" field="IsLock" width="50" align="center"><b>Status</b></th>
			</tr>
			<tr>
				<th field="CompFrom" width="120" align="center"><b>Perusahaan</b></th>
				<th field="BankFrom" width="120" align="center"><b>Bank</b></th>
				<th field="CompTo" width="120"  align="center"><b>Perusahaan</b></th>
				<th field="BankTo" width="120"  align="center"><b>Bank</b></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_piutang_list')">Cancel</a>
	</div>
</div>


<script type="text/javascript">

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

$(document).ready(function(){
	
	$('#payment_afiliasi_no').val('<?= $payment_afiliasi_number; ?>');

	$('#fm_payment_afiliasi').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.IsLock=='Locked'){
		$.messager.alert('Info','Tidak bisa memilih Transaksi yang di-Lock');
	}
	else{
		var piutang_no 		= rows.ADebtNumber;
		var comp_from		= rows.CompFromCode;
		var comp_to_name 	= rows.CompTo;
		var comp_to			= rows.CompToCode;	
		var bank_from		= rows.BankFromCode;
		var bank_to			= rows.BankToCode;
		var cheque_no		= rows.ChequeNumber;
		var cheque_stat		= rows.CqTermStatus;
		var cheque_date		= rows.ChequeDate;
		var description		= rows.ADebtDesc;
		var amount			= rows.ADebtAmount;
		var sisa_amount 	= rows.BalanceAmount;
		
		var replace_piutang_no	= piutang_no.replace('/','.');
		var replace_piutang_no2	= replace_piutang_no.replace('/','.');

		var url_bank_to 	= '<?= base_url().$menu_link; ?>/get_other_expense/'+comp_from;
		$('#loss_account').combogrid('grid').datagrid('loadData', {'total':0,'rows':[]});
		$('#loss_account').combogrid('grid').datagrid({
			url:url_bank_to,
		});

		var url_revenue_account 	= '<?= base_url().$menu_link; ?>/get_other_revenue/'+comp_to;

		var dg 						= $('#dtg_payment_history');

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

		$('#comp_from').val(comp_from);
		$('#comp_to').val(comp_to);
		$('#comp_to_name').val(comp_to_name);

		$('#txt_payment_for').val(piutang_no);
	   	$('#txa_memo').html(description);

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

		modal_close('dialog_piutang_list');
	}
}

function addNewRow(){

	var no_piutang 		= $('#txt_payment_for').val();
	var comp_to 		= $('#comp_to_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 piutang terlebih dahulu','Warning');
	}else{
		 $('#dtg_payment_history').datagrid('appendRow',{
			PaymentCompany		: comp_to,
			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();
            }
        }
    );
}
	
//== Button Calculator
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);
    }
}
//== End Button Calculator


//======== SAVE ========
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_payment_afiliasi');	
			}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(){

			});
		}
    }
}
//======= END SAVE ===========
</script>