<?php
if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    echo "<script>window.location.href = '/Agent/agent-login'</script>";
    exit;
}
?>
<div class="container" style="margin-bottom: 105px;">
  <h3 class="">New Payment</h3>
  <div style="display: flex; gap: 20px; flex-direction: row;">
    <input class="form-control" type="text" id="acno" placeholder="Enter Account No" />
    <button class="btn btn-primary" onclick="getAccountDetails()">Next <i class="fa-solid fa-arrow-right"></i></button>
  </div>

  <!-- User Friendly Message -->
  <div id="userMessage" style="margin-top:10px; display:none; padding:10px; border-radius:5px;"></div>

  <form id="PAYMENT_RECEIVE_FORM" action="" method="post" style="display: none;">
    <input id="ACCOUNT_NUMBER" name="AA_ACNO" class="form-control" type="hidden" />

    <div>
      <label for="ACCOUNT_HOLDER_NAME">Account Holder Name: </label>
      <input id="ACCOUNT_HOLDER_NAME" class="form-control" type="text" placeholder="" readonly />
    </div>

    <div>
      <label for="INSTALLMENT_AMOUNT">Amount: </label>
      <input id="INSTALLMENT_AMOUNT" name="add_i" class="form-control" type="text" placeholder="" />
    </div>
    <input class="btn btn-primary" type="submit" value="Receive Now" style="margin-top: 20px;" />
  </form>
</div>

<script>
  function showMessage(msg, type = "success") {
    let box = document.getElementById("userMessage");
    box.style.display = "block";
    box.innerText = msg;

    if (type === "success") {
      box.style.background = "#d4edda";
      box.style.color = "#155724";
      box.style.border = "1px solid #c3e6cb";
    } else {
      box.style.background = "#f8d7da";
      box.style.color = "#721c24";
      box.style.border = "1px solid #f5c6cb";
    }

    setTimeout(() => {
      box.style.display = "none";
    }, 4000);
  }

  function getAccountDetails() {
    let acno = document.getElementById("acno").value;

    fetch("/exe/get-loan-details/", {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: "AA_ACNO=" + encodeURIComponent(acno)
    })
      .then(res => res.json())
      .then(data => {
        console.log("Response from get-loan-details:", data);

        if (data.status === "Success") {
          document.getElementById("PAYMENT_RECEIVE_FORM").style.display = "block";
          document.getElementById("ACCOUNT_NUMBER").value = data.data[0].AA_ACNO;
          document.getElementById("ACCOUNT_HOLDER_NAME").value = data.data[0].AA_NAME;
          document.getElementById("INSTALLMENT_AMOUNT").value = data.data[0].AA_INSTALLMENT;

          showMessage("Account found: " + data.data[0].AA_NAME, "success");
        } else {
          showMessage(data.statusmsg, "error");
        }
      })
      .catch(err => {
        console.error("Fetch error in getAccountDetails:", err);
        showMessage("Something went wrong while fetching details.", "error");
      });
  }

  // Attach form submit properly
  document.getElementById("PAYMENT_RECEIVE_FORM").addEventListener("submit", function (event) {
    event.preventDefault();
    var XHR = new XMLHttpRequest();
    var FD = new FormData(this);

    console.log("Sending FormData to /exe/receive_amount/:", Object.fromEntries(FD.entries()));

    XHR.addEventListener("load", function (event) {
      try {
        var obj = JSON.parse(event.target.responseText);
        console.log("Response from receive_amount:", obj);

        showMessage(obj.statusmsg, obj.status === "Success" ? "success" : "error");

        if (obj.status === "Success") {
          setTimeout(() => window.history.back(), 2000);
        }
      } catch (e) {
        console.error("Error parsing JSON response:", e, event.target.responseText);
        showMessage("Invalid response from server.", "error");
      }
    });

    XHR.addEventListener("error", function () {
      console.error("XHR request failed");
      showMessage("Ooops!! Something went wrong.", "error");
    });

    XHR.open("POST", "/exe/receive_amount/");
    XHR.send(FD);
  });
</script>
