<?php include 'auth_header.php'; ?>

    <?php
					                                if(isset($_POST['add_loan'])){
						   
						                            $conn = mysqli_connect($host, $username, $password, $database);
                                                    
                                                    // Check connection
                                                    
                                                    if (!$conn) {
                                                          die("Connection failed: " . mysqli_connect_error());
                                                    }
                                                     
                                                    echo ""; 
                                                    
                                                    $db_select = mysqli_select_db($con, $database);
						   
						                         
                                                    $name =$_REQUEST['name'];
						                            $uname =$_REQUEST['uname'];
						                            $email =$_REQUEST['email'];
						                            $loanamt =$_REQUEST['loanamt'];
						                            $inter =$_REQUEST['inter'];
						                            $dura =$_REQUEST['dura'];
                                                    $monthlypay =$_REQUEST['monthlypay'];
                                                    $purpose =$_REQUEST['purpose'];
                                                    $balance =$_REQUEST['balance'];
                                                    $status =$_REQUEST['status'];
                                                    $date =$_REQUEST['date'];            
                                            
    $stmt = $reg_user->runQuery("SELECT * FROM quick_loan WHERE loanamt=:loanamt");
    $stmt1 = $reg_user->runQuery("SELECT * FROM quick_loan WHERE dura=:dura"); 
    $stmt->execute(array(":loanamt" => $loanamt));
    $stmt1->execute(array(":dura" => $dura)); 
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $row1 = $stmt1->fetch(PDO::FETCH_ASSOC); 


    if ($stmt->rowCount() > 0 || $stmt1->rowCount() > 0 ) {
        $msg = "
		      <div class='alert alert-danger'>
				<button class='close' data-dismiss='alert'>&times;</button>
					<strong>Sorry!</strong> You Have Same Amount Pending Application, Contact Support
			  </div>
			                                                            <script type='text/javascript'>
                                                							<!--
                                                							function Redirect() {
                                                							window.location='user_home.php';
                                                							}
                                                							document.write ('');
                                                							setTimeout('Redirect()', 3000);
                                                							//-->
                                                							</script>
			  ";
    } else {        
        $sql = "INSERT INTO `quick_loan` (`id`, `name`, `uname`, `email`, `loanamt`, `inter`, `dura`, `monthlypay`, `purpose`, `balance`, `status`, `date`) 
        VALUES (NULL, '$name', '$uname', '$email', '$loanamt', '$inter', '$dura', '$monthlypay', '$purpose', '$balance', '$status', '$date')"; 
                                                      
                                                                            
          
                            						   $insert=mysqli_query($conn, $sql);
                            						   
                            						   if($insert){
                            						       
                            						       
                            							  	$msg = "
                                            					<div class='alert'> 
                                            				 <strong >Loan Application Was Successful, Please Wait for Approval
                                                                       </strong>
                                                                       
                                                                       	<script type='text/javascript'>
                                                							<!--
                                                							function Redirect() {
                                                							window.location='user_loanstatus.php';
                                                							}
                                                							document.write ('');
                                                							setTimeout('Redirect()', 5000);
                                                							//-->
                                                							</script>
                                            			  		</div>
                                            					";
                            							   
                            						   }else{
                            						       
                            						       $msg1= '<h3>Loan Application Failed!</h3>';
                            						       
                            						       
                            						   }
                            					   
					                                }
					                                }
                            					?>
                    
                    
                    
                                                                                                        
                                                      
                                                         
<!-- partial -->
      <div class="main-panel"> 
       
        <div class="content-wrapper">
            
            <?php if (isset($msg)) echo $msg; ?>  
               <?php if (isset($msg1)) echo $msg1; ?>  
          <div class="row">
              
              
              
               <div class="col-12 col-xl-8 mb-4 mb-xl-0">
                  <h3 class="font-weight-bold"><?php echo welcome();  ?> <?php echo $row['fname']; ?> <?php echo $row['lname']; ?>   <div class="badge badge-success"><?php echo $row['type']; ?></div></h3>
                  <h5 class="font-weight-normal mb-0">Account Number: <div class="badge badge-danger"><?php
function mask_mobile_no($number)
{
    return substr($number, 0, 5) . '*****' . substr($number, -2);
}
$number = $row['acc_no']; 
echo mask_mobile_no($number) ;
?></div> </h5><br>
                </div>
              
              
              
              
              
              
            <div class="col-md-6 grid-margin stretch-card">
              <div class="card">
                <div class="card-body">
                    
                      
                  <h4 class="card-title">Loan Application</h4>
                  <p class="card-description">
                    All fields are neccessary
                  </p>
                  
                       
   
 
            <form id="loan-form" class="forms-sample" >
              
              
               <div class="form-group">
                    <div class="input-group">
                      <div class="input-group-prepend">
                        <span class="input-group-text">$</span>
                      </div>
                        <input type="number" class="form-control" id="amount" placeholder="Loan Amount" required>
                    </div>
                  </div>
              
              
              
                <div class="form-group">
                    <div class="input-group">
                      <div class="input-group-prepend">
                        <span class="input-group-text">%</span>
                      </div>
                          <input type="number" class="form-control" id="interest" value="20.17" required >
                    </div>
                  </div>
              
              
              <div class="form-group">
                    <div class="input-group">
                      <div class="input-group-prepend">
                        <span class="input-group-text">Year</span>
                      </div>
                         <input type="number" class="form-control" id="years" placeholder="Period To Repay" required>
                    </div>
                  </div>
                  
                  
              
             
              <div class="form-group">
                <input type="submit" value="Calculate"  class="btn btn-primary mr-2">
              </div>

              
            </form>
        
      
            <div id="results" class="pt-4">
              <h5>Results</h5>
               <div class="form-group">
                    <div class="input-group">
                      <div class="input-group-prepend">
                        <span class="input-group-text">Monthly Payment</span>
                      </div>
                       <input type="number" class="form-control" id="monthly-payment" disabled> 
                    </div>
                  </div>
              
              
                <div class="form-group">
                    <div class="input-group">
                      <div class="input-group-prepend">
                        <span class="input-group-text">Total Payment</span>
                      </div>
                    <input type="number" class="form-control" id="total-payment" disabled>
                    </div>
                  </div>
              
              
              <div class="form-group">
                    <div class="input-group">
                      <div class="input-group-prepend">
                        <span class="input-group-text">Total Interest</span>
                      </div>
                     <input type="number" class="form-control" id="total-interest"  disabled>
                    </div>
                  </div>
   
            </div> 
              

     
 
                       
                       
                </div>
              </div>
            </div>
            <div class="col-md-6 grid-margin stretch-card">
              <div class="card">
                <div class="card-body">
                  <h4 class="card-title">Loan Calculation Results</h4>
                  <p class="card-description">
                   results displayed
                  </p>
                   
                  <form  class="forms-sample" autocomplete="off" method="POST" action="">
              
         
              
              
            
           
   
            <div class="form-group">
                    <div class="input-group">
                      <div class="input-group-prepend">
                        <span class="input-group-text">Year(s)</span>
                      </div>
                     <input type="number" class="form-control" id="" name="dura" required>
                    </div>
                  </div>
                  
                  
                   <div class="form-group">
                    <div class="input-group">
                      <div class="input-group-prepend">
                        <span class="input-group-text">Loan Amount ($)</span>
                      </div>
                     <input type="number" class="form-control" id="" name="loanamt" required>
                    </div>
                  </div>


                <div class="form-group">
                    <div class="input-group">
                       <textarea class="form-control" name="purpose"
                                 placeholder="state the purpose of the loan" id="exampleFormControlTextarea1" rows="5" required=""></textarea>
                    </div>
                  </div>




                   <input class="custom-date form-control"  type="hidden" name="email" value="<?php echo $row['email']; ?>"> 
								      <input class="custom-date form-control"  type="hidden" name="name" value="<?php echo $row['fname']; ?> <?php echo $row['lname']; ?>"> 
								     <input class="custom-date form-control"  type="hidden" name="uname" value="<?php echo $row['uname']; ?>"> 
								       <input class="custom-date form-control"  type="hidden" name="inter" value="0.00%"> 
								    <input class="custom-date form-control"  type="hidden" name="monthlypay" value="USD0.00"> 
								    <input class="custom-date form-control"  type="hidden" name="status" value="PENDING"> 
                                    <input class="custom-date form-control"  type="hidden" name="balance" value="0.00">  
                                    <input class="custom-date form-control"  type="hidden" name="date" value="<?php echo date("h:i A d M Y"); ?>"> 






               <div class="form-group">
                <input type="submit" value="Apply Now" name="add_loan" class="btn btn-primary mr-2">
              </div>
     
           </form>
                   
                   
                   
                   
                </div>
              </div>
            </div>
            
          
            
           
            
        
            
          </div>
        </div>
        
 










<!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
    <script >
        
        
        // Listen for submit
document.getElementById('loan-form').addEventListener('submit', calculateResults);

// Calculate Results
function calculateResults(e){

// console.log("calculating");

// Declare UI Variables

const amount = document.getElementById('amount');
const interest = document.getElementById('interest');
const years = document.getElementById('years');
const monthlyPayment = document.getElementById('monthly-payment');
const totalPayment = document.getElementById('total-payment');
const totalInterest = document.getElementById('total-interest');

// Turn amount into decimal and store it into variable
const principal = parseFloat(amount.value);
const calculatedInterest = parseFloat(interest.value) /100 / 12;
const calculatedPayment =  parseFloat(years.value) * 12;

// Compute monthly payments
const x = Math.pow(1 + calculatedInterest, calculatedPayment);
const monthly = (principal * x * calculatedInterest)/(x-1);


// Check if value is finite

if(isFinite(monthly)){
	monthlyPayment.value = monthly.toFixed(2);
	totalPayment.value = (monthly * calculatedPayment).toFixed(2);
	totalInterest.value = ((monthly * calculatedPayment) - principal).toFixed(2);

} else{
	showError("Please check your numbers")
}

e.preventDefault();
}

// Function to show error
function showError(error){
	// create div
	const errorDiv = document.createElement('div');

	// Get card and heading in order to add new div to DOM. Parent element
	const card = document.querySelector('.card');
	const heading = document.querySelector('.heading');


	// Give div a class name
	errorDiv.className = 'alert alert-danger';

	// Create text and append div
	errorDiv.appendChild(document.createTextNode(error));

	// Insert error above heading. Insert above will take in the parent element which is the card in this case and for the parameters
	// It will take in the element you want to put in and the element you want to put it before, in this case errorDiv and the heading

	card.insertBefore(errorDiv, heading);

	// Clear error after 3 seconds

	setTimeout(clearError, 3000);

}


// Create clear error
function clearError(){
	document.querySelector('.alert').remove();
}
        
    </script>





        
        <?php include 'auth_footer.php'; ?>	  