<% if (user.account_type === "client") { %>

<div class="modal" id="payment-modal">
  <div class="modal-backdrop"></div>
  <div class="modal-content">
    <div class="content">
      <h3 style="color : var(--accent-clr-light)">Payment</h3>

      <form class="form">

        <div class="form-element-wrapper">
          <div class="form-element">
            <label for="service-amount">Service tax</label>
            <input type="number" id="service-amount" disabled />
          </div>
        </div>

        <div class="form-element-wrapper">
          <div class="form-element">
            <label for="pay-amount">Amount</label>
            <input type="number" id="pay-amount" disabled />
          </div>
        </div>

        <div class="form-element-wrapper">
          <div class="form-element">
            <label for="bill-amount">Total bill amount</label>
            <input type="number" min="5" id="bill-amount" disabled />
          </div>
        </div>

        <button class="btn" type="submit">Pay</button>
      </form>
    </div>
  </div>
</div>

<style>
  .payments .status {
    padding: 0.5rem;
    border-radius: 100px;
    text-transform: capitalize;
  }

  .payments .status.pending,
  .payments .status.failed {
    background-color: orangered;
  }

  .payments .status.success {
    background-color: rgb(0, 86, 0);
  }
</style>


<div class="payments even-grid">
  <% if (payments) { %>

  <% for(const payment of payments) { %>
  <div class="payment card">

    <div>
      <h3 class="title" style="color: var(--accent-clr-light)">
        <a href="/app/posted-job/<%= payment.job_id %>"><%= payment.job_title %></a>
      </h3>
      <p class="desc silver one-liner"><%= payment.job_description.slice(0, 255) %></p>
    </div>

    <div class="flex-centered space-between">
      <div class="amount gold">
        $ <%= payment.amount %>
      </div>
      <div class="created_at">
        <%= payment.created_at.toLocaleString() %>
      </div>
    </div>
    <div class="flex-centered space-between mt1 line pt1">
      <div class="status <%= payment.status %>">
        <%= payment.status %>
      </div>
      <button data-contract-id="<%= payment.contract_id %>" data-amount="<%= payment.amount %>" class="payment-btn btn" <%= payment.status === "success" ? 'disabled' : '' %>>Pay Now</button>
    </div>
  </div>
  <% } %>
  <% } else { %>
  <div class="empty">Nothing to display</div>
  <% } %>

</div>

<script>
  const paymentModal = document.querySelector("#payment-modal");
  const paymentButtons = document.querySelectorAll(".payment-btn")

  if (paymentButtons) {
    paymentButtons.forEach(btn => {
      const amount = parseFloat(btn.getAttribute("data-amount"));
      const cid = parseFloat(btn.getAttribute("data-contract-id"));
      const numberField = paymentModal.querySelector("#bill-amount");

      const serviceTaxField = paymentModal.querySelector("#service-amount")
      const amountField = paymentModal.querySelector("#pay-amount")

      btn.addEventListener("click", () => {
        const billamt = billAmountCalculator(amount);

        amountField.value = amount;
        serviceTaxField.value = billamt - amount;
        numberField.value = billamt;
        paymentModal.classList.add("open");

        paymentModal.querySelector("form").addEventListener("submit", async (e) => {
          e.preventDefault();
          paymentModal.classList.remove("open");

          try {
            showLoader()
            const res = await fetch(`/api/pay-money/${cid}`, {
              method: "POST",
              headers: {
                "Content-Type": "application/json"
              },
              body: JSON.stringify({
                amount: amount,
                bill_amount: billamt
              })
            });


            if (res.status === 200) {
              hideLoader();
              showSnackBar("Payment success", "success");
              setTimeout(() => {
                window.location.reload();
              }, 300)
            } else {
              const d = await res.json();
              hideLoader();
              showSnackBar(d.message, "error");
              setTimeout(() => {
                window.location.reload();
              }, 300)
            }
          } catch (e) {
            console.log(e)
            hideLoader();
            showSnackBar("Something went wrong", "error");
          }
        })
      })
    })
  }
</script>

<% } else { %>
<div class="balance-page">
  <div class="withdraw-modal" id="withdraw-modal">
    <div class="backdrop" id="withdraw-backdrop"></div>
    <div class="content">
      <form class="form" id="withdraw-form">
        <h3>Enter the amount to withdraw</h3>
        <p class="silver italic">10% will be charged as service tax with maximum service tax being $100</p>

        <div class="form-element-wrapper">
          <div class="form-element">
            <label for="withdraw-amount">Withdraw amount</label>
            <input id="withdraw-amount" type="number" min="10" value="10" />
          </div>
        </div>

        <div class="form-element-wrapper">
          <div class="form-element">
            <label for="service-tax">Service tax amount</label>
            <input id="service-tax" type="number" value="1" disabled />
          </div>
        </div>

        <div class="form-element-wrapper">
          <div class="form-element">
            <label for="actual-amount">Total </label>
            <input id="real-amount" type="number" value="9" disabled />
          </div>
        </div>


        <button class="btn" type="submit">Withdraw</button>
      </form>
    </div>
  </div>
  <div class="balance">
    <div class="text">Your balance is $<span id="doc-balance"><%= balance  %></span></div>
    <button class="btn" id="withdraw-modal-opener">Get Paid</button>
  </div>
  <div class="balance-hint">
    Note : You cannot withdraw money if your balance is less than $10
  </div>
</div>

<script>
  const docBalance = document.querySelector("#doc-balance");
  const withdrawBackdrop = document.querySelector("#withdraw-backdrop");
  const withdrawModal = document.querySelector("#withdraw-modal");
  const withdrawModalButton = document.querySelector("#withdraw-modal-opener");
  const withdrawAmountField = document.querySelector("#withdraw-amount");


  withdrawAmountField.addEventListener("input", (e) => {
    const value = withdrawAmountField.value;
    let serviceTax = ((value / 100) * 10).toFixed(2);
    if (serviceTax > 100) serviceTax = 100;

    withdrawModal.querySelector("#real-amount").value = value - serviceTax;
    withdrawModal.querySelector("#service-tax").value = serviceTax;
  })

  if (withdrawModal) {
    withdrawModal.querySelector("#withdraw-form").addEventListener("submit", async (e) => {
      e.preventDefault();

      const value = withdrawAmountField.value;
      let serviceTax = ((value / 100) * 10).toFixed(2);
      if (serviceTax > 100) serviceTax = 100;


      const approved = confirm("Please confirm to continue");

      if (approved) {
        withdrawModal.classList.remove("open");
        try {
          showLoader();
          const res = await fetch("/api/withdraw-money", {
            method: "POST",
            headers: {
              "Content-Type": "application/json"
            },
            body: JSON.stringify({
              amount: value,
            })
          });
          if (res.status === 200) {
            docBalance.textContent = parseFloat(docBalance.textContent) - value;
            hideLoader();
            showSnackBar("Withdraw processed successfully", "success");
          } else {
            const d = await res.json()
            hideLoader();
            showSnackBar(d.message, "error");
          }

        } catch (e) {
          console.log(e)
          hideLoader();
          showSnackBar("Something went wrong", "error");
        }
      }
    })
  }

  if (withdrawModalButton)
    withdrawModalButton.addEventListener("click", () => {
      withdrawModal.classList.add("open");

    })
  if (withdrawBackdrop)
    withdrawBackdrop.addEventListener("click", () => {
      withdrawModal.classList.remove("open");
    })
</script>
<% } %>