<?php
// Prevent caching so the order status is always fresh on reload
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';

$amount = $_GET['amount'] ?? '';
$upi = $_GET['upi'] ?? '';
$orderId = $_GET['order_id'] ?? '';
$slug = $_GET['slug'] ?? '';

$errorMsg = '';
$user = null;
$isAlreadyPaid = false;
$isPaymentLink = false;

if ($slug) {
    // 0. Loading a custom Payment Link
    $link = getPaymentLinkBySlug($slug);
    if (!$link) {
        $errorMsg = 'Payment link not found.';
    } elseif ($link['status'] === 'expired' || $link['status'] === 'disabled' || ($link['status'] !== 'paid' && time() > $link['expires_at'])) {
        if ($link['status'] !== 'expired' && $link['status'] !== 'disabled') {
            updatePaymentLink($slug, 'expired');
        }
        $errorMsg = 'This payment link has expired or has been disabled by the merchant.';
        $user = getUserById($link['user_id']);
        if ($user) {
            // apiKey fetch removed for security
        }
    } else {
        $user = getUserById($link['user_id']);
        if (!$user) {
            $errorMsg = 'Merchant not found.';
        } else {
            if ($link['status'] === 'paid') {
                $isAlreadyPaid = true;
            }
            $amount = $link['amount'];
            $upi = $user['fampay_upi_id'];
            $orderId = 'LINK_' . $slug; // Use a virtual order ID for frontend polling
            $isPaymentLink = true;
            
            // Dummy order array to feed the frontend
            $order = [
                'order_id' => $orderId,
                'status' => $link['status'] === 'paid' ? 'success' : 'pending',
                'amount' => $amount,
                'payable_amount' => !empty((float)($link['payable_amount'] ?? 0)) ? $link['payable_amount'] : $amount,
                'upi_id' => $upi,
                'expires_at_timestamp' => $link['expires_at'],
                'created_at_timestamp' => $link['created_at']
            ];

            // apiKey fetch removed for security
        }
    }
} elseif ($orderId) {
    // 1. Loading an existing order
    $order = getOrderById($orderId);
    if (!$order) {
        $errorMsg = 'Order not found.';
    } elseif ($order['status'] === 'expired' || ($order['status'] !== 'success' && isset($order['expires_at_timestamp']) && time() > $order['expires_at_timestamp'])) {
        // Fix: server-side expiry check prevents rendering a stale QR
        if ($order['status'] !== 'expired') {
            updateOrder($orderId, ['status' => 'expired']);
        }
        $errorMsg = 'This payment link has expired. Please generate a new one.';
    } else {
        $user = getUserById($order['user_id']);
        if (!$user) {
            $errorMsg = 'Merchant not found.';
        } else {
            if ($order['status'] === 'success') {
                $isAlreadyPaid = true;
            }
            $amount = $order['amount'];
            $upi = $order['upi_id'];
            // apiKey fetch removed for security
        }
    }
} else {
    // 2. Creating orders via URL is no longer supported for security reasons
    $errorMsg = 'Invalid payment link or missing order ID.';
}

if (!$errorMsg) {
    $remainingSeconds = max(0, ($order['expires_at_timestamp'] ?? 0) - time());
    $initialH = floor($remainingSeconds / 3600);
    $initialM = str_pad(floor(($remainingSeconds % 3600) / 60), 2, '0', STR_PAD_LEFT);
    $initialS = str_pad($remainingSeconds % 60, 2, '0', STR_PAD_LEFT);
    if ($initialH > 0) {
        $initialTimerText = "Expires in $initialH:$initialM:$initialS";
    } else {
        $initialTimerText = "Expires in $initialM:$initialS";
    }

    // Use payable_amount (with unique decimal) for QR so IMAP matching is unambiguous
    $qrAmount = $order['payable_amount'] ?? $amount;
    $tn = "Payment for Order " . $orderId;
    $upiString = "upi://pay?pa=" . urlencode($upi) . "&pn=" . urlencode('FamPay') . "&tr=" . urlencode($orderId) . "&tn=" . urlencode($tn) . "&am=" . urlencode($qrAmount) . "&cu=INR";
    $qrUrl = "https://api.qrserver.com/v1/create-qr-code/?size=280x280&ecc=M&data=" . urlencode($upiString);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php 
$pageTitle = "Checkout | FamGateway";
$baseDir = "/";
include 'includes/header.php'; 
?>
<style>
    @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800&display=swap');
    
    :root { 
        --ink: #0f172a; 
        --ink-2: #1e293b; 
        --paper: #f0f4f8; /* Soft bg outside the card */
        --white: #ffffff; 
        --lime: #2563eb; 
        --lime-dark: #1d4ed8; 
        --muted: #64748b; 
        --dark-line: rgba(15,23,42,.12); 
    }
    
    * { box-sizing: border-box; margin:0; padding:0; }
    body {
        font-family: 'Poppins', Arial, sans-serif;
        background: var(--paper);
        color: var(--ink);
        min-height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 20px;
        -webkit-font-smoothing: antialiased;
    }

    /* Background Pattern like hero */
    body::before {
        content: ""; position: absolute; inset: 0; opacity: 0.4; pointer-events: none;
        background-image: linear-gradient(rgba(96,165,250,.4) 1px, transparent 1px), linear-gradient(90deg, rgba(96,165,250,.4) 1px, transparent 1px);
        background-size: 64px 64px; z-index: -1;
    }

    /* Product Mockup Window */
    .product { 
        background: #eff6ff; 
        border: 1px solid #93c5fd; 
        color: var(--ink); 
        box-shadow: 18px 19px 0 #60a5fa; 
        position: relative; 
        max-width: 440px; 
        width: 100%; 
        border-radius: 12px;
        animation: popIn 0.5s cubic-bezier(0.2, 0.8, 0.2, 1) forwards;
    }
    @keyframes popIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
    
    .product-head { 
        display: flex; justify-content: space-between; align-items: center; 
        padding: 15px 18px; border-bottom: 1px solid #bfdbfe; 
        font-size: 12px; font-weight: 700; 
        background: #dbeafe; border-radius: 12px 12px 0 0; 
    }
    .product-head span { color: #475569; font-weight: 600; letter-spacing: 0.5px; }
    .product-head .live-badge { color: #059669; display: flex; align-items: center; gap: 6px; }
    .product-head .live-badge i { width: 6px; height: 6px; background: #10b981; border-radius: 50%; box-shadow: 0 0 0 2px rgba(16,185,129,0.2); }
    
    .dots { display: flex; gap: 6px; }
    .dots i { width: 11px; height: 11px; border-radius: 50%; }
    .dots i:nth-child(1) { background: #ef4444; }
    .dots i:nth-child(2) { background: #eab308; }
    .dots i:nth-child(3) { background: #22c55e; }

    .product-main { padding: 28px; }
    
    .gateway-brand { display: flex; align-items: center; gap: 12px; margin-bottom: 24px; }
    .gateway-mark { 
        width: 38px; height: 38px; display: grid; place-items: center; 
        border-radius: 10px; background: #ffad00; color: #10151d; font-size: 18px; font-weight: 800;
    }
    .gateway-mark svg { width: 22px; height: 22px; fill: currentColor; }
    .gateway-brand b { display: block; font-size: 17px; line-height: 1; letter-spacing: -0.3px; }
    .gateway-brand small { display: block; margin-top: 4px; color: var(--muted); font-size: 10px; font-weight: 700; letter-spacing: 0.5px; text-transform: uppercase; }

    .product-label { font-size: 11px; font-weight: 700; letter-spacing: 0.8px; text-transform: uppercase; color: var(--muted); margin-bottom: 4px; }
    
    .money { margin: 0 0 24px; font-size: 46px; letter-spacing: -1.5px; font-weight: 800; color: var(--ink); line-height: 1; }
    .money small { color: var(--muted); font-size: 16px; letter-spacing: 0; font-weight: 600; margin-left: 4px; }

    .pay-card { 
        background: var(--white); border: 1px solid #dbeafe; padding: 20px; 
        border-radius: 16px; margin-bottom: 24px; box-shadow: 0 4px 12px rgba(37,99,235,0.04);
    }
    
    .qr-container { text-align: center; margin-bottom: 20px; }
    .qr-container img { width: 170px; height: 170px; border-radius: 8px; border: 1px solid #e2e8f0; padding: 8px; background: #fff; display: block; margin: 0 auto; }
    .qr-note { font-size: 11px; font-weight: 600; color: var(--muted); margin-top: 12px; text-transform: uppercase; letter-spacing: 0.5px; }

    .pay-row { display: flex; justify-content: space-between; align-items: center; padding: 12px 0; border-bottom: 1px solid #e2e8f0; font-size: 13px; }
    .pay-row:last-child { border: 0; padding-bottom: 0; }
    .pay-row:first-child { padding-top: 0; }
    .pay-row span { color: var(--muted); font-weight: 500; }
    .pay-row b { color: var(--ink); font-weight: 600; font-size: 13px; }

    .status { display: inline-flex; align-items: center; gap: 8px; font-size: 12px; 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; color: #ef4444; font-size: 13px; padding: 14px; border-radius: 12px; font-weight: 500; text-align: left; }

    /* Premium Success Animation */
    .success-container { display: none; text-align: center; padding: 25px 0 10px; }
    .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; }

    @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) {
        .product { box-shadow: 10px 10px 0 #60a5fa; margin: 20px auto; }
        .product-main { padding: 20px; }
        .money { font-size: 38px; }
    }
</style>
</head>
<body>

<div class="product">
  <?php if ($errorMsg): ?>
  <div class="product-main">
    <div class="gateway-brand">
      <span class="gateway-mark" style="background:#ef4444; color:#fff;">!</span>
      <span><b>Payment Error</b><small>Checkout halted</small></span>
    </div>
    <div class="error-box"><?= htmlspecialchars($errorMsg) ?></div>
    <?php if (!empty($user['support_link'])): ?>
    <div style="margin-top: 20px; text-align: center; border-top: 1px dashed #bfdbfe; padding-top: 16px;">
        <span style="color:#64748b; font-size:12px; display:block; margin-bottom:8px;">Need help?</span>
        <a href="<?= htmlspecialchars($user['support_link']) ?>" target="_blank" style="background:#eff6ff; color:#2563eb; font-weight:600; text-decoration:none; font-size:13px; padding:10px 16px; border-radius:8px; display:inline-flex; align-items:center; gap:6px; border:1px solid #bfdbfe;">
            Contact Merchant Support
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="width:14px; height:14px;"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>
        </a>
    </div>
    <?php endif; ?>
  </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;display:block;object-fit:contain;">
    </div>
    
    <div class="product-label">Order total</div>
    <div class="money">₹ <?= htmlspecialchars($order['payable_amount'] ?? $amount) ?> <small>INR</small></div>
    
    <div class="pay-card">
      <div class="qr-container">
        <img id="qr" src="<?= htmlspecialchars($qrUrl) ?>" alt="QR Code">
        <div class="qr-note">Scan with any UPI app</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>
        <p id="redirectText" style="color:#3b82f6; font-size:13px; font-weight:600; margin-top: 15px; display: none; background: #eff6ff; padding: 8px; border-radius: 8px; border: 1px solid #bfdbfe;"></p>
      </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><?= htmlspecialchars($isPaymentLink ? $slug : $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>
      <?php if (!empty($user['support_link'])): ?>
      <div class="pay-row" style="border-top: 1px dashed #e2e8f0; margin-top: 12px; padding-top: 16px; padding-bottom: 4px;">
        <span>Need help?</span>
        <a href="<?= htmlspecialchars($user['support_link']) ?>" target="_blank" style="color: #2563eb; font-weight: 600; text-decoration: none; font-size: 13px; display: inline-flex; align-items: center; gap: 4px;">
            Contact Support
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="width:12px; height:12px;"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>
        </a>
      </div>
      <?php endif; ?>
    </div>
  </div>
  <?php endif; ?>
</div>


<?php if (!$errorMsg): ?>
<script>
    const orderId = <?= json_encode($orderId) ?>;
    const isAlreadyPaid = <?= json_encode($isAlreadyPaid) ?>;
    let remainingSeconds = <?= intval($remainingSeconds ?? 0) ?>;
    const statusBox = document.getElementById('statusBox');
    const statusText = document.getElementById('statusText');
    const timerText = document.getElementById('timerText');
    const spinner = document.getElementById('spinner');

    const baseUrl = <?= json_encode(getBaseUrl()) ?>;
    let timerInterval = null;
    let poll = null;
    let failCount = 0;
    
    if (isAlreadyPaid) {
        showSuccess();
    } else {
        if (remainingSeconds > 0) {
            timerInterval = setInterval(() => {
                remainingSeconds--;
                if (remainingSeconds <= 0) {
                    clearInterval(timerInterval);
                    if (timerText) timerText.innerText = 'Expired';
                } else {
                    const h = Math.floor(remainingSeconds / 3600);
                    const m = Math.floor((remainingSeconds % 3600) / 60).toString().padStart(2, '0');
                    const s = (remainingSeconds % 60).toString().padStart(2, '0');
                    if (timerText) {
                        if (h > 0) {
                            timerText.innerText = `Expires in ${h}:${m}:${s}`;
                        } else {
                            timerText.innerText = `Expires in ${m}:${s}`;
                        }
                    }
                }
            }, 1000);
        }

        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') {
                        spinner.style.display = 'none';
                        statusBox.style.color = '#fca5a5';
                        statusText.innerText = data.message;
                    }
                })
                .catch((err) => {
                    // Surface IMAP/server errors instead of silently retrying forever
                    failCount = failCount + 1;
                    if (failCount >= 3) {
                        clearInterval(poll);
                        if (timerInterval) clearInterval(timerInterval);
                        if (timerText) timerText.style.display = 'none';
                        spinner.style.display = 'none';
                        statusBox.style.color = '#fca5a5';
                        statusText.innerText = 'Connection error. Please refresh the page.';
                    }
                });
        }, 1500);
    }

    function spawnConfetti() {
        const overlay = document.querySelector('.product-main');
        const colors = ['#2563eb','#60a5fa','#93c5fd','#dbeafe','#1d4ed8','#bfdbfe'];
        for (let i = 0; i < 22; i++) {
            const dot = document.createElement('div');
            dot.className = 'confetti-dot';
            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;
                transform: translate(var(--tx), var(--ty));
                --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('.confetti-dot').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;margin-top:-1px" 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();

        // Only redirect if this is an API order with a valid redirect URL
        const redirectUrl = "<?= (!empty($order['redirect_url']) && empty($isPaymentLink)) ? htmlspecialchars($order['redirect_url']) : '' ?>";
        
        if (redirectUrl) {
            let redirectSeconds = 5;
            const redirectTextEl = document.getElementById('redirectText');
            redirectTextEl.style.display = 'block';
            redirectTextEl.innerText = `Redirecting back to merchant in ${redirectSeconds} seconds...`;
            
            const rInt = setInterval(() => {
                redirectSeconds--;
                if (redirectSeconds <= 0) {
                    clearInterval(rInt);
                    redirectTextEl.innerText = `Redirecting now...`;
                    window.location.href = redirectUrl;
                } else {
                    redirectTextEl.innerText = `Redirecting back to merchant in ${redirectSeconds} seconds...`;
                }
            }, 1000);
        }
    }
    
    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; ?>

<?php if ($errorMsg && !empty($slug)): ?>
<script>
    // Background listener on Error Screen to auto-restore QR page when merchant clicks Unexpire
    const baseUrl = <?= json_encode(getBaseUrl()) ?>;
    const slug = <?= json_encode($slug) ?>;

    setInterval(() => {
        fetch(baseUrl + '/api/checkout-status.php?order_id=LINK_' + encodeURIComponent(slug))
            .then(res => res.json())
            .then(data => {
                if (data.status === 'pending' || data.status === 'success') {
                    window.location.reload();
                }
            })
            .catch(() => {});
    }, 1500);
</script>
<?php endif; ?>
</body>
</html>
