<?php
session_start();
$page_title = 'Share Receipt';
$active_nav = 'wallet';
include("includes/header.php");
$uid = (int)$_SESSION['user_id'];

$tid = (int)($_GET['id'] ?? 0);
if (!$tid) { header("Location: wallet.php"); exit; }

$stmt = $conn->prepare("SELECT wt.*, r.name AS restaurant_name FROM wallet_transactions wt LEFT JOIN restaurants r ON wt.restaurant_id = r.id WHERE wt.id=? AND wt.user_id=?");
$stmt->bind_param("ii", $tid, $uid);
$stmt->execute();
$t = $stmt->get_result()->fetch_assoc();
if (!$t) { header("Location: wallet.php"); exit; }

$is_cr  = $t['type'] === 'credit';
$status = $t['status'] ?: 'success';
$ref    = $t['reference'] ?: ('DBL' . str_pad($t['id'], 10, '0', STR_PAD_LEFT));
$session_id = strtoupper(substr(hash('sha1', $ref . $t['created_at']), 0, 24));
$party_label = $is_cr ? 'Funded via' : 'Paid to';
$party_value = $is_cr ? ($t['description'] ?: 'Bank / Card') : ($t['restaurant_name'] ?: 'Dabil Merchant');
?>

<style>
.app-topbar { display: none; }
.main-content { padding-top: calc(env(safe-area-inset-top) + 6px); }
.sr-wrap { max-width: 600px; margin: 0 auto; }

.sub-topbar { display: flex; align-items: center; gap: 12px; padding: 4px 2px 18px; }
.sub-topbar .sub-back { width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: var(--primary); background: var(--primary-bg); flex-shrink: 0; }
.sub-topbar .sub-title { font-size: 1.15rem; font-weight: 800; letter-spacing: -.02em; color: var(--text); }

/* Receipt card (captured to image/PDF) */
.receipt { background: #fff; border-radius: 18px; padding: 32px 22px 24px; box-shadow: 0 8px 30px rgba(15,23,42,.10); position: relative; overflow: hidden; }
/* Decorative perforated edges — pinned to the very top/bottom of the card
   so they never overlap the logo or any content. */
.receipt::before, .receipt::after { content: ''; position: absolute; left: 0; right: 0; height: 12px; pointer-events: none; z-index: 0; }
.receipt::before { top: 0; background-image: radial-gradient(circle at 7px -4px, transparent 7px, #fff 7px); background-size: 16px 12px; }
.receipt::after { bottom: 0; background-image: radial-gradient(circle at 7px 16px, transparent 7px, #fff 7px); background-size: 16px 12px; }
.receipt-brand { position: relative; z-index: 1; display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 18px; }
.receipt-brand .b-left { display: flex; align-items: center; gap: 9px; }
.receipt-brand .b-icon { width: 30px; height: 30px; background: #225AE3; border-radius: 8px; display: flex; align-items: center; justify-content: center; }
.receipt-brand .b-logo { height: 30px; width: auto; max-width: 140px; object-fit: contain; display: block; }
.receipt-brand .b-name { font-size: 1.05rem; font-weight: 800; color: #0F172A; letter-spacing: -.02em; }
.receipt-brand .b-tag { font-size: .76rem; color: #64748B; font-weight: 600; }

.receipt-amt { text-align: center; margin: 6px 0 18px; }
.receipt-amt .ra { font-size: 2.1rem; font-weight: 800; letter-spacing: -.03em; line-height: 1; }
.receipt-amt .ra.cr { color: #10B981; }
.receipt-amt .ra.dr { color: #0F172A; }
.receipt-amt .rs { display: inline-flex; align-items: center; gap: 6px; margin-top: 10px; font-weight: 700; font-size: .9rem; color: #10B981; }
.receipt-amt .rd { font-size: .78rem; color: #94A3B8; margin-top: 6px; }

.receipt-divider { border: none; border-top: 1.5px dashed #E2E8F0; margin: 6px 0 14px; }
.receipt-row { display: flex; justify-content: space-between; gap: 14px; padding: 9px 0; }
.receipt-row .rk { font-size: .8rem; color: #64748B; flex-shrink: 0; }
.receipt-row .rv { font-size: .82rem; font-weight: 700; color: #0F172A; text-align: right; word-break: break-word; }
.receipt-note { font-size: .72rem; color: #94A3B8; line-height: 1.5; margin-top: 16px; padding-top: 14px; border-top: 1px solid #F1F5F9; }

.sr-actions { display: flex; gap: 12px; margin-top: 18px; }
.sr-btn { flex: 1; display: flex; align-items: center; justify-content: center; gap: 8px; height: 52px; border-radius: 14px; font-family: var(--font); font-weight: 700; font-size: .9rem; cursor: pointer; border: 1.5px solid var(--border); background: #fff; color: var(--primary); }
.sr-btn:active { background: var(--bg); }
.sr-btn svg { width: 18px; height: 18px; }
.sr-btn.primary { background: var(--primary); color: #fff; border-color: var(--primary); box-shadow: 0 6px 18px rgba(34,90,227,.3); }
</style>

<div class="sr-wrap">

  <div class="sub-topbar">
    <a href="transaction_detail.php?id=<?php echo (int)$t['id']; ?>" class="sub-back" aria-label="Back" onclick="return goBack(event)">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 12H5m0 0l7 7M5 12l7-7"/></svg>
    </a>
    <span class="sub-title">Share Receipt</span>
  </div>

  <div class="receipt" id="receipt">
    <div class="receipt-brand">
      <div class="b-left">
        <img class="b-logo" src="assets/img/dlogo.png" alt="Dabil">
      </div>
      <span class="b-tag">Transaction Receipt</span>
    </div>

    <div class="receipt-amt">
      <div class="ra <?php echo $is_cr ? 'cr' : 'dr'; ?>"><?php echo $is_cr ? '+' : '-'; ?>₦<?php echo number_format($t['amount'], 2); ?></div>
      <div class="rs"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#10B981" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="8 12 11 15 16 9"/></svg><?php echo ucfirst($status); ?></div>
      <div class="rd"><?php echo date('M j, Y · g:i A', strtotime($t['created_at'])); ?></div>
    </div>

    <hr class="receipt-divider">

    <div class="receipt-row"><span class="rk"><?php echo $is_cr ? 'Account Holder' : 'Paid by'; ?></span><span class="rv"><?php echo htmlspecialchars($__name); ?></span></div>
    <div class="receipt-row"><span class="rk"><?php echo $party_label; ?></span><span class="rv"><?php echo htmlspecialchars($party_value); ?></span></div>
    <div class="receipt-row"><span class="rk">Transaction Type</span><span class="rv"><?php echo $is_cr ? 'Wallet Funding' : 'Wallet Payment'; ?></span></div>
    <div class="receipt-row"><span class="rk">Transaction No.</span><span class="rv"><?php echo htmlspecialchars($ref); ?></span></div>
    <div class="receipt-row"><span class="rk">Session ID</span><span class="rv"><?php echo $session_id; ?></span></div>

    <div class="receipt-note">This is an electronic receipt generated by Dabil for your wallet activity. Keep it for your records. For any questions, contact Dabil support.</div>
  </div>

  <div class="sr-actions">
    <button class="sr-btn" id="shareImg">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></svg>
      Share as image
    </button>
    <button class="sr-btn primary" id="sharePdf">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
      Share as PDF
    </button>
  </div>
</div>

<div class="os-toast" id="srToast" style="position:fixed;bottom:calc(env(safe-area-inset-bottom) + 90px);left:50%;transform:translateX(-50%);background:#0F172A;color:#fff;padding:10px 18px;border-radius:30px;font-size:.8rem;font-weight:600;box-shadow:0 6px 20px rgba(0,0,0,.25);z-index:700;opacity:0;pointer-events:none;transition:opacity .25s"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script>
(function () {
  const fileBase = 'Dabil-Receipt-<?php echo preg_replace('/[^A-Za-z0-9]/', '', $ref); ?>';
  function srToast(m){const t=document.getElementById('srToast');t.textContent=m;t.style.opacity='1';clearTimeout(window._sr);window._sr=setTimeout(()=>t.style.opacity='0',2200);}

  function renderCanvas() {
    if (typeof html2canvas !== 'function') return Promise.reject('lib');
    return html2canvas(document.getElementById('receipt'), { scale: 2, backgroundColor: '#ffffff', useCORS: true });
  }

  document.getElementById('shareImg').addEventListener('click', function () {
    srToast('Preparing image…');
    renderCanvas().then(canvas => {
      canvas.toBlob(blob => {
        if (!blob) { srToast('Could not create image'); return; }
        const file = new File([blob], fileBase + '.png', { type: 'image/png' });
        if (navigator.canShare && navigator.canShare({ files: [file] })) {
          navigator.share({ files: [file], title: 'Dabil Receipt' }).catch(() => {});
        } else {
          const a = document.createElement('a');
          a.href = URL.createObjectURL(blob); a.download = file.name; a.click();
          URL.revokeObjectURL(a.href);
          srToast('Image saved');
        }
      }, 'image/png');
    }).catch(() => srToast('Sharing not available here'));
  });

  document.getElementById('sharePdf').addEventListener('click', function () {
    srToast('Preparing PDF…');
    renderCanvas().then(canvas => {
      const { jsPDF } = window.jspdf || {};
      if (!jsPDF) { srToast('PDF not available'); return; }
      const img = canvas.toDataURL('image/png');
      const pdf = new jsPDF({ unit: 'pt', format: [canvas.width / 2, canvas.height / 2] });
      pdf.addImage(img, 'PNG', 0, 0, canvas.width / 2, canvas.height / 2);
      pdf.save(fileBase + '.pdf');
      srToast('PDF saved');
    }).catch(() => srToast('PDF not available here'));
  });
})();
</script>

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