<?php
// Universal API Checkout Page
// SECURE: accepts only order_id (locked in DB). No api_key or amount in URL.
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

require_once __DIR__ . '/includes/functions.php';

$orderId = trim($_GET['order_id'] ?? '');
$errorMsg = '';
$order = null;
$user = null;
$apiKey = '';
$redirectUrl = '';
$isAlreadyPaid = false;

if (!$orderId) {
    $errorMsg = 'Missing order_id. Please return to the merchant and try again.';
} else {
    $order = getOrderById($orderId);
    if (!$order) {
        $errorMsg = 'Order not found. It may have expired or been cancelled.';
    } elseif ($order['status'] === 'expired' || ($order['status'] !== 'success' && isset($order['expires_at_timestamp']) && time() > $order['expires_at_timestamp'])) {
        if ($order['status'] !== 'expired') {
            updateOrder($orderId, ['status' => 'expired']);
        }
        $errorMsg = 'This payment session has expired. Please go back and generate a new order.';
    } else {
        $user = getUserById($order['user_id']);
        if (!$user) {
            $errorMsg = 'Merchant not found.';
        } else {
            if ($order['status'] === 'success') {
                $isAlreadyPaid = true;
            }
            $redirectUrl = $order['redirect_url'] ?? '';
            // apiKey fetch removed for security
        }
    }
}

$qrUrl = '';
$remainingSeconds = 0;
$initialTimerText = '';
if ($order && !$errorMsg && !$isAlreadyPaid) {
    $qrUrl = getBaseUrl() . '/api/qr-image.php?order_id=' . urlencode($orderId);
    $remainingSeconds = max(0, ($order['expires_at_timestamp'] ?? 0) - time());
    $m = floor($remainingSeconds / 60);
    $s = $remainingSeconds % 60;
    $initialTimerText = ($remainingSeconds > 0) ? sprintf('%02d:%02d', $m, $s) : 'Expired';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php $pageTitle = "Secure Checkout — FamGateway"; include 'includes/header.php'; ?>
<style>
:root { --blue: #2563eb; --blue-light: #dbeafe; --muted: #64748b; --border: #e2e8f0; }
* { box-sizing: border-box; margin: 0; padding: 0; }
body { background: #f1f5f9; min-height: 100vh; display: flex; align-items: center; justify-content: center; font-family: 'Poppins', sans-serif; padding: 20px; }
.product {
    background: white;
    border-radius: 24px;
    box-shadow: 16px 16px 0 #93c5fd, 0 24px 60px rgba(37,99,235,0.12);
    width: 100%;
    max-width: 400px;
    overflow: hidden;
    position: relative;
}
.product-main { padding: 28px; }
.gateway-brand { display: flex; align-items: center; gap: 10px; margin-bottom: 24px; padding-bottom: 18px; border-bottom: 1px solid var(--border); }
.product-label { font-size: 11px; font-weight: 600; letter-spacing: 1.5px; color: var(--muted); text-transform: uppercase; margin-bottom: 4px; }
.money { font-size: 44px; font-weight: 900; color: #0f172a; letter-spacing: -2px; margin-bottom: 20px; }
.money small { font-size: 18px; font-weight: 600; color: var(--muted); }
.pay-card { background: #f8fafc; border: 1px solid var(--border); border-radius: 16px; padding: 18px; }
.qr-container { text-align: center; margin-bottom: 16px; }
.qr-container img { width: 190px; height: 190px; border-radius: 12px; object-fit: contain; }
.qr-note { font-size: 11px; color: var(--muted); margin-top: 8px; font-weight: 500; }
.pay-row { display: flex; align-items: center; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid var(--border); font-size: 13px; }
.pay-row:last-child { border-bottom: none; }
.pay-row span { color: var(--muted); font-weight: 500; }
.pay-row b { font-weight: 700; color: #1e293b; font-size: 12px; }
.status { display: inline-flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 600; color: #1d4ed8; background: #eff6ff; padding: 6px 12px; border-radius: 999px; border: 1px solid #bfdbfe; }
.spinner-pulse { width: 8px; height: 8px; background: #3b82f6; border-radius: 50%; animation: pulse 1.5s infinite; }
@keyframes pulse { 0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.7); } 70% { transform: scale(1); box-shadow: 0 0 0 6px rgba(59, 130, 246, 0); } 100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(59, 130, 246, 0); } }
.error-box { background: #fef2f2; border: 1px solid #fecaca; border-radius: 12px; padding: 16px; color: #dc2626; font-size: 13px; line-height: 1.6; }
.success-container { display: none; text-align: center; padding: 10px 0; }
.product.success-mode .success-container { display: block; }
.product.success-mode .qr-container, .product.success-mode .pay-row-timer { display: none; }
.success-icon-wrap { width: 84px; height: 84px; margin: 0 auto 20px; position: relative; }
.success-icon-wrap::before { content: ''; position: absolute; inset: 0; background: #22c55e; border-radius: 50%; transform: scale(0); animation: popIn 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards; box-shadow: 0 10px 25px rgba(34,197,94,0.4); z-index: 1; }
.success-icon-wrap::after { content: ''; position: absolute; inset: -4px; border-radius: 50%; border: 2px solid #22c55e; opacity: 0; animation: ripple 1.2s ease-out 0.4s infinite; z-index: 0; }
.success-icon-wrap svg { position: relative; z-index: 2; width: 40px; height: 40px; top: 22px; color: white; stroke-dasharray: 100; stroke-dashoffset: 100; animation: drawCheck 0.4s ease-out 0.4s forwards; stroke-linecap: round; stroke-linejoin: round; }
.redirect-badge { display: inline-block; margin-top: 8px; font-size: 11px; color: var(--muted); background: #f1f5f9; padding: 4px 10px; border-radius: 20px; }
@keyframes popIn { 0% { transform: scale(0); opacity: 0; } 100% { transform: scale(1); opacity: 1; } }
@keyframes drawCheck { 100% { stroke-dashoffset: 0; } }
@keyframes ripple { 0% { transform: scale(0.8); opacity: 0.8; border-width: 4px; } 100% { transform: scale(1.5); opacity: 0; border-width: 0px; } }
@media (max-width: 500px) {
    body { padding: 16px; align-items: flex-start; background: #f8fafc; }
    .product { border-radius: 20px; box-shadow: 0 10px 40px rgba(37,99,235,0.08); min-height: auto; margin-top: 20px; }
    .money { font-size: 36px; }
}
</style>
</head>
<body>

<div class="product">
  <?php if ($errorMsg): ?>
  <div class="product-main">
    <div class="gateway-brand">
      <span style="background:#ef4444;color:#fff;width:28px;height:28px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-weight:700;">!</span>
      <span><b>Payment Error</b><br><small style="color:var(--muted);font-size:11px;">Checkout could not be loaded</small></span>
    </div>
    <div class="error-box"><?= htmlspecialchars($errorMsg) ?></div>
  </div>
  <?php else: ?>

  <div class="product-main">
    <div class="gateway-brand">
      <img src="/assets/img/logo-dark.png" alt="FamGateway" style="height:26px;width:auto;object-fit:contain;">
    </div>

    <div class="product-label">Order total</div>
    <div class="money">₹ <?= htmlspecialchars($order['payable_amount'] ?? $order['amount']) ?> <small>INR</small></div>

    <div class="pay-card">
      <div class="qr-container">
        <img id="qr" src="<?= htmlspecialchars($qrUrl) ?>" alt="UPI QR Code">
        <div class="qr-note">Scan with any UPI app · Pay <b>₹<?= htmlspecialchars($order['payable_amount'] ?? $order['amount']) ?></b> exactly</div>
      </div>

      <div class="success-container">
        <div class="success-icon-wrap">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3">
            <polyline points="20 6 9 17 4 12"></polyline>
          </svg>
        </div>
        <h3 style="color:#16a34a;margin:15px 0 5px;font-weight:800;font-size:20px;letter-spacing:-0.5px;">Payment Successful!</h3>
        <p style="color:var(--muted);font-size:12px;font-weight:500;">Thank you for your payment.</p>
        <?php if ($redirectUrl): ?>
        <div class="redirect-badge" id="redirectBadge">Redirecting you back...</div>
        <?php endif; ?>
      </div>

      <div class="pay-row">
        <span>Merchant</span>
        <b style="color:#0f172a;text-transform:capitalize;"><?= htmlspecialchars($user['name'] ?? 'Merchant') ?></b>
      </div>
      <div class="pay-row">
        <span>Order ID</span>
        <b style="font-family:monospace;"><?= htmlspecialchars($orderId) ?></b>
      </div>
      <div class="pay-row pay-row-timer">
        <span>Expires In</span>
        <b id="timerText"><?= htmlspecialchars($initialTimerText) ?></b>
      </div>
      <div class="pay-row">
        <span>Verification</span>
        <span class="status" id="statusBox">
          <div class="spinner-pulse"></div>
          <span id="statusText">Waiting for payment...</span>
        </span>
      </div>
    </div>
  </div>
  <?php endif; ?>
</div>

<?php if (!$errorMsg): ?>
<script>
    const orderId      = <?= json_encode($orderId) ?>;
    const redirectUrl  = <?= json_encode($redirectUrl) ?>;
    const isAlreadyPaid = <?= json_encode($isAlreadyPaid) ?>;
    const baseUrl      = <?= json_encode(getBaseUrl()) ?>;

    let remainingSeconds = <?= intval($remainingSeconds) ?>;
    const statusBox  = document.getElementById('statusBox');
    const statusText = document.getElementById('statusText');
    const timerText  = document.getElementById('timerText');

    let timerInterval = null;
    let poll = null;
    let failCount = 0;

    if (isAlreadyPaid) {
        showSuccess();
    } else {
        // Countdown timer
        if (remainingSeconds > 0) {
            timerInterval = setInterval(() => {
                remainingSeconds--;
                if (remainingSeconds <= 0) {
                    clearInterval(timerInterval);
                    if (timerText) timerText.innerText = 'Expired';
                } else {
                    const m = Math.floor(remainingSeconds / 60).toString().padStart(2, '0');
                    const s = (remainingSeconds % 60).toString().padStart(2, '0');
                    if (timerText) timerText.innerText = `${m}:${s}`;
                }
            }, 1000);
        }

        // Poll verify-order every 3 seconds
        poll = setInterval(() => {
            fetch(baseUrl + '/api/checkout-status.php?order_id=' + encodeURIComponent(orderId))
                .then(res => res.json())
                .then(data => {
                    if (data.status === 'success') {
                        clearInterval(poll);
                        if (timerInterval) clearInterval(timerInterval);
                        showSuccess(data);
                    } else if (data.status === 'expired') {
                        clearInterval(poll);
                        if (timerInterval) clearInterval(timerInterval);
                        window.location.reload();
                    } else if (data.status === 'error') {
                        if (statusBox) {
                            statusBox.style.color = '#fca5a5';
                            statusText.innerText = data.message;
                        }
                    }
                })
                .catch(() => {
                    failCount++;
                    if (failCount >= 3) {
                        clearInterval(poll);
                        if (timerInterval) clearInterval(timerInterval);
                        statusText.innerText = 'Connection error. Please refresh.';
                    }
                });
        }, 3000);
    }

    function spawnConfetti() {
        const overlay = document.querySelector('.product-main');
        const colors = ['#2563eb','#60a5fa','#93c5fd','#dbeafe','#1d4ed8'];
        for (let i = 0; i < 22; i++) {
            const dot = document.createElement('div');
            const angle = Math.random() * 2 * Math.PI;
            const dist = 80 + Math.random() * 140;
            dot.style.cssText = `
                position:absolute; left:${40+Math.random()*20}%; top:${30+Math.random()*20}%;
                background:${colors[Math.floor(Math.random()*colors.length)]};
                width:${4+Math.random()*5}px; height:${4+Math.random()*5}px;
                border-radius:50%; z-index:99;
                --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;
            `;
            overlay.appendChild(dot);
        }
        setTimeout(() => overlay.querySelectorAll('div[style*="popConfetti"]').forEach(d => d.remove()), 2500);
    }

    function showSuccess(data) {
        document.querySelector('.product').classList.add('success-mode');
        if (statusBox) {
            statusBox.style.background = '#dcfce7';
            statusBox.style.color = '#16a34a';
            statusBox.style.borderColor = '#bbf7d0';
            statusBox.innerHTML = '<svg style="width:13px;height:13px;margin-right:2px" fill="none" stroke="currentColor" stroke-width="3" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"></path></svg> Payment received';
        }
        spawnConfetti();
        // Auto-redirect if merchant set a redirect_url
        if (redirectUrl) {
            setTimeout(() => {
                const sep = redirectUrl.includes('?') ? '&' : '?';
                window.location.href = redirectUrl + sep + 'order_id=' + encodeURIComponent(orderId) + '&status=success';
            }, 2500);
        }
    }

    const style = document.createElement('style');
    style.innerHTML = `
        @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); }
        }
    `;
    document.head.appendChild(style);
</script>
<?php endif; ?>
</body>
</html>
