<!---- 
    Author 	: Wahyu
    Tanggal : 12-08-2014	
    Revisi 	:
-->
<?php
//---------Untuk privellege jika dia ada tombol save,suspen,jurnal----------
	if($group_user->SavePrivillage == 1){
		$cek_autority_save  = "";
	}
	else{
		$cek_autority_save 	= "disabled";
	}
	
	if($group_user->JournalPrivillage == 1){
		$cek_autority_journal  = "";
	}
	else{
		$cek_autority_journal 	= "disabled";
	}
	
	if($group_user->DeletePrivillage == 1){
		$cek_autority_delete  = "";
	}
	else{
		$cek_autority_delete 	= "disabled";
	}
	if($group_user->ReversePrivillage == 1){
        $cek_autority_reverse  = "";
    }
    else{
        $cek_autority_reverse    = "display:none";
    }
//-------------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">
                            <input type="checkbox" class="easyui-checkbox" name="chk_suspended" id="chk_suspended" style="margin-top:0px;margin-right:1px;" onclick="suspend_transaction(1,'<?= $menu_link;?>',$('#payment_karyawan_no').val(),'<?=$menu_label;?>')" <?=(!in_array($detail->TransStatus,array(4,6))) ? 'disabled' : ''?> <?=($detail->TransStatus) == 3 ? 'checked':''?> <?= $cek_autority_delete;?>/>
                            <span style="display:inline-block;margin-top:2px;<?=(($detail->TransStatus==3)?'color:gray;':'color:black')?>">Suspend</span>
							<a href="#" class="easyui-linkbutton" iconCls="icon-journal" plain="true" onclick="parent.tab_edit('Journal <?=$menu_label?>', '<?= $menu_link; ?>', 'icon-bank', 'to_journal',$('#payment_karyawan_no').val())" <?= $cek_autority_journal;?>>Journal</a>
							<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-reload" plain="true" onclick="location.reload()">Refresh</a>
							
						</td>
						<td align="center" width="40%"><span id="approval_information">
		                <?php
		                if($detail->TransStatus == 4){
		                    echo get_status_approval_header($detail->TransStatus);
		                }
		                ?>
		                </span></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">
    <?php if($detail->TransStatus==2){ ?>
        <div class="blanket"></div>
        <div class="paid-box"><b>Paid</b></div>
    <?php }else if($detail->TransStatus==3){ ?>
    	 <div class="blanket"></div>
         <div class="suspend-box"><b>Suspended</b></div>
	<?php
	}
	?>
		<div id="form-wrapper" class="easyui-panel"  style="width:1180px;height:526px;padding:5px;" fit='true'>
			<form id="fm_payment_karyawan" name="fm_payment_karyawan" 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" value="<?=$detail->EDebtNumber;?>" type="text" style="width:362px;background-color:#E3E2E2;" readonly />
						</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="text" name="payment_karyawan_no" id="payment_karyawan_no" value="<?=$detail->EInjNumber;?>" 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='<?=$detail->EInjDate;?>' readonly/></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;"><?=$detail->EInjDesc;?></textarea>
						</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" value="<?=$detail->EInjAmount;?>" 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" value="<?=$detail->EInjAmount;?>" 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="detail_id" name="detail_id" />
							<input type="hidden" id="emp_code" name="emp_code" value="<?=$detail->EmplTransCode;?>" />
							<input type="hidden" id="emp_name" name="emp_name" value="<?=$detail->EmployeeName;?>" />
						</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;"
                        url="<?= base_url().$menu_link;?>/get_history_payment/<?= str_replace('/', '__',$detail->EInjNumber);?>"
                        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>
                                	<?php if($detail->TransStatus == 4):?>
                                		<th data-options="field:'EInjDetailID',halign:'center',align:'left',width:200" hidden="true">EInjDetailID</th>
	                                	<th data-options="field:'EmployeeName',halign:'center',align:'left',width:200">Payment Employee</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: '<?= base_url().$menu_link; ?>/get_gl_account',
				                                    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>
	                                <?php else:?>
	                                	<th data-options="field:'EInjDetailID',halign:'center',align:'left',width:200" hidden="true">EInjDetailID</th>
	                                	<th data-options="field:'EmployeeName',halign:'center',align:'left',width:200">Payment Employee</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,
				                           			disabled: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,disabled:true}}" formatter="formatRp">Payment Amount</th>
	                                    <th data-options="field:'Memo',halign:'center',align:'left',width:150,editor:{type:'text',disabled:true}">Memo</th>
	                                <?php endif;?>
                                </tr>
                            </thead>
                        </table>
                        
                        <div id="tb_dtg_payment_afiliasi">
                            <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 app-button" iconCls="icon-ok" onclick="app_mgr()" <?= (($this->session->userdata("jobtitle_status") != 1 || !in_array($detail->TransStatus, array(4,6))) || (date('Y-m-d') < date('Y-m-d', strtotime($detail->EInjDate))))?'disabled':'' ?>>App. Mgr</a>
			 		 <a href="javascript:void(0)" class="easyui-linkbutton form-button app-button" iconCls="icon-reload" onclick="app_reverse()" <?=(in_array($detail->TransStatus,array(1,2,9)))?'':'disabled'?> style="<?= $cek_autority_reverse;?>" >Reverse</a>
			 		 <a href="javascript:void(0)" class="easyui-linkbutton form-button save-button" iconCls="icon-save" onclick="save_me()" <?=(in_array($detail->TransStatus,array(0,1,2,3)))?'disabled':''?> <?= $cek_autority_save;?>>Save</a> 								
			 	 	 <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-print" onclick="parent.tab_edit('Print Payment Karyawan', '<?=$menu_link?>', 'icon-print', 'to_print_detail','<?= $detail->EInjNumber;?>');" <?=(in_array($detail->TransStatus,array(4,5,6,1,2,3,9)))?'':'disabled'?>>Preview & Print</a>  
			 		 <a href="javascript:void(0)" class="easyui-linkbutton form-button" iconCls="icon-cancel" onclick="<?=($this->session->userdata('jobtitle_status')==0)?'suspend(2)':'parent.tab_close(\'tt\')'?>" <?=(!in_array($detail->TransStatus,array(0,4,6)))?'disabled':''?>><?=($this->session->userdata('jobtitle_status')==0)?'Cancel':'Close'?></a>
                </td>
             </tr>
        </table>				
    </div>
</div>

<script type="text/javascript">

var SavePrivillage 	= '<?=$group_user->SavePrivillage;?>';
var array_item 		= [];

$(document).ready(function(){
	
	$('#fm_payment_karyawan').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);
			
		}
    });


    $('#txt_payment_for').on('mouseover',function(){
    	$(this).css({'color':'blue','font-weight':'bold','cursor':'pointer'});
    }).on('mouseout',function(){
    	$(this).css({'color':'#545454','font-weight':'normal'});
    }).on('click',function(){
    	var TransNumber = $(this).val();
    	parent.tab_edit('Edit Piutang Karyawan','list/piutang_karyawan', 'icon-edit', 'edit',TransNumber) ;
    });

});

function remove_row(){
    var item = $('#dtg_payment_history').datagrid('getData').total;

    if(item <= 1){
        $.messager.alert('Warning','Anda tidak dapat menghapus list detail, minimum list detail adalah satu (1)','error');
    }
    else {
        $('#dtg_payment_history').edatagrid('saveRow');     
        var selectedrow     = $('#dtg_payment_history').datagrid('getSelected');
        var row_index       = $('#dtg_payment_history').datagrid('getRowIndex', selectedrow);

        $.messager.confirm('Confirmation :', 'Apakah Anda yakin akan menghapus account ini ?',  
            function(r){
                if (r){
                  
                   array_item.push(selectedrow.EInjDetailID);
                   $("#detail_id").val(JSON.stringify(array_item));
                   $('#dtg_payment_history').datagrid('deleteRow', row_index);
                   $('.app-button').linkbutton('disable');
                   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);
    }
}

//======== 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){

    			var login_as        = "<?= $this->session->userdata('username');?>";
			    var created_by      = "<?= $detail->CreatedBy;?>";
			    var depart_by       = "<?= $detail->DepartmentCode;?>";
				var depart_ses      = "<?= $this->session->userdata('department');?>";
				var jobtitle_status = "<?= $this->session->userdata('jobtitle_status');?>";

			    var no_transaksi    = $('#payment_karyawan_no').val();
			    var status          = '<?= $detail->TransStatus;?>';

			    // $('#dtg_payment_history').edatagrid('saveRow');
		     //    var i=$('#dtg_payment_history').datagrid('getRows');
		     //    var detail = JSON.stringify(i);
		     //    $("#detail").val(detail);
	      //       edit_data('<?=$menu_link?>','#fm_payment_karyawan',created_by,login_as,depart_by,depart_ses,jobtitle_status);

				checking_update(no_transaksi,status,function(check){
        
			        if(check.status == true){

			        	$('#dtg_payment_history').edatagrid('saveRow');
				        var i=$('#dtg_payment_history').datagrid('getRows');
				        var detail = JSON.stringify(i);
				        $("#detail").val(detail);
			            edit_data('<?=$menu_link?>','#fm_payment_karyawan',created_by,login_as,depart_by,depart_ses,jobtitle_status);

			        }else{
			            $.messager.alert('Unseccessfull',check.message,'error',function(){
			                location.reload();
			            });
			        }

			    });

			}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 ===========

function app_mgr(){

	var no_transaksi    = $('#payment_karyawan_no').val();

    checking_approval(no_transaksi,function(check){
        
        if(check.status == false){
             approved_data('<?=$menu_link?>','#fm_payment_karyawan');
        }else{
            $.messager.alert('Unseccessfull',check.message,'error',function(){
                location.reload();
            });
        }
    });
		
}

function app_reverse(){
	var no_transaksi    = $('#payment_karyawan_no').val();
    
    checking_reverse(no_transaksi,function(check){
        if(check.status == true){
            reversed_data('F','<?=$menu_link?>',no_transaksi, '<?=$menu_label?>');
        }else{
           $.messager.alert('Unseccessfull',check.message,'error',function(){
                location.reload();
            });
        }
    });
}

function suspend(type){
    var created_by      = '<?php echo $detail->CreatedBy;?>';
    var login_as        = '<?php echo$this->session->userdata('username');?>';
    var job_title       = '<?php echo $this->session->userdata('jobtitle_status');?>';
    var url             = '<?= base_url();?>custom/custom/checking_suspend';
    
    suspend_check_trans('F', type, '<?=$menu_link?>', $('#payment_karyawan_no').val(), '<?=$menu_label;?>', url, created_by, login_as, job_title);
}

</script>