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

<head>
  <meta charset="UTF-8" />
  <title>Payment Receipt - Safe Step Properties Limited</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <style>
    :root {
      --brand-blue: #125db8;
      --brand-blue-dark: #07356f;
      --brand-blue-soft: #eaf3ff;
      --brand-green: #3baa15;
      --brand-green-dark: #257b0b;
      --ink: #0b1b33;
      --muted: #5d6a7c;
      --line: #dbe4ef;
      --surface: #f6f9fc;
      --surface-strong: #eef5fb;
      --white: #ffffff;
      --footer: #06172d;
      --shadow: 0 18px 50px rgba(7, 53, 111, 0.12);
      --shadow-soft: 0 10px 28px rgba(7, 53, 111, 0.08);
      --radius: 8px;
      --container: 1180px;
    }

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: "Poppins", "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      background:
        radial-gradient(circle at top left, rgba(59, 170, 21, 0.10), transparent 24%),
        radial-gradient(circle at bottom right, rgba(18, 93, 184, 0.07), transparent 26%),
        var(--surface);
      padding: 20px;
      color: var(--ink);
    }

    .page-wrapper {
      max-width: 920px;
      margin: 0 auto;
      position: relative;
    }

    .print-controls {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
      margin-bottom: 12px;
    }

    .btn {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      border: 1px solid var(--brand-blue);
      background: linear-gradient(135deg, var(--brand-blue), var(--brand-green));
      color: #ffffff;
      padding: 10px 14px;
      font-size: 12px;
      font-weight: 700;
      text-transform: uppercase;
      letter-spacing: .12em;
      border-radius: 10px;
      cursor: pointer;
      transition: all .15s ease;
      user-select: none;
      box-shadow: 0 10px 18px rgba(18, 93, 184, 0.15);
    }

    .btn.secondary {
      background: #ffffff;
      color: var(--brand-blue);
      border-color: rgba(15, 23, 42, .12);
      box-shadow: none;
    }

    .btn:disabled {
      opacity: .6;
      cursor: not-allowed;
    }

    .btn:hover:not(:disabled) {
      transform: translateY(-1px);
    }

    .receipt-container {
      background: #ffffff;
      border: 1px solid rgba(15, 23, 42, .08);
      border-radius: 22px;
      padding: 24px 24px;
      box-shadow: 0 14px 34px rgba(2, 8, 23, 0.06);
      overflow: hidden;
      position: relative;
    }

    .receipt-container::before {
      content: "";
      position: absolute;
      inset: 0;
      pointer-events: none;
      background:
        radial-gradient(circle at top right, rgba(59, 170, 21, 0.05), transparent 18%),
        radial-gradient(circle at bottom left, rgba(18, 93, 184, 0.04), transparent 18%);
    }

    .receipt-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      gap: 16px;
      padding-bottom: 16px;
      margin-bottom: 18px;
      border-bottom: 1px solid rgba(15, 23, 42, .08);
      position: relative;
      z-index: 1;
    }

    .company-block {
      display: flex;
      align-items: flex-start;
      gap: 14px;
      min-width: 0;
    }

    .company-logo {
      width: 84px;
      height: auto;
      object-fit: contain;
      flex: 0 0 auto;
      display: block;
    }

    .company-text {
      min-width: 0;
    }

    .company-text h1 {
      font-size: 18px;
      font-weight: 800;
      letter-spacing: 0.14em;
      text-transform: uppercase;
      color: var(--ink);
      margin-bottom: 4px;
      line-height: 1.25;
    }

    .company-text p {
      font-size: 11px;
      line-height: 1.6;
      color: rgba(15, 23, 42, .72);
    }

    .company-text a {
      color: var(--brand-blue);
      text-decoration: none;
      font-weight: 700;
    }

    .receipt-meta-top {
      text-align: right;
      font-size: 11px;
      color: rgba(15, 23, 42, .75);
      min-width: 220px;
    }

    .receipt-meta-top h2 {
      font-size: 12px;
      text-transform: uppercase;
      letter-spacing: 0.18em;
      color: var(--brand-blue);
      margin-bottom: 8px;
      font-weight: 800;
    }

    .receipt-meta-top span {
      display: block;
      line-height: 1.5;
    }

    .receipt-number {
      font-weight: 800;
      font-size: 13px;
      color: var(--brand-blue);
    }

    .section {
      margin-bottom: 16px;
      position: relative;
      z-index: 1;
    }

    .section-title {
      font-size: 11px;
      text-transform: uppercase;
      letter-spacing: 0.16em;
      color: rgba(15, 23, 42, .55);
      margin-bottom: 8px;
      font-weight: 800;
    }

    .info-grid {
      display: flex;
      gap: 18px;
      font-size: 12px;
    }

    .info-card {
      flex: 1;
      border: 1px solid rgba(15, 23, 42, .08);
      background: #ffffff;
      border-radius: 16px;
      padding: 12px 12px;
    }

    .kv {
      width: 100%;
      border-collapse: collapse;
    }

    .kv td {
      padding: 4px 0;
      vertical-align: top;
    }

    .kv td.label {
      width: 130px;
      color: rgba(15, 23, 42, .55);
      font-size: 11px;
      letter-spacing: .02em;
      padding-right: 10px;
      white-space: nowrap;
    }

    .kv td.value {
      font-weight: 700;
      color: #0f172a;
      word-break: break-word;
    }

    .summary-table {
      width: 100%;
      border-collapse: collapse;
      font-size: 12px;
      border: 1px solid rgba(15, 23, 42, .08);
      border-radius: 16px;
      overflow: hidden;
      background: #fff;
    }

    .summary-table th,
    .summary-table td {
      border-bottom: 1px solid rgba(15, 23, 42, .06);
      padding: 10px 10px;
      text-align: left;
    }

    .summary-table th {
      background: #eaf3ff;
      font-weight: 800;
      color: rgba(15, 23, 42, .65);
      text-transform: uppercase;
      letter-spacing: .12em;
      font-size: 10px;
    }

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

    .amount {
      text-align: right;
      white-space: nowrap;
      font-variant-numeric: tabular-nums;
    }

    .amount.positive {
      color: var(--brand-green-dark);
      font-weight: 800;
    }

    .amount.negative {
      color: #b42318;
      font-weight: 800;
    }

    .plot-code {
      font-weight: 800;
      color: var(--brand-blue);
    }

    .client-code {
      font-weight: 800;
      color: var(--brand-blue);
    }

    .status-badge {
      display: inline-block;
      padding: 4px 10px;
      border-radius: 999px;
      font-size: 10px;
      font-weight: 800;
      text-transform: uppercase;
      letter-spacing: .12em;
      border: 1px solid transparent;
      white-space: nowrap;
    }

    .status-active {
      background: rgba(22, 163, 74, .10);
      color: #166534;
      border-color: rgba(22, 163, 74, .25);
    }

    .status-pending {
      background: rgba(245, 158, 11, .12);
      color: #b54708;
      border-color: rgba(245, 158, 11, .25);
    }

    .receipt-footer {
      border-top: 1px solid rgba(15, 23, 42, .08);
      padding-top: 10px;
      margin-top: 10px;
      font-size: 10px;
      color: rgba(15, 23, 42, .60);
      line-height: 1.6;
      position: relative;
      z-index: 1;
    }

    .signature-block {
      margin-top: 18px;
      font-size: 11px;
      position: relative;
      z-index: 1;
    }

    .signature-row {
      display: flex;
      gap: 26px;
    }

    .signature-col {
      flex: 1;
    }

    .signature-line {
      margin-top: 26px;
      border-top: 1px solid rgba(15, 23, 42, .35);
      width: 72%;
    }

    .signature-label {
      margin-top: 6px;
      color: rgba(15, 23, 42, .75);
      font-weight: 800;
      text-transform: uppercase;
      letter-spacing: .10em;
      font-size: 10px;
    }

    @media print {
      body {
        background: #ffffff;
        padding: 0;
      }

      .print-controls {
        display: none;
      }

      .page-wrapper {
        margin: 0;
        max-width: none;
      }

      .receipt-container {
        border-radius: 0;
        border: none;
        box-shadow: none;
      }
    }

    @media (max-width: 720px) {
      .receipt-header {
        flex-direction: column;
        align-items: stretch;
      }

      .receipt-meta-top {
        text-align: left;
        min-width: 0;
      }

      .info-grid {
        flex-direction: column;
      }

      .company-block {
        flex-direction: column;
      }

      .company-logo {
        width: 72px;
      }
    }
  </style>
</head>

<body>
  <div class="page-wrapper">
    <div class="print-controls">
      <button class="btn secondary" onclick="window.print()">
        <i class="fas fa-print"></i> Print
      </button>
      <button class="btn" onclick="window.print()">
        <i class="fas fa-file-pdf"></i> Download PDF
      </button>
      <button class="btn" id="btn-send-email" onclick="sendReceiptEmail()">
        <i class="fas fa-envelope"></i> Send via Email
      </button>
    </div>

    <div class="receipt-container" id="receipt">
      <div class="receipt-header">
        <div class="company-block">
          <img src="logo-safe-step.png" alt="Safe Step Properties Limited" class="company-logo" />

          <div class="company-text">
            <h1>Safe Step Properties Limited</h1>
            <p style="font-weight:700; color:var(--ink);">Sales, Investment &amp; Property Management</p>
            <p>Suite 02, Jahi Mall, Valentine Nwabuaeze Crescent, Jahi, FCT Abuja.</p>
            <p>
              Contact: +234 814 241 1113<br />
              WhatsApp: +234 704 646 6653<br />
              Email: <a href="mailto:info@safestepproperties.com">info@safestepproperties.com</a>
            </p>
          </div>
        </div>

        <div class="receipt-meta-top">
          <h2>Payment Receipt</h2>
          <span>Invoice / Receipt No:</span>
          <span class="receipt-number" id="receiptNumber">INV-000000</span>
          <span>Issue Date: <span id="issueDate">N/A</span></span>
        </div>
      </div>

      <div class="section">
        <div class="section-title">Client &amp; Payment Details</div>

        <div class="info-grid">
          <div class="info-card">
            <table class="kv">
              <tbody>
                <tr>
                  <td class="label">Client Name</td>
                  <td class="value" id="clientName">Client Name</td>
                </tr>
                <tr>
                  <td class="label">Client ID</td>
                  <td class="value client-code" id="clientId">CLI-000000</td>
                </tr>
                <tr>
                  <td class="label">Contract ID</td>
                  <td class="value" id="contractId">CT-000000</td>
                </tr>
                <tr>
                  <td class="label">Phone</td>
                  <td class="value" id="clientPhone">N/A</td>
                </tr>
                <tr>
                  <td class="label">Email</td>
                  <td class="value" id="clientEmail">N/A</td>
                </tr>
              </tbody>
            </table>
          </div>

          <div class="info-card">
            <table class="kv">
              <tbody>
                <tr>
                  <td class="label">Payment Date</td>
                  <td class="value" id="paymentDate">N/A</td>
                </tr>
                <tr>
                  <td class="label">Payment Method</td>
                  <td class="value" id="paymentMethod">N/A</td>
                </tr>
                <tr>
                  <td class="label">Reference</td>
                  <td class="value" id="paymentReference">N/A</td>
                </tr>
                <tr>
                  <td class="label">Notes</td>
                  <td class="value" id="paymentNotes">None</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <div class="section">
        <div class="section-title">Financial Summary</div>

        <table class="summary-table">
          <tbody>
            <tr>
              <th>Description</th>
              <th class="amount">Amount (₦)</th>
            </tr>
            <tr>
              <td>Total Contract Value</td>
              <td class="amount" id="totalValue">0.00</td>
            </tr>
            <tr>
              <td>Total Amount Paid (before this payment)</td>
              <td class="amount" id="totalPaidBefore">0.00</td>
            </tr>
            <tr>
              <td>Current Payment</td>
              <td class="amount positive" id="amountPaid">0.00</td>
            </tr>
            <tr>
              <td>Outstanding Balance</td>
              <td class="amount negative" id="outstanding">0.00</td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="section">
        <div class="section-title">Purchased Plot</div>

        <table class="summary-table" id="plotsTable">
          <thead>
            <tr>
              <th>Area</th>
              <th>Plot Code</th>
              <th class="amount">Price (₦)</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody id="plotsBody">
            <tr>
              <td colspan="4" style="text-align:center; color:rgba(15,23,42,.55); padding:12px;">
                No plots found
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="receipt-footer">
        <p>This document serves as an official receipt issued by Safe Step Properties Limited.</p>
        <p>All payments are subject to the terms and conditions of the underlying contract.</p>
        <p>Address: Suite 02, Jahi Mall, Valentine Nwabuaeze Crescent, Jahi, FCT Abuja. · Phone: +234 814 241 1113 / +234 704 646 6653 · Email: info@safestepproperties.com</p>
        <p>Generated on <span id="footerDate"></span>.</p>
      </div>

      <div class="signature-block">
        <div class="signature-row">
          <div class="signature-col">
            <div class="signature-line"></div>
            <div class="signature-label">Authorized Signatory</div>
          </div>
          <div class="signature-col">
            <div class="signature-line"></div>
            <div class="signature-label">Accounts / Admin</div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script>
    function getQueryParam(name) {
      const params = new URLSearchParams(window.location.search);
      return params.get(name);
    }

    function setText(id, value, fallback) {
      const el = document.getElementById(id);
      if (!el) return;
      el.textContent = value || fallback;
    }

    function fmtMoney(v) {
      const n = Number(v);
      if (!isFinite(n)) return v || "0.00";
      return n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    }

    async function loadReceipt() {
      const paymentId = getQueryParam('paymentId');
      if (!paymentId) {
        console.error('No paymentId provided in query string');
        const fd = document.getElementById('footerDate');
        if (fd) fd.textContent = new Date().toLocaleString();
        return;
      }

      try {
        const res = await fetch(
          `../../api/get_payment_receipt.php?paymentId=${encodeURIComponent(paymentId)}`
        );
        const data = await res.json();

        if (!res.ok || !data) {
          console.error('Failed to load receipt data', data);
          const fd = document.getElementById('footerDate');
          if (fd) fd.textContent = new Date().toLocaleString();
          return;
        }

        setText('receiptNumber', data.receiptNumber, 'N/A');
        setText('issueDate', data.issueDate, 'N/A');

        setText('clientName', data.clientName, 'N/A');
        setText('clientId', data.clientId, 'N/A');
        setText('contractId', data.contractId, 'N/A');
        setText('clientPhone', data.clientPhone, 'N/A');
        setText('clientEmail', data.clientEmail, 'N/A');

        setText('paymentDate', data.paymentDate, 'N/A');
        setText('paymentMethod', data.paymentMethod, 'N/A');
        setText('paymentReference', data.paymentReference, 'N/A');
        setText('paymentNotes', data.paymentNotes, 'None');

        setText('amountPaid', (data.amountPaid !== undefined ? fmtMoney(data.amountPaid) : null), '0.00');
        setText('totalValue', (data.totalValue !== undefined ? fmtMoney(data.totalValue) : null), '0.00');
        setText('totalPaidBefore', (data.totalPaidBefore !== undefined ? fmtMoney(data.totalPaidBefore) : null), '0.00');
        setText('outstanding', (data.outstanding !== undefined ? fmtMoney(data.outstanding) : null), '0.00');

        const plotsBody = document.getElementById('plotsBody');
        if (plotsBody && data.plots && data.plots.length > 0) {
          plotsBody.innerHTML = '';
          data.plots.forEach(plot => {
            const rawStatus = (plot.status || '').toString().trim();
            const statusLower = rawStatus.toLowerCase();
            const statusClass = statusLower === 'completed' ? 'status-active' : 'status-pending';

            const row = document.createElement('tr');
            row.innerHTML = `
              <td>${plot.area || ''}</td>
              <td class="plot-code">${plot.code || ''}</td>
              <td class="amount">${plot.price ? fmtMoney(plot.price) : '0.00'}</td>
              <td><span class="status-badge ${statusClass}">${rawStatus || 'N/A'}</span></td>
            `;
            plotsBody.appendChild(row);
          });
        }

        const fd = document.getElementById('footerDate');
        if (fd) fd.textContent = new Date().toLocaleString();
      } catch (err) {
        console.error('Error loading receipt:', err);
        const fd = document.getElementById('footerDate');
        if (fd) fd.textContent = new Date().toLocaleString();
      }
    }

    async function sendReceiptEmail() {
      const paymentId = getQueryParam('paymentId');
      if (!paymentId) {
        alert('Missing paymentId.');
        return;
      }

      const btn = document.getElementById('btn-send-email');
      if (btn) {
        btn.disabled = true;
        btn.innerHTML = `<i class="fas fa-spinner fa-spin"></i> Sending...`;
      }

      try {
        const res = await fetch(
          `../../api/send_payment_receipt_email.php?paymentId=${encodeURIComponent(paymentId)}`,
          { method: 'POST' }
        );
        const data = await res.json();

        if (!res.ok || !data || data.status !== 'ok') {
          console.error('Email send failed', data);
          alert(data && data.message ? data.message : 'Failed to send email.');
        } else {
          alert('Receipt emailed to client successfully.');
        }
      } catch (err) {
        console.error('Error sending email:', err);
        alert('Error sending email.');
      } finally {
        if (btn) {
          btn.disabled = false;
          btn.innerHTML = `<i class="fas fa-envelope"></i> Send via Email`;
        }
      }
    }

    window.onload = loadReceipt;
  </script>
</body>

</html>
