<?php
require_once __DIR__ . '/includes/functions.php';
startSecureSession();

$apiKey = $_GET['api_key'] ?? '';
$amount = $_GET['amount'] ?? '';
$upi = $_GET['upi'] ?? '';
$redirectUrl = $_GET['redirect_url'] ?? '';
$linkName = $_GET['name'] ?? '';
$nonce = $_GET['nonce'] ?? '';

// Only allow http(s) redirect targets — blocks javascript:, data:, etc.
if ($redirectUrl && !preg_match('#^https?://#i', $redirectUrl)) {
    $redirectUrl = '';
}

$user = getUserByApiKey($apiKey);
$errorMsg = '';
$alreadyPaidInfo = null; // set if this exact link was already paid before

if (!$user) {
    $errorMsg = 'Invalid API key.';
} elseif (strtotime($user['plan_expires_at']) < time()) {
    $errorMsg = 'This API key has expired.';
} elseif (!$amount || !is_numeric($amount)) {
    $errorMsg = 'Invalid or missing amount.';
} elseif (!$user['gmail_connected']) {
    $errorMsg = 'Merchant has not connected their FamPay Gmail yet.';
} else {
    // Use merchant's own UPI ID if not overridden by ?upi= param
    $upi = $upi ?: $user['fampay_upi_id'];

    $payLinkId = computePayLinkId($apiKey, $amount, $redirectUrl, $linkName, $nonce);
    $existingOrder = getLatestOrderByLinkId($payLinkId);

    if ($existingOrder && $existingOrder['status'] === 'success') {
        $alreadyPaidInfo = $existingOrder;
    } elseif ($existingOrder && $existingOrder['status'] === 'pending' && ($existingOrder['expires_at_timestamp'] ?? 0) > time()) {
        $orderId = $existingOrder['order_id'];
        $noteCode = $existingOrder['note_code'] ?? '';
        $now = nowIST();
    } else {
        $orderId = generateOrderId('FAMPAY');
        $noteCode = generatePaymentNoteCode();
        $now = nowIST();
        $order = [
            'order_id' => $orderId,
            'type' => 'api_order',
            'user_id' => $user['id'],
            'upi_id' => $upi,
            'amount' => floatval($amount),
            'note_code' => $noteCode,
            'pay_link_id' => $payLinkId,
            'status' => 'pending',
            'created_at' => $now->format('Y-m-d H:i:s'),
            'created_at_timestamp' => time(),
            'expires_at_timestamp' => time() + 300
        ];
        saveOrder($order);

        $user['total_requests'] = ($user['total_requests'] ?? 0) + 1;
        saveUser($user);
    }

    if (!$alreadyPaidInfo) {
        $upiString = "upi://pay?pa=" . urlencode($upi) . "&pn=" . urlencode('FamPay') . "&tr=" . urlencode($orderId) . "&tn=" . urlencode($noteCode) . "&am=" . urlencode($amount) . "&cu=INR";
        $qrUrl = "https://api.qrserver.com/v1/create-qr-code/?size=280x280&data=" . urlencode($upiString);
    }
}

$pageTitle = 'Pay via UPI - Secure Checkout';
$metaDesc  = 'Secure UPI payment page powered by AdityaHost FamAPI. Scan the QR with any UPI app and pay instantly.';
include __DIR__ . '/includes/public_header.php';
?>
<style>
  :root {
    --bg: #f0f4f8;
    --card: #ffffff;
    --blue: #3b82f6;
    --blue-light: #eff6ff;
    --blue-dark: #1e40af;
    --ink: #1e293b;
    --muted: #64748b;
    --line: #e2e8f0;
    --green: #16a34a;
    --green-bg: #f0fdf4;
    --green-border: #bbf7d0;
    --red: #dc2626;
    --red-bg: #fef2f2;
    --red-border: #fecaca;
    --amber: #f59e0b;
    --mono: 'SF Mono', 'Cascadia Code', 'Fira Code', monospace;
  }

  .pg {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 32px 16px;
    background: var(--bg);
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  }

  .pay-card {
    width: 100%;
    max-width: 400px;
    background: var(--card);
    border-left: 4px solid var(--blue);
    border-radius: 16px;
    box-shadow: 0 4px 24px rgba(0,0,0,0.06), 0 1px 4px rgba(0,0,0,0.04);
    padding: 32px 28px;
    position: relative;
    overflow: hidden;
  }

  .pay-inner {
    text-align: center;
  }

  /* Brand */
  .pay-brand {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    margin-bottom: 28px;
  }
  .pay-brand img {
    width: 32px;
    height: 32px;
    border-radius: 8px;
  }
  .pay-brand-name {
    font-size: 18px;
    font-weight: 700;
    color: var(--ink);
    letter-spacing: -0.3px;
  }
  .pay-brand-name span {
    color: var(--blue);
  }

  /* Amount */
  .pay-order-label {
    font-size: 11px;
    font-weight: 700;
    letter-spacing: 1.6px;
    text-transform: uppercase;
    color: var(--muted);
    margin: 0 0 6px;
  }
  .pay-amount {
    font-size: 48px;
    font-weight: 800;
    color: var(--ink);
    font-family: var(--mono);
    letter-spacing: -1.5px;
    line-height: 1.1;
    margin: 0 0 24px;
  }
  .pay-amount .curr {
    font-size: 26px;
    color: var(--muted);
    font-weight: 700;
    margin-right: 2px;
  }
  .pay-amount .code {
    font-size: 16px;
    color: var(--muted);
    font-weight: 600;
    margin-left: 6px;
  }

  /* QR */
  .pay-qr-wrap {
    width: 220px;
    height: 220px;
    margin: 0 auto 8px;
    padding: 12px;
    border: 2px solid var(--line);
    border-radius: 16px;
    background: #fff;
  }
  .pay-qr-img {
    width: 100%;
    height: 100%;
    object-fit: contain;
    display: block;
  }
  .pay-qr-hint {
    font-size: 12px;
    font-weight: 600;
    color: var(--muted);
    margin: 0 0 20px;
    letter-spacing: 0.3px;
  }

  /* Details rows */
  .pay-details {
    text-align: left;
    border: 1px solid var(--line);
    border-radius: 12px;
    overflow: hidden;
    margin-bottom: 20px;
  }
  .pay-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    font-size: 13px;
    border-bottom: 1px solid var(--line);
    transition: background 0.15s;
  }
  .pay-row:last-child {
    border-bottom: none;
  }
  .pay-row:hover {
    background: #f8fafc;
  }
  .pay-row-label {
    color: var(--muted);
    font-weight: 500;
  }
  .pay-row-value {
    color: var(--ink);
    font-weight: 700;
    text-align: right;
    word-break: break-all;
    max-width: 55%;
  }

  /* Status pill */
  .pay-status {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 10px 20px;
    border-radius: 10px;
    background: var(--blue-light);
    border: 1px solid #bfdbfe;
    font-size: 13px;
    font-weight: 700;
    color: var(--blue-dark);
    margin-bottom: 16px;
  }
  .pay-status .dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: var(--blue);
    animation: pulse-dot 1.5s ease-in-out infinite;
    box-shadow: 0 0 0 0 rgba(59,130,246,0.4);
  }
  .pay-status.suc {
    background: var(--green-bg);
    border-color: var(--green-border);
    color: var(--green);
  }
  .pay-status.suc .dot {
    background: var(--green);
    animation: none;
    box-shadow: 0 0 0 4px rgba(22,163,74,0.15);
  }
  .pay-status.pending-check .dot {
    background: var(--blue);
  }

  @keyframes pulse-dot {
    0%, 100% { box-shadow: 0 0 0 0 rgba(59,130,246,0.4); }
    50% { box-shadow: 0 0 0 6px rgba(59,130,246,0); }
  }

  /* Footer */
  .pay-foot {
    font-size: 11.5px;
    color: var(--muted);
    text-align: center;
    margin-top: 20px;
    opacity: 0.7;
  }
  .pay-foot b {
    font-weight: 700;
    color: var(--ink);
  }

  /* Expiry */
  .pay-expiry {
    font-size: 12px;
    color: var(--muted);
    margin-top: 6px;
  }

  /* Error */
  .err-wrap {
    text-align: center;
  }
  .err-icon {
    width: 64px;
    height: 64px;
    border-radius: 50%;
    background: var(--red-bg);
    border: 2px solid var(--red-border);
    display: grid;
    place-items: center;
    margin: 0 auto 16px;
  }
  .err-icon svg {
    width: 30px;
    height: 30px;
    color: var(--red);
  }
  .err-title {
    font-size: 18px;
    font-weight: 800;
    color: var(--red);
    margin: 0 0 8px;
  }
  .err-msg {
    font-size: 14px;
    color: var(--muted);
    margin: 0 0 6px;
    line-height: 1.5;
  }

  /* Success */
  .suc-wrap {
    text-align: center;
  }
  .suc-check {
    width: 72px;
    height: 72px;
    border-radius: 50%;
    background: var(--green);
    display: grid;
    place-items: center;
    margin: 0 auto 18px;
    animation: suc-pop 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards;
    box-shadow: 0 8px 24px rgba(22,163,74,0.3);
  }
  .suc-check svg {
    width: 36px;
    height: 36px;
    color: #fff;
    stroke-dasharray: 50;
    stroke-dashoffset: 50;
    animation: draw-suc 0.5s ease-out 0.25s forwards;
  }
  @keyframes suc-pop {
    0% { transform: scale(0); opacity: 0; }
    100% { transform: scale(1); opacity: 1; }
  }
  @keyframes draw-suc {
    to { stroke-dashoffset: 0; }
  }

  .suc-title {
    font-size: 22px;
    font-weight: 800;
    color: var(--green);
    margin: 0 0 6px;
    animation: slide-up 0.4s ease-out 0.1s both;
  }
  .suc-sub {
    font-size: 13px;
    color: var(--muted);
    margin: 0 0 16px;
    animation: slide-up 0.4s ease-out 0.15s both;
  }
  .suc-amt {
    font-size: 40px;
    font-weight: 800;
    color: var(--ink);
    font-family: var(--mono);
    letter-spacing: -1px;
    margin: 0 0 18px;
    animation: bounce-in 0.5s ease-out 0.2s both;
  }

  /* UTR box */
  .suc-utr-box {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    background: var(--green-bg);
    border: 1.5px solid var(--green-border);
    border-radius: 12px;
    padding: 14px 16px;
    margin-bottom: 20px;
    animation: slide-up 0.4s ease-out 0.25s both;
  }
  .suc-utr-box small {
    font-size: 10px;
    font-weight: 800;
    letter-spacing: 1.2px;
    text-transform: uppercase;
    color: var(--green);
  }
  .suc-utr-box b {
    font-family: var(--mono);
    font-size: 16px;
    color: var(--ink);
    letter-spacing: 0.5px;
  }
  .suc-utr-box button {
    background: var(--green);
    border: 0;
    color: #fff;
    font-size: 11px;
    font-weight: 800;
    padding: 6px 14px;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.15s;
    letter-spacing: 0.5px;
  }
  .suc-utr-box button:hover {
    background: #15803d;
    transform: scale(1.05);
  }

  .suc-redirect {
    font-size: 13px;
    font-weight: 700;
    color: var(--blue);
    margin-top: 16px;
    animation: slide-up 0.4s ease-out 0.35s both;
  }

  .suc-note {
    font-size: 12px;
    color: var(--muted);
    margin-top: 14px;
    opacity: 0.7;
  }

  .pay-close-btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    margin-top: 16px;
    padding: 12px 28px;
    border-radius: 12px;
    font-weight: 700;
    font-size: 14px;
    border: 0;
    cursor: pointer;
    color: #fff;
    background: var(--blue);
    box-shadow: 0 4px 12px rgba(59,130,246,0.3);
    transition: all 0.15s;
  }
  .pay-close-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 6px 16px rgba(59,130,246,0.4);
  }

  @keyframes slide-up {
    0% { opacity: 0; transform: translateY(16px); }
    100% { opacity: 1; transform: translateY(0); }
  }
  @keyframes bounce-in {
    0% { transform: scale(0.3); opacity: 0; }
    50% { transform: scale(1.05); }
    70% { transform: scale(0.95); }
    100% { transform: scale(1); opacity: 1; }
  }
  @keyframes popConfetti {
    0% { opacity: 1; transform: translate(0,0) scale(0.5); }
    80% { opacity: 1; transform: translate(var(--tx),var(--ty)) scale(1); }
    100% { opacity: 0; transform: translate(var(--tx),calc(var(--ty) + 20px)) scale(0.8); }
  }
</style>

<div class="pg">
  <div class="pay-card">
    <?php if ($errorMsg): ?>
      <div class="pay-inner err-wrap">
        <div class="err-icon">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round">
            <circle cx="12" cy="12" r="9"/>
            <path d="M12 7.5v5M12 16.3h.01"/>
          </svg>
        </div>
        <h2 class="err-title">Payment Unavailable</h2>
        <p class="err-msg"><?= htmlspecialchars($errorMsg) ?></p>
        <p class="err-msg" style="margin-top:8px;font-size:12px;">Please contact the merchant for help.</p>
      </div>

    <?php elseif ($alreadyPaidInfo): ?>
      <div class="pay-inner suc-wrap">
        <div class="suc-check" style="background:var(--green);animation:none;">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
            <polyline points="20 6 9 17 4 12"/>
          </svg>
        </div>
        <h2 class="suc-title">Already Paid</h2>
        <p class="suc-sub">This payment link has already been used and cannot be paid again.</p>
        <div class="suc-amt"><span class="curr">₹</span><?= htmlspecialchars(number_format((float)$amount, 2)) ?></div>
        <?php if (!empty($alreadyPaidInfo['utr'])): ?>
          <div class="suc-utr-box">
            <small>UTR</small>
            <b><?= htmlspecialchars($alreadyPaidInfo['utr']) ?></b>
          </div>
        <?php endif; ?>
        <p class="suc-note">Need to pay again? Ask the merchant for a fresh link.</p>
      </div>

    <?php else: ?>
      <div id="viewPay" class="pay-inner">
        <div class="pay-brand">
          <img src="assets/img/logo.png" alt="AdityaHost">
          <span class="pay-brand-name">Aditya<span>Host</span></span>
        </div>

        <?php if ($linkName): ?>
          <div class="pay-status pending-check">
            <span class="dot"></span>
            <?= htmlspecialchars($linkName) ?>
          </div>
        <?php endif; ?>

        <div class="pay-order-label">Order Total</div>
        <div class="pay-amount">
          <span class="curr">₹</span><?= htmlspecialchars(number_format(floor((float)$amount))) ?>.00<span class="code">INR</span>
        </div>

        <div class="pay-qr-wrap">
          <img class="pay-qr-img" id="qr" src="<?= htmlspecialchars($qrUrl) ?>" alt="Scan to Pay with UPI">
        </div>
        <div class="pay-qr-hint">SCAN WITH ANY UPI APP</div>

        <div class="pay-status pending-check" id="statusBox">
          <span class="dot"></span>
          <span id="statusText">Waiting for payment…</span>
        </div>
        <div class="pay-expiry" id="payExpiry"></div>

        <div class="pay-details">
          <div class="pay-row">
            <span class="pay-row-label">Merchant</span>
            <b class="pay-row-value"><?= htmlspecialchars($user['name'] ?? 'AdityaHost') ?></b>
          </div>
          <div class="pay-row">
            <span class="pay-row-label">Order ID</span>
            <b class="pay-row-value" id="detailOrderId"><?= htmlspecialchars($orderId ?? '—') ?></b>
          </div>
          <div class="pay-row">
            <span class="pay-row-label">Expires In</span>
            <b class="pay-row-value" id="detailExpiry">—</b>
          </div>
          <div class="pay-row">
            <span class="pay-row-label">Verification</span>
            <b class="pay-row-value">
              <span class="pay-status pending-check" style="padding:4px 10px;font-size:11px;border-radius:6px;margin:0;">
                <span class="dot" style="width:6px;height:6px;"></span>
                Waiting
              </span>
            </b>
          </div>
        </div>
      </div>

      <div id="viewSuccess" class="pay-inner suc-wrap" style="display:none">
        <div class="suc-check">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
            <polyline points="20 6 9 17 4 12"/>
          </svg>
        </div>
        <h2 class="suc-title">Payment Successful!</h2>
        <p class="suc-sub">Money received in the merchant's account</p>

        <div class="pay-status suc" style="margin:10px auto 16px;display:inline-flex;">
          <span class="dot"></span>
          Payment received
        </div>

        <div class="suc-amt" id="suAmount">₹0.00</div>

        <div class="suc-utr-box">
          <small>UTR Number</small>
          <b id="suUtr">——————</b>
          <button onclick="copyUtr()" id="suUtrBtn">COPY</button>
        </div>

        <div class="pay-details" style="text-align:left;">
          <div class="pay-row">
            <span class="pay-row-label">Merchant</span>
            <b class="pay-row-value" id="suMerchant">—</b>
          </div>
          <div class="pay-row">
            <span class="pay-row-label">Order ID</span>
            <b class="pay-row-value" id="suOrder">—</b>
          </div>
          <div class="pay-row">
            <span class="pay-row-label">Paid By</span>
            <b class="pay-row-value" id="suSender">—</b>
          </div>
          <div class="pay-row">
            <span class="pay-row-label">Payment Time</span>
            <b class="pay-row-value" id="suTime">—</b>
          </div>
          <div class="pay-row">
            <span class="pay-row-label">Transaction ID</span>
            <b class="pay-row-value" id="suTxn">—</b>
          </div>
        </div>

        <div class="suc-redirect" id="suRedirect" style="display:none">
          Returning to merchant in <b id="suCount">4</b>s…
        </div>
        <button class="pay-close-btn" id="suClose" style="display:none" onclick="window.close()">Close this page</button>
        <p class="suc-note">Keep this UTR to track or dispute your payment.</p>
      </div>
    <?php endif; ?>
  </div>

  <p class="pay-foot">Powered by <b>AdityaHost FamAPI</b></p>
</div>

<?php if (!$errorMsg && !$alreadyPaidInfo): ?>
<script>
    const orderId = <?= json_encode($orderId ?? '') ?>;
    const apiKey = <?= json_encode($apiKey) ?>;
    const redirectUrl = <?= json_encode($redirectUrl) ?>;
    const statusBox = document.getElementById('statusBox');
    const statusText = document.getElementById('statusText');
    const expiryTs = <?= json_encode(($order['expires_at_timestamp'] ?? time() + 300) * 1000) ?>;

    function startExpiry() {
        const el = document.getElementById('payExpiry');
        const detEl = document.getElementById('detailExpiry');
        const tick = () => {
            const left = Math.max(0, Math.floor((expiryTs - Date.now()) / 1000));
            const mm = String(Math.floor(left / 60)).padStart(2, '0');
            const ss = String(left % 60).padStart(2, '0');
            el.textContent = 'This QR expires in ' + mm + ':' + ss;
            detEl.textContent = mm + ':' + ss;
            if (left > 0) setTimeout(tick, 1000);
        };
        tick();
    }

    function spawnConfetti() {
        const host = document.querySelector('.pay-card');
        const colors = ['#3b82f6','#60a5fa','#93c5fd','#dbeafe','#1e40af','#16a34a','#4ade80','#f59e0b'];
        for (let i = 0; i < 35; i++) {
            const dot = document.createElement('div');
            const angle = Math.random() * 2 * Math.PI;
            const dist = 60 + Math.random() * 180;
            dot.style.cssText = `
                position:absolute; left:${30 + Math.random() * 40}%; top:${25 + Math.random() * 20}%;
                background:${colors[Math.floor(Math.random() * colors.length)]};
                width:${4 + Math.random() * 6}px; height:${4 + Math.random() * 6}px;
                border-radius:50%; z-index:99; pointer-events:none;
                --tx:${Math.cos(angle) * dist}px; --ty:${Math.sin(angle) * dist}px;
                animation:popConfetti ${1.2 + Math.random() * 0.8}s ease-out forwards;
                animation-delay:${Math.random() * 0.3}s;
            `;
            host.appendChild(dot);
        }
    }

    function showSuccess(d) {
        document.getElementById('viewPay').style.display = 'none';
        const vs = document.getElementById('viewSuccess');
        vs.style.display = 'block';
        const amt = parseFloat(d.amount || 0);
        document.getElementById('suAmount').textContent = '₹' + amt.toFixed(2);
        document.getElementById('suUtr').textContent = d.utr || 'N/A';
        document.getElementById('suMerchant').textContent = <?= json_encode($user['name'] ?? 'AdityaHost') ?>;
        document.getElementById('suOrder').textContent = d.order_id || orderId;
        document.getElementById('suSender').textContent = d.sender_name || '—';
        document.getElementById('suTime').textContent = d.payment_time_ist || '—';
        document.getElementById('suTxn').textContent = d.transaction_id || '—';
        spawnConfetti();
        if (redirectUrl) {
            const box = document.getElementById('suRedirect');
            box.style.display = 'block';
            let n = 4;
            const c = document.getElementById('suCount');
            const timer = setInterval(() => {
                n--;
                if (n <= 0) { clearInterval(timer); window.location.href = redirectUrl; }
                c.textContent = n;
            }, 1000);
        } else {
            const box = document.getElementById('suRedirect');
            box.style.display = 'block';
            box.innerHTML = 'Redirecting to dashboard in <b id="suCount">3</b>s...';
            let n = 3;
            const c = document.getElementById('suCount');
            const timer = setInterval(() => {
                n--;
                if (n <= 0) {
                    clearInterval(timer);
                    try { window.close(); } catch(e) {}
                    window.location.href = 'dashboard.php';
                }
                c.textContent = n;
            }, 1000);
        }
    }

    function copyUtr() {
        const utr = document.getElementById('suUtr').textContent;
        const btn = document.getElementById('suUtrBtn');
        const done = () => { btn.textContent = 'COPIED ✓'; setTimeout(() => btn.textContent = 'COPY', 1800); };
        if (navigator.clipboard) {
            navigator.clipboard.writeText(utr).then(done).catch(() => { fallbackCopy(utr); done(); });
        } else { fallbackCopy(utr); done(); }
    }

    function fallbackCopy(txt) {
        const ta = document.createElement('textarea');
        ta.value = txt; document.body.appendChild(ta); ta.select();
        try { document.execCommand('copy'); } catch (e) {}
        document.body.removeChild(ta);
    }

    startExpiry();

    const poll = setInterval(() => {
        fetch('api/verify_order.php?api_key=' + encodeURIComponent(apiKey) + '&order_id=' + encodeURIComponent(orderId))
            .then(res => res.json())
            .then(data => {
                if (data.status === 'success') {
                    clearInterval(poll);
                    statusBox.classList.add('suc');
                    statusText.textContent = 'Payment received!';
                    showSuccess(data.data || {});
                } else if (data.status === 'expired') {
                    clearInterval(poll);
                    statusBox.classList.add('suc');
                    statusText.textContent = 'Order expired. Please refresh.';
                } else if (data.status === 'error') {
                    statusText.textContent = data.message;
                }
            })
            .catch(() => {});
    }, 1500);
</script>
<?php endif; ?>
<?php include __DIR__ . '/includes/public_footer.php'; ?>
