<div class="box">
 	<div class="box-body">
		<div class="panel panel-success">
            <div class="panel-heading">
             	<h3 class="panel-title"><i class="fa fa-dollar"></i>&nbsp;Novo Emprestimo</h3>
            </div>
            <div class="box-body">
<?php
if(isset($_POST['save_loan']))
{
$borrower =  mysqli_real_escape_string($link, $_POST['borrower']);
$baccount = mysqli_real_escape_string($link, $_POST['account']);
$desc = mysqli_real_escape_string($link, $_POST['desc']);
$amount = mysqli_real_escape_string($link, $_POST['amount']);
$juros = mysqli_real_escape_string($link, $_POST['juros']);
$periodo = mysqli_real_escape_string($link, $_POST['periodo']);
$date_release = mysqli_real_escape_string($link, $_POST['date_release']);
$agent = mysqli_real_escape_string($link, $_POST['agent']);
$status = mysqli_real_escape_string($link, $_POST['status']);
$pay_date = mysqli_real_escape_string($link, $_POST['pay_date']);
$amount_topay = mysqli_real_escape_string($link, $_POST['amount_topay']);
$tot_juros = mysqli_real_escape_string($link, $_POST['tot_juros']);
$tot_mes = mysqli_real_escape_string($link, $_POST['tot_mes']);
$upstatus = "Pendente";
$teller = mysqli_real_escape_string($link, $_POST['teller']);
$remark = mysqli_real_escape_string($link, $_POST['remark']);

$sql = mysqli_query($link, "SELECT * FROM balance WHERE amount <= 0") or die (mysqli_error($link));
if (mysqli_num_rows($sql) > 0) {
	echo '<meta http-equiv="refresh" content="2;url=newpoupanca.php?tid='.$_SESSION['tid'].'">';
echo '<br>';
echo'<span class="itext" style="color: #FF0000">O saldo poupado e inferior ou igual a zero.....Nao sera possivel efetuar o emprestimo!</span>';
}else{
	$insert = mysqli_query($link, "INSERT INTO loan_info(`borrower`, `baccount`, `desci`, `amount`, `juros`, `periodo`, `date_release`, `agent`,`status`, `pay_date`, `amount_topay`,`amount_to_pay_invisible`,`tot_juros`, `tot_mes`, `teller`, `remark`, `upstatus`) VALUES('$borrower','$baccount','$desc', '$amount', '$juros', '$periodo','$date_release','$agent','$endereco','$status','$pay_date','$amount_topay','$amount_topay', '$contrato','$tot_juros', '$tot_mes','$teller','$remark','$upstatus')") or die (mysqli_error($link));
if(!$insert)
{
 echo '<meta http-equiv="refresh" content="2;url=newloans.php?tid='.$_SESSION['tid'].'">';
echo '<br>';
echo'<span class="itext" style="color: #FF0000">Impossivel salvar o emprestimo.....Por favor tente novamente!</span>';
}
else{
    $sql = mysqli_query($link, "SELECT LAST_INSERT_ID() as id") or die (mysqli_error($link));
    $dados = mysqli_fetch_assoc($sql);
    $id = $dados['id'];
    $sql = mysqli_query($link, "UPDATE balance set amount = amount - '$amount' WHERE id = 1") or die (mysqli_error($link));
    $sql = mysqli_query($link, "INSERT INTO transacoes(mutuario,emprestimo, descricao, referencia, debito, saldo, data) VALUES('$borrower','$id', '$desc', '$contrato', '$amount_topay', '$amount_topay', '$pay_date')") or die (mysqli_error($link));
echo '<meta http-equiv="refresh" content="2;url=listloans.php?tid='.$_SESSION['tid'].'">';
echo '<br>';
echo'<span class="itext" style="color: #FF0000">Salvando Emprestimo.....Por favor aguarde!</span>';
}
}

}

?>
<form class="form-horizontal" method="post" enctype="multipart/form-data" action="">
			  <?php echo '<div class="alert alert-info fade in" >
			  <a href = "#" class = "close" data-dismiss= "alert"> &times;</a>
  				<strong>Note que&nbsp;</strong> &nbsp;&nbsp;Os campos obrigatorios estao assinalados por <span style="color:red"> *</span>.
				</div>'?>
             <div class="box-body">
				
			 
			 <div class="form-group">
                <label for="" class="col-sm-2 control-label" style="color:#009900"><b style="color:red">*</b> Mutuário</label>
				 <div class="col-sm-10">
                <select name="borrower" class="customer select2" style="width: 100%;" required>
          				<option>--Selecione Cliente--</option>
          				<?php
          				$get = mysqli_query($link, "SELECT * FROM borrowers order by id") or die (mysqli_error($link));
          				while($rows = mysqli_fetch_array($get))
          				{
          				echo '<option value="'.$rows['id'].'">'.$rows['fname'].'&nbsp;'.$rows['lname'].'</option>';
          				}
          				?>
                </select>
              </div>
			  </div>
			  
			<div class="form-group">
                  <label for="" class="col-sm-2 control-label" style="color:#009900"><b style="color:red">*</b> Conta</label>
                  <div class="col-sm-10">
                  <select class="account select2" name="account" style="width: 100%;" required>
			
				</select>
                  </div>
            </div>
		
		
		<div class="form-group">
            <label for="" class="col-sm-2 control-label" style="color:#009900"><b style="color:red">*</b> Valor</label>
                <div class="col-sm-10">
                  <input name="amount" type="number" class="form-control" placeholder="Valor" id="valor" min="0" required step="0.01">
                </div>
        </div>
        <div class="form-group">
            <label for="" class="col-sm-2 control-label" style="color:#009900"><b style="color:red">*</b> Taxa de Juros(%)</label>
                <div class="col-sm-10">
                  <input name="juros" type="number" class="form-control" placeholder="Taxa de Juros" id="juros" min="0" required>
                </div>
        </div>
        <div class="form-group">
            <label for="" class="col-sm-2 control-label" style="color:#009900"><b style="color:red">*</b>Periodo de Vigência(em meses)</label>
            <div class="col-sm-10">
                <input name="periodo" type="number" class="form-control" placeholder="Periodo de Vigencia" id="periodo" min="0" required>
            </div>
        </div>
		
		 <div class="form-group">
                  	<label for="" class="col-sm-2 control-label" style="color:#009900">Descrição</label>
                  	<div class="col-sm-10">
					<textarea name="desc"  class="form-control" rows="4" cols="80"></textarea>
           			 </div>
					 </div>
		
		 <div class="form-group">
                <label for="" class="col-sm-2 control-label" style="color:#009900"><b style="color:red">*</b> Data de Aprovação</label>
			 <div class="col-sm-10">
              <div class="input-group date">
                  <div class="input-group-addon">
                    <i class="fa fa-calendar"></i>
                  </div>
                  <input name="date_release" class="form-control pull-right" id="datepicker" required>
                </div>
              </div>
			  </div>

			<div class="form-group">
                  <label for="" class="col-sm-2 control-label" style="color:#009900">Gestor</label>
                  <div class="col-sm-10">
            
<?php
$tid = $_SESSION['tid'];
$sele = mysqli_query($link, "SELECT * from user WHERE id = '$tid'") or die (mysqli_error($link));
while($row = mysqli_fetch_array($sele))
{
?>
                  <input name="agent" type="text" class="form-control" value="<?php echo $row['name']; ?>" readonly>
<?php } ?>
                  </div>
                  </div>
                  <div class="form-group">
                  <label for="" class="col-sm-2 control-label" style="color:#009900">Estado</label>
                  <div class="col-sm-10">
                  <input name="status" type="text" class="form-control" value="Pendente" readonly="readonly">
                  </div>
                  </div>
	<hr>	
<div class="alert-danger">&nbsp;INFO DE PAGAMENTO</div>
<hr>	
				   <div class="form-group">
                <label for="" class="col-sm-2 control-label" style="color:#009900"><b style="color:red">*</b> Data de Pagamento</label>
			 <div class="col-sm-10">
              <div class="input-group date">
                  <div class="input-group-addon">
                    <i class="fa fa-calendar"></i>
                  </div>
                  <input name="pay_date" type="date" class="form-control pull-right" id="datepicker2" required>
                </div>
              </div>
			  </div>
				  
				  <div class="form-group">
                  <label for="" class="col-sm-2 control-label" style="color:#009900"><b style="color:red">*</b> Total de Juros</label>
                  <div class="col-sm-10">
                  <input name="tot_juros" type="number" class="form-control" placeholder="Total de Juros" id="tot_juros" required readonly step="0.01">
                  </div>
                  </div>
                  <div class="form-group">
                  <label for="" class="col-sm-2 control-label" style="color:#009900"><b style="color:red">*</b> Total a Pagar Mensalmente</label>
                  <div class="col-sm-10">
                  <input name="tot_mes" type="number" class="form-control" placeholder="Total a Pagar Mensalmente" id="tot_mes" required readonly step="0.01">
                  </div>
                  </div>
                  <div class="form-group">
                  <label for="" class="col-sm-2 control-label" style="color:#009900"><b style="color:red">*</b> Valor a pagar</label>
                  <div class="col-sm-10">
                  <input name="amount_topay" type="number" class="form-control" placeholder="Valor a pagar" id="amount_topay" required readonly step="0.01">
                  </div>
                  </div>
				  
				  <div class="form-group">
                  <label for="" class="col-sm-2 control-label" style="color:#009900">Faturado por</label>
                  <div class="col-sm-10">
<?php
$tid = $_SESSION['tid'];
$sele = mysqli_query($link, "SELECT * from user WHERE id = '$tid'") or die (mysqli_error($link));
while($row = mysqli_fetch_array($sele))
{
?>
                  <input name="teller" type="text" class="form-control" value="<?php echo $row['name']; ?>" readonly>
<?php } ?>
                  </div>
                  </div>
				
				
			<div class="form-group">
                  	<label for="" class="col-sm-2 control-label" style="color:#009900">Comentários</label>
                  	<div class="col-sm-10">
					<textarea name="remark"  class="form-control" rows="4" cols="80"></textarea>
           			 </div>
          	</div>
				  
			 </div>
			 
			  <div align="right">
              <div class="box-footer">
                <button type="reset" class="btn btn-primary btn-flat"><i class="fa fa-times">&nbsp;Limpar</i></button>
                <button name="save_loan" type="submit" class="btn btn-success btn-flat" ><i class="fa fa-save">&nbsp;Gravar</i></button>

              </div>
			  </div>
			  </form>
			  

           
</div>	
</div>
</div>
</div>

<script type="text/javascript">
	$(function() {

	    $(".customer").on('change', function(){
	        preecher_select2();
	    });

		function preecher_select2() {
		    var ida = $(".customer").val();
			$.ajax({
				url: 'numeroConta.php',
				type: 'GET',
				data:{
				    id: ida
				},
				success: function(data) {
					$(".account").html(data);
				},
				error: function() {
					$(".account").html("Ocorreu um erro na tentativa de preencher o select!");
				}
			});
		}
		$("#periodo").on('change', function(){
		    var valor = $("#valor").val();
		    var juros = $("#juros").val();
		    var periodo = $(this).val();
		    var taxa = juros/100;
		    var total_juros = valor*taxa*periodo;
	        var total_pagar = parseInt(total_juros)+parseInt(valor);
	        var total_mes = total_pagar/periodo;
	        
	        $("#tot_juros").val(total_juros);
	        $("#tot_mes").val(total_mes);
	        $("#amount_topay").val(total_pagar);
	       //alert(valor+" "+juros+" "+periodo);
		});
	});
</script>