<%
  const userCanManage =
    typeof canManage !== "undefined" &&
    canManage === true;

  // ==================================================
  // SAFE DYNAMIC CURRENCY FORMATTER
  // ==================================================

  const company =
    typeof companySettings !== "undefined" &&
    companySettings
      ? companySettings
      : {};

  const displayMoney =
    typeof formatMoney === "function"
      ? formatMoney
      : function (value) {
          const convertedValue = Number(value);

          const safeValue =
            Number.isFinite(convertedValue)
              ? convertedValue
              : 0;

          const formattedValue =
            new Intl.NumberFormat(
              "en-US",
              {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
              }
            ).format(safeValue);

          const currency =
            company.currency_symbol ||
            company.currency_code ||
            "";

          return currency
            ? currency + " " + formattedValue
            : formattedValue;
        };

  // ==================================================
  // SAFE DATA VARIABLES
  // ==================================================

  const paymentTotals =
    typeof totals !== "undefined" && totals
      ? totals
      : {};

  const paymentList =
    typeof payments !== "undefined" &&
    Array.isArray(payments)
      ? payments
      : [];

  const projectSummaryList =
    typeof projectSummaries !== "undefined" &&
    Array.isArray(projectSummaries)
      ? projectSummaries
      : [];

  // ==================================================
  // PAYMENT STATUS CLASS
  // ==================================================

  const getPaymentStatusClass = (status) => {
    switch (status) {
      case "Paid":
        return "status-paid";

      case "Partially Paid":
        return "status-partially-paid";

      case "Overpaid":
        return "status-overpaid";

      default:
        return "status-unpaid";
    }
  };
%>

<!DOCTYPE html>
<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta
    name="viewport"
    content="width=device-width, initial-scale=1.0"
  >

  <title>Project Payments</title>

  <link rel="stylesheet" href="/css/style.css">

  <style>

    /* ==========================================
       MAIN PAGE
    ========================================== */

    .payments-page {
      max-width: 1400px;
      margin: 35px auto;
      padding: 20px;
    }

    /* ==========================================
       PAGE HEADER
    ========================================== */

    .payments-page-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 20px;
      margin-bottom: 25px;
    }

    .payments-page-header h1 {
      margin: 15px 0 0;
      color: #1f2937;
    }

    .payment-page-actions {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .add-payment-button {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      padding: 11px 18px;
      border-radius: 6px;
      background-color: #2563eb;
      color: #ffffff;
      font-weight: 600;
      text-decoration: none;
    }

    .add-payment-button:hover {
      background-color: #1d4ed8;
    }

    /* ==========================================
       PAYMENT SUMMARY CARDS
    ========================================== */

    .payment-summary-grid {
      display: grid;
      grid-template-columns: repeat(6, minmax(0, 1fr));
      gap: 15px;
      margin-bottom: 30px;
    }

    .payment-summary-card {
      min-width: 0;
      padding: 18px;
      border-left: 5px solid #2563eb;
      border-radius: 8px;
      background-color: #ffffff;
      box-shadow: 0 3px 12px rgba(0, 0, 0, 0.07);
    }

    .payment-summary-card span {
      display: block;
      margin-bottom: 9px;
      color: #64748b;
      font-size: 14px;
      font-weight: 600;
    }

    .payment-summary-card strong {
      display: block;
      color: #0f172a;
      font-size: 18px;
      overflow-wrap: anywhere;
    }

    .payment-summary-card.total-card {
      border-left-color: #16a34a;
    }

    .payment-summary-card.advance-card {
      border-left-color: #7c3aed;
    }

    .payment-summary-card.progress-card {
      border-left-color: #0284c7;
    }

    .payment-summary-card.final-card {
      border-left-color: #dc2626;
    }

    .payment-summary-card.retention-card {
      border-left-color: #f59e0b;
    }

    /* ==========================================
       SECTION TITLES
    ========================================== */

    .payment-section-title {
      margin: 0 0 15px;
      color: #1f2937;
      font-size: 22px;
    }

    /* ==========================================
       PROJECT PAYMENT SUMMARY
    ========================================== */

    .project-payment-summary-section {
      margin-bottom: 35px;
    }

    .project-summary-table-container {
      overflow-x: auto;
      border-radius: 9px;
      background-color: #ffffff;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
    }

    .project-summary-table {
      width: 100%;
      border-collapse: collapse;
    }

    .project-summary-table th,
    .project-summary-table td {
      padding: 14px;
      border-bottom: 1px solid #e5e7eb;
      text-align: left;
      vertical-align: middle;
      white-space: nowrap;
    }

    .project-summary-table th {
      background-color: #334155;
      color: #ffffff;
      font-weight: 700;
    }

    .project-summary-table tbody tr:hover {
      background-color: #f8fafc;
    }

    .project-summary-table tbody tr:last-child td {
      border-bottom: none;
    }

    .project-name-cell {
      color: #1e293b;
      font-weight: 700;
    }

    .project-contract-amount {
      color: #1e293b;
      font-weight: 700;
    }

    .project-received-amount {
      color: #15803d;
      font-weight: 700;
    }

    .project-remaining-amount {
      color: #c2410c;
      font-weight: 700;
    }

    .project-overpayment-amount {
      color: #7c3aed;
      font-weight: 700;
    }

    /* ==========================================
       PROJECT PAYMENT STATUS
    ========================================== */

    .project-payment-status {
      display: inline-block;
      padding: 6px 11px;
      border-radius: 20px;
      font-size: 13px;
      font-weight: 700;
    }

    .status-unpaid {
      background-color: #fee2e2;
      color: #b91c1c;
    }

    .status-partially-paid {
      background-color: #fef3c7;
      color: #b45309;
    }

    .status-paid {
      background-color: #dcfce7;
      color: #15803d;
    }

    .status-overpaid {
      background-color: #ede9fe;
      color: #6d28d9;
    }

    /* ==========================================
       PAYMENTS TABLE
    ========================================== */

    .payment-records-section {
      margin-bottom: 25px;
    }

    .payments-table-container {
      overflow-x: auto;
      border-radius: 9px;
      background-color: #ffffff;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
    }

    .payments-table {
      width: 100%;
      border-collapse: collapse;
    }

    .payments-table th,
    .payments-table td {
      padding: 14px;
      border-bottom: 1px solid #e5e7eb;
      text-align: left;
      vertical-align: middle;
      white-space: nowrap;
    }

    .payments-table th {
      background-color: #1f2937;
      color: #ffffff;
      font-weight: 700;
    }

    .payments-table tbody tr:hover {
      background-color: #f8fafc;
    }

    .payments-table tbody tr:last-child td {
      border-bottom: none;
    }

    /* ==========================================
       PAYMENT INFORMATION
    ========================================== */

    .payment-amount {
      color: #15803d;
      font-weight: 700;
    }

    .payment-type {
      display: inline-block;
      padding: 5px 9px;
      border-radius: 20px;
      background-color: #e0f2fe;
      color: #0369a1;
      font-size: 13px;
      font-weight: 600;
    }

    /* ==========================================
       EDIT AND DELETE BUTTONS
    ========================================== */

    .payment-actions {
      display: flex;
      align-items: center;
      gap: 8px;
      white-space: nowrap;
    }

    .payment-edit-button,
    .payment-delete-button {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      min-width: 68px;
      height: 38px;
      padding: 0 14px;
      border: none;
      border-radius: 6px;
      box-sizing: border-box;
      color: #ffffff;
      font-size: 14px;
      font-weight: 600;
      line-height: 1;
      text-decoration: none;
      cursor: pointer;
    }

    .payment-edit-button {
      background-color: #64748b;
    }

    .payment-edit-button:hover {
      background-color: #475569;
    }

    .payment-delete-form {
      display: inline-flex;
      width: auto;
      min-width: 0;
      margin: 0;
      padding: 0;
      border: none;
      border-radius: 0;
      background: transparent;
      box-shadow: none;
    }

    .payment-delete-button {
      background-color: #dc2626;
    }

    .payment-delete-button:hover {
      background-color: #b91c1c;
    }

    /* ==========================================
       EMPTY MESSAGE
    ========================================== */

    .empty-payment-message {
      padding: 35px;
      color: #64748b;
      text-align: center;
    }

    /* ==========================================
       RESPONSIVE DESIGN
    ========================================== */

    @media (max-width: 1150px) {

      .payment-summary-grid {
        grid-template-columns: repeat(3, minmax(0, 1fr));
      }

    }

    @media (max-width: 800px) {

      .payment-summary-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
      }

    }

    @media (max-width: 650px) {

      .payments-page {
        margin: 20px auto;
        padding: 15px;
      }

      .payments-page-header {
        align-items: flex-start;
        flex-direction: column;
      }

      .payment-summary-grid {
        grid-template-columns: 1fr;
      }

      .payment-page-actions {
        width: 100%;
      }

      .add-payment-button {
        width: 100%;
        box-sizing: border-box;
      }

      .payment-section-title {
        font-size: 19px;
      }

    }

  </style>

</head>

<body>

  <main class="payments-page">

    <!-- ========================================
         PAGE HEADER
    ========================================= -->

    <div class="payments-page-header">

      <div>

        <a
          href="/"
          class="back-button"
        >
          ← Back to Dashboard
        </a>

        <h1>Project Payments</h1>

      </div>

      <div class="payment-page-actions">

        <a
          href="/project-payments/create"
          class="add-payment-button"
        >
          + Add Payment
        </a>

      </div>

    </div>

    <!-- ========================================
         GENERAL PAYMENT SUMMARY
    ========================================= -->

    <section class="payment-summary-grid">

      <!-- Payment Records -->

      <div class="payment-summary-card">

        <span>
          Payment Records
        </span>

        <strong>
          <%=
            paymentTotals.total_records ??
            paymentList.length
          %>
        </strong>

      </div>

      <!-- Total Received -->

      <div class="payment-summary-card total-card">

        <span>
          Total Received
        </span>

        <strong>
          <%= displayMoney(paymentTotals.total_received) %>
        </strong>

      </div>

      <!-- Advance Payments -->

      <div class="payment-summary-card advance-card">

        <span>
          Advance Payments
        </span>

        <strong>
          <%= displayMoney(paymentTotals.advance_payments) %>
        </strong>

      </div>

      <!-- Progress Payments -->

      <div class="payment-summary-card progress-card">

        <span>
          Progress Payments
        </span>

        <strong>
          <%= displayMoney(paymentTotals.progress_payments) %>
        </strong>

      </div>

      <!-- Final Payments -->

      <div class="payment-summary-card final-card">

        <span>
          Final Payments
        </span>

        <strong>
          <%= displayMoney(paymentTotals.final_payments) %>
        </strong>

      </div>

      <!-- Retention Released -->

      <div class="payment-summary-card retention-card">

        <span>
          Retention Released
        </span>

        <strong>
          <%= displayMoney(paymentTotals.retention_payments) %>
        </strong>

      </div>

    </section>

    <!-- ========================================
         PROJECT PAYMENT SUMMARY
    ========================================= -->

    <section class="project-payment-summary-section">

      <h2 class="payment-section-title">
        Project Payment Summary
      </h2>

      <div class="project-summary-table-container">

        <% if (projectSummaryList.length === 0) { %>

          <div class="empty-payment-message">
            No projects are available for payment summary.
          </div>

        <% } else { %>

          <table class="project-summary-table">

            <thead>

              <tr>
                <th>Project</th>
                <th>Contract Amount</th>
                <th>Total Received</th>
                <th>Remaining</th>
                <th>Overpayment</th>
                <th>Status</th>
              </tr>

            </thead>

            <tbody>

              <% projectSummaryList.forEach((project) => { %>

                <tr>

                  <td class="project-name-cell">
                    <%= project.project_name %>
                  </td>

                  <td class="project-contract-amount">
                    <%= displayMoney(project.awarded_amount) %>
                  </td>

                  <td class="project-received-amount">
                    <%= displayMoney(project.total_received) %>
                  </td>

                  <td class="project-remaining-amount">
                    <%= displayMoney(project.remaining_amount) %>
                  </td>

                  <td class="project-overpayment-amount">
                    <%= displayMoney(project.overpayment_amount) %>
                  </td>

                  <td>

                    <span
                      class="
                        project-payment-status
                        <%= getPaymentStatusClass(
                          project.payment_status
                        ) %>
                      "
                    >
                      <%= project.payment_status %>
                    </span>

                  </td>

                </tr>

              <% }); %>

            </tbody>

          </table>

        <% } %>

      </div>

    </section>

    <!-- ========================================
         PAYMENT RECORDS
    ========================================= -->

    <section class="payment-records-section">

      <h2 class="payment-section-title">
        Payment Records
      </h2>

      <div class="payments-table-container">

        <% if (paymentList.length === 0) { %>

          <div class="empty-payment-message">
            No project payments have been recorded yet.
          </div>

        <% } else { %>

          <table class="payments-table">

            <thead>

              <tr>
                <th>ID</th>
                <th>Project</th>
                <th>Payment Type</th>
                <th>Amount</th>
                <th>Payment Date</th>
                <th>Method</th>
                <th>Reference</th>
                <th>Remark</th>
                <th>Actions</th>
              </tr>

            </thead>

            <tbody>

              <% paymentList.forEach((payment) => { %>

                <tr>

                  <td>
                    <%= payment.id %>
                  </td>

                  <td>
                    <%= payment.project_name %>
                  </td>

                  <td>

                    <span class="payment-type">
                      <%= payment.payment_type %>
                    </span>

                  </td>

                  <td class="payment-amount">
                    <%= displayMoney(payment.amount) %>
                  </td>

                  <td>
                    <%= payment.payment_date || "-" %>
                  </td>

                  <td>
                    <%= payment.payment_method || "-" %>
                  </td>

                  <td>
                    <%= payment.reference_number || "-" %>
                  </td>

                  <td>
                    <%= payment.remark || "-" %>
                  </td>

                  <td>

                    <div class="payment-actions">

                      <a
                        href="/project-payments/<%= payment.id %>/edit"
                        class="payment-edit-button"
                      >
                        Edit
                      </a>

                      <form
                        action="/project-payments/<%= payment.id %>/delete"
                        method="POST"
                        class="payment-delete-form"
                        onsubmit="return confirm('Are you sure you want to delete this project payment?');"
                      >

                        <button
                          type="submit"
                          class="payment-delete-button"
                        >
                          Delete
                        </button>

                      </form>

                    </div>

                  </td>

                </tr>

              <% }); %>

            </tbody>

          </table>

        <% } %>

      </div>

    </section>

  </main>

</body>

</html>