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



$deposits = $db_handle->runBaseQuery("SELECT * FROM fixed_deposits  WHERE user_id = $id ORDER BY id DESC");


$fixed_deposit = $db_handle->runBaseQuery("SELECT * FROM fixed_deposits WHERE user_id = $id AND status = 'ONGOING' ORDER BY id DESC LIMIT 1");

$fixed_deposit_balance = ($fixed_deposit)? $fixed_deposit[0]['balance'] : 0;
?>


<div class="main-content app-content">
  <div class="container mt-3">
 

      <!-- Left: Form -->
      
      <?php

if(!$user[0]['fixed_deposit']){ ?>

<div class="d-flex justify-content-between align-items-center mb-3 mt-3 p-4 rounded-4 shadow-sm text-white" 
     style="background: #C81D25;">
  
  <div>
    <h5 class="fw-bold mb-1 text-light">Apply For Fixed Deposit</h5>
    <p class="mb-0 opacity-75">Grow your savings with secure and guaranteed returns.</p>
  </div>

  <div>
    <i class="bi bi-piggy-bank-fill" style="font-size: 2.5rem;"></i>
  </div>
</div>
        <div class="card border-0 shadow-sm rounded-4">
          <div class="card-body">
            <h5 class="text-uppercase mb-4 fw-bold text-danger"> Make a Fixed Deposit</h5>
            <div id="responseMessage" class="mt-2 mb-2"></div>
            <form method="POST" action="payment" id="fixedDepositForm">
              <?php echo $csrf->csrfInput(); ?>
              
              <input type="hidden" name="id" value="<?php echo $id; ?>">

              <div class="mb-3">
                <label class="form-label fw-semibold">Amount <span class="text-danger">*</span></label>
                <input type="number" class="form-control modern-input" name="amount" id="amount" placeholder="Enter deposit amount" required>
              </div>

              <div class="mb-3">
                <label class="form-label">Start Date</label>
                <input type="date" class="form-control modern-input" name="start_date" id="start_date" value="<?php echo date('Y-m-d'); ?>" required readonly>
              </div>

             <div class="mb-3">
                <label class="form-label fw-semibold">Duration <span class="text-danger">*</span></label>
                <select class="form-select modern-input" name="tenure" id="tenure" required>
                  <option value="">-- Select duration --</option>
                  
                  <option value="6">6 Months</option>
                  <option value="12">12 Months</option>
                </select>
              </div>

              <div class="mb-3">
                <label class="form-label fw-semibold">Interest Rate</label>
                <input type="text" class="form-control modern-input" id="interest_rate" name="interest_rate" value="" readonly>
              </div>

              <div class="mb-3">
                <label class="form-label">Maturity Date</label>
                <input type="text" class="form-control modern-input" id="maturity_date" name="maturity_date" readonly>
              </div>

              <div class="mb-3">
                <label class="form-label">Estimated Interest</label>
                <input type="text" class="form-control modern-input" id="estimated_interest" name="estimated_interest" readonly>
              </div>

              <div class="mb-3">
                <label class="form-label">Total at Maturity</label>
                <input type="text" class="form-control modern-input" id="total_maturity" name="total_maturity" readonly>
              </div>

              <div class="text-end">
                <button class="btn btn-danger modern-btn px-4 py-2" type="submit">Submit</button>
              </div>
            </form>
          </div>
        </div>
        
        <?php
        
}else{
 
?>

<div class="d-flex justify-content-between align-items-center mb-3 p-4 rounded-4 shadow-sm text-white" 
     style="background: #C81D25;">
  
  <div>
      <h4 class="fw-bold mb-1 text-light">Fixed Deposit</h4>
    <h5 class="fw-bold mb-1 text-light">₦<?php echo number_format($fixed_deposit_balance,2); ?></h5>
    
    <p class="mb-0 opacity-75">Unlocks on <b><?php echo $fixed_deposit[0]['maturity_date']; ?></b>.</p>
  </div>

  <div>
    <i class="bi bi-piggy-bank-fill" style="font-size: 2.5rem;"></i>
  </div>
</div>

      <!-- Right: Summary Box -->
      
      <div class="row">
            <div class="col-xl-12">
                <div class="card custom-card">
                    <div class="card-header justify-content-between border-bottom-0">
                        <div class="card-title"> Recent Fixed Deposits</div>
                        
                    </div>
                    <div class="card-body p-3">
                        <div class="table-responsive">
                            <table class="table text-nowrap table-bordered" id="TableTab">
                                <thead>
                                    <tr>
                                        <th scope="col">#</th>
                                        <th scope="col">Principal</th>
                                        <th scope="col">Current Balance</th>
                                      
                                        <th scope="col">Interest</th>
                                        <th scope="col">Start Date</th>
                                        <th scope="col">Expiring Date</th>
                                        <th scope="col">Status</th>
                                        
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                        if($deposits){
                                            $i = 1;
                                            foreach($deposits as $deposit){
                                                $userID = ($deposit['user_id']);

                                                    
                               echo "<tr>";
                                    echo '<td class="fw-medium">'.$i.'</td>';
                                  
                                      echo '<td class="fw-medium">NGN'.number_format($deposit['principal']).'</td>';
                                      echo '<td class="fw-medium">NGN'.number_format($deposit['balance']).'</td>';
                                        echo '<td> <span class="fw-medium">'.$deposit['interest_rate'].'%</span></td>';
                                       
                                        
                                        echo '<td> <span class="">'.$deposit['start_date'].'</span> </td>';
                                        
                                        echo '<td> <span class="">'.$deposit['maturity_date'].'</span> </td>';
                                        
                                        echo '<td> <span class="">'.$deposit['status'].'</span> </td>';

                                     
                                       
                                    echo '</tr>';

                                    $i++;
                                    
                                    }


                                }

                                ?>




                                   
                                    
                                   
                                </tbody>
                            </table>
                        </div>
                    </div>
                   
                </div>
            </div>
        </div>
      
      <?php
}
?>
    
  </div>
</div>

<!-- jsPDF -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

<script>
function formatCurrency(num) {
  return "₦" + Number(num).toLocaleString();
}

function calculateDepositDetails() {
  let tenure = parseInt(document.getElementById("tenure").value);
  let startDate = document.getElementById("start_date").value;
  let amount = parseFloat(document.getElementById("amount").value);


 /* if (tenure === 3) rate = 8;
  if (tenure === 6) rate = 10;
  if (tenure === 12) rate = 12;*/
  
  let rate = 20;
  //let tenure = 12;

  document.getElementById("interest_rate").value = rate ? rate + "%" : "";

  let maturityDate = "-";
  let interest = 0;
  let total = 0;

  if (tenure && startDate) {
    let start = new Date(startDate);
    start.setMonth(start.getMonth() + tenure);
    maturityDate = start.toISOString().split("T")[0];
    document.getElementById("maturity_date").value = maturityDate;
  }

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

 
}


document.getElementById("tenure").addEventListener("change", calculateDepositDetails);
//document.getElementById("start_date").addEventListener("change", calculateDepositDetails);
document.getElementById("amount").addEventListener("input", calculateDepositDetails);

window.onload = calculateDepositDetails;
</script>

<?php include("includes/footer.php"); ?>

<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) {
         $("#csrf_token").val(response.token)
        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>

