<?php

include("includes/header.php"); 
include("includes/sidebar.php");

$reg_date = strtotime($user[0]['date_registered']);
$now = strtotime("now");

$diffInSeconds =  $now - $reg_date;
$diffInDays = $diffInSeconds / (60 * 60 * 24);



if(isset($_POST['apply'])){
    
if (!isset($_POST['csrf_token']) || !$csrf->validateToken($_POST['csrf_token'])) {
        die("CSRF token validation failed!");
    }

$amount = $db_handle->sanitize($_POST['amount']);
//$repayment_date = $db_handle->sanitize($_POST['repayment_date']);
$repayment_date = "";
$interest = $db_handle->sanitize($_POST['interest']);
$repayment = $db_handle->sanitize($_POST['repayment']);

$current_loan = $db_handle->runBaseQuery("SELECT * FROM loan_application WHERE userID = $id ORDER BY id DESC LIMIT 1");


$date = date("Y-m-d h:i:sa");

if($current_loan && $current_loan[0]['status'] == 0){
    
    $msg = "<div class='alert alert-danger'>Sorry, you currently have a pending loan, please be patient why we process it.</div>";
    
}else{

$insert = $db_handle->insertRecord("INSERT INTO loan_application(userID,amount,interest,repayment,repayment_date,date) 
    VALUES (?,?,?,?,?,?)","isssss",array($id,$amount,$interest,$repayment,$repayment_date,$date));

    if($insert){

        $msg = "<div class='alert alert-success'>Loan Application Successful, you will be notified shortly</div>";
    }

}

}
 ?>
 <div class="main-content app-content">
<div class="container">
                            
                            <!--Modal: order-modal-->
                            <div class="d-flex justify-content-between align-items-center mb-3 p-4 rounded-4 shadow-sm text-white" 
     style="background: #C81D25;">
  
  <div>
    <h5 class="fw-bold mb-1 text-light">Apply for Loan</h5>
    <p class="mb-0 opacity-75">Apply for a loan quickly and securely with flexible options.</p>
  </div>

  <div>
    <i class="bi bi-piggy-bank-fill" style="font-size: 2.5rem;"></i>
  </div>
</div>
                           
                                
    <div class="row settings mt-3">
       
        <div class="col-xl-12">
            <div id="settingmenuContent">
                
                <?php
                if($diffInDays < 90){ ?>
                
                 <div id="editprofile">
                                     <?php echo $msg; ?>
                    <div class="row mb-5">
                        <div class="col-12">
                            <div class="card border-0 box-shadow">
                                <div class="card-body pb-0">
                                    <div class="d-flex align-items-center mb-3">
                                        
                                        
                                        <p>You are currently not eligible to apply for a loan. Please remain active for at least 3 months to become eligible</p>

                                    </div>
                                    
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                    
                    
                <?php
                
                }else{?>
                    
                    
                
                
                                <div id="editprofile">
                                     <?php echo $msg; ?>
                    <div class="row mb-5">
                        <div class="col-12">
                            <div class="card border-0 box-shadow">
                                <div class="card-body pb-0">
                                    <div class="d-flex align-items-center mb-3">
                                        <h5 class="text-uppercase text-red">Apply for a Loan</h5>

                                    </div>
                                    <form method="POST"
                                        action=""
                                        enctype="multipart/form-data">
                                       
                                        <?php echo $csrf->csrfInput(); ?>                                        <div class="row">
                                            <div class="mb-3">
                                                <label class="form-label">Amount<span
                                                        class="text-danger"> * </span></label>
                                                <input type="number" class="form-control modern-input" name="amount" id="amount"
                                                    required >

                                            </div>
                                          
                                            <div class="mb-3">
                                                <label class="form-label"
                                                    for="mobile">Interest<span
                                                        class="text-danger"> * </span></label>
                                                <input type="text" class="form-control modern-input" name="interest" id="estimated_interest" required readonly>

                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label"
                                                    for="mobile">To Repay<span
                                                        class="text-danger"> * </span></label>
                                                <input type="text" class="form-control modern-input" name="repayment" id="repayment"
                                                    
                                                     required readonly>

                                            </div>
                                            
                                                                                <div class="form-group text-end">
                                                                                            <br>
                                                <button
                                                    class="btn btn-red modern-btn "
                                                     type="submit" name="apply" value="1" >Apply For Loan</button>
                                             </div>
                                      
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                    </div>
                  
                
                <?php
                }
                ?>
                                
                               

            </div>
        </div>
    </div>
    
    
                        </div>
                    </div>
               
 <?php include("includes/footer.php"); ?>
 <script>
function formatCurrency(num) {
  return "₦" + Number(num).toLocaleString();
}

function calculateDepositDetails() {
  
  let amount = parseFloat(document.getElementById("amount").value);
 
  
  let rate = 20;

 
  let interest = 0;
  let total = 0;

 
  if (amount && rate) {
    interest = (amount * (rate/100));
    total = amount + interest;
    document.getElementById("estimated_interest").value = interest.toFixed(2);
    document.getElementById("repayment").value = total.toFixed(2);
  }

 
}



document.getElementById("amount").addEventListener("input", calculateDepositDetails);

window.onload = calculateDepositDetails;
</script>



<script>
$(document).ready(function () {
  $("#fixedDepositForm").on("submit", function (e) {
    e.preventDefault(); // Prevent page reload

    $.ajax({
      url: "process_fixeddeposit.php", // PHP handler
      type: "POST",
      data: $(this).serialize(), // Send form data
      dataType: "json",
      beforeSend: function () {
        $("#responseMessage").html("<div class='text-info'>Processing...</div>");
      },
      success: function (response) {
          console.log(response)
        if (response.status === "success") {
          $("#responseMessage").html(
            "<div class='alert alert-success'>" + response.message + "</div>"
          );
          $("#fixedDepositForm")[0].reset(); // Reset form
        } else {
          $("#responseMessage").html(
            "<div class='alert alert-danger'>" + response.message + "</div>"
          );
        }
      },
      error: function () {
        $("#responseMessage").html(
          "<div class='alert alert-danger'>An error occurred. Please try again.</div>"
        );
      }
    });
  });
});
</script>

 
