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

$adminSettings = getAdminSettings();
$quickMode = isset($_GET['quick']);
$amountParam = $_GET['amount'] ?? null;

$showAmountForm = ($amountParam === null && !$quickMode);
$demoAmount = null;

if ($quickMode) {
    $demoAmount = floatval($adminSettings['demo_amount']);
} elseif ($amountParam !== null && is_numeric($amountParam) && floatval($amountParam) > 0) {
    $demoAmount = floatval($amountParam);
}

$shareLink = '';
if ($demoAmount !== null) {
    $shareLink = getBaseUrl() . '/demo.php?amount=' . urlencode((string) $demoAmount);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Test Payment Demo - AdityaHost</title>
<link rel="icon" href="favicon.ico" sizes="any">
<link rel="icon" href="favicon-32x32.png" type="image/png" sizes="32x32">
<link rel="apple-touch-icon" href="apple-touch-icon.png" sizes="180x180">
<style>
:root{--dm-blue:#3b82f6;--dm-blue-light:#eff6ff;--dm-blue-dark:#1e40af;--dm-ink:#1e293b;--dm-muted:#64748b;--dm-line:#e2e8f0;--dm-green:#16a34a;--dm-green-bg:#f0fdf4;--dm-green-border:#bbf7d0;--dm-red:#dc2626;--dm-red-bg:#fef2f2;--dm-red-border:#fecaca;--dm-mono:'SF Mono','Cascadia Code','Fira Code',monospace}
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:#f0f4f8;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:32px 16px}
.dm-wrap{width:100%;max-width:400px;display:flex;flex-direction:column;align-items:center}
.dm-card{width:100%;background:#fff;border-left:4px solid var(--dm-blue);border-radius:16px;box-shadow:0 4px 24px rgba(0,0,0,.06),0 1px 4px rgba(0,0,0,.04);padding:32px 28px;text-align:center}
.dm-brand{display:flex;align-items:center;justify-content:center;gap:10px;margin-bottom:28px}
.dm-brand img{width:32px;height:32px;border-radius:8px}
.dm-brand-name{font-size:18px;font-weight:700;color:var(--dm-ink);letter-spacing:-.3px}
.dm-brand-name span{color:var(--dm-blue)}
.dm-eyebrow{font-size:11px;font-weight:700;letter-spacing:1.6px;text-transform:uppercase;color:var(--dm-blue);margin-bottom:8px}
.dm-title{font-size:26px;font-weight:800;color:var(--dm-ink);letter-spacing:-.02em;margin-bottom:8px}
.dm-sub{font-size:14px;color:var(--dm-muted);margin:0 auto 24px;max-width:340px;line-height:1.5}
.dm-amount-display{font-size:40px;font-weight:800;color:var(--dm-ink);font-family:var(--dm-mono);letter-spacing:-1.5px;margin-bottom:8px}
.dm-amount-display .dm-cur{font-size:22px;color:var(--dm-muted);font-weight:700;margin-right:2px}
.dm-input{width:100%;padding:13px 16px;border:1.5px solid var(--dm-line);border-radius:10px;font-size:15px;color:var(--dm-ink);background:#fff;outline:none;transition:border .15s}
.dm-input:focus{border-color:var(--dm-blue);box-shadow:0 0 0 3px rgba(59,130,246,.12)}
.dm-btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;width:100%;padding:13px 24px;border-radius:12px;font-weight:700;font-size:14px;border:0;cursor:pointer;transition:all .15s;text-decoration:none;text-align:center}
.dm-btn-primary{background:var(--dm-blue);color:#fff;box-shadow:0 4px 12px rgba(59,130,246,.3)}
.dm-btn-primary:hover{transform:translateY(-1px);box-shadow:0 6px 16px rgba(59,130,246,.4)}
.dm-btn-secondary{background:#f1f5f9;color:var(--dm-ink);border:1.5px solid var(--dm-line)}
.dm-btn-secondary:hover{background:#e2e8f0}
.dm-grid-2{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:16px}
.dm-divider{height:1px;background:var(--dm-line);margin:20px 0}
.dm-qr-wrap{width:220px;height:220px;margin:0 auto 8px;padding:12px;border:2px solid var(--dm-line);border-radius:16px;background:#fff}
.dm-qr-img{width:100%;height:100%;object-fit:contain;display:block}
.dm-qr-hint{font-size:12px;font-weight:600;color:var(--dm-muted);margin:0 0 20px;letter-spacing:.3px}
.dm-details{text-align:left;border:1px solid var(--dm-line);border-radius:12px;overflow:hidden;margin-bottom:20px}
.dm-row{display:flex;justify-content:space-between;align-items:center;padding:12px 16px;font-size:13px;border-bottom:1px solid var(--dm-line)}
.dm-row:last-child{border-bottom:none}
.dm-row:hover{background:#f8fafc}
.dm-row-label{color:var(--dm-muted);font-weight:500}
.dm-row-value{color:var(--dm-ink);font-weight:700;text-align:right}
.dm-status{display:inline-flex;align-items:center;gap:8px;padding:10px 20px;border-radius:10px;background:var(--dm-blue-light);border:1px solid #bfdbfe;font-size:13px;font-weight:700;color:var(--dm-blue-dark)}
.dm-status .dm-dot{width:8px;height:8px;border-radius:50%;background:var(--dm-blue);animation:dm-pulse 1.5s ease-in-out infinite;box-shadow:0 0 0 0 rgba(59,130,246,.4)}
.dm-pill{display:inline-flex;align-items:center;gap:7px;padding:6px 14px;border-radius:999px;font-size:12.5px;font-weight:600;background:var(--dm-blue-light);color:var(--dm-blue);border:1px solid #bfdbfe}
.dm-pill .dm-dot{width:7px;height:7px;border-radius:50%;background:var(--dm-blue);animation:dm-pulse 1.6s infinite}
.dm-pill.ok{background:var(--dm-green-bg);color:var(--dm-green);border-color:var(--dm-green-border)}
.dm-pill.ok .dm-dot{background:var(--dm-green);animation:none}
.dm-footer{font-size:11.5px;color:var(--dm-muted);text-align:center;margin-top:20px;opacity:.7}
.dm-footer b{font-weight:700;color:var(--dm-ink)}
@keyframes dm-pulse{0%,100%{box-shadow:0 0 0 0 rgba(59,130,246,.4)}50%{box-shadow:0 0 0 6px rgba(59,130,246,0)}}
.dm-overlay{position:fixed;inset:0;background:rgba(0,0,0,.55);display:flex;align-items:center;justify-content:center;z-index:1000;opacity:0;pointer-events:none;transition:opacity .3s}
.dm-overlay.active{opacity:1;pointer-events:auto}
.dm-success-card{background:#fff;border-radius:20px;padding:40px 32px;text-align:center;max-width:380px;width:90%;box-shadow:0 20px 60px rgba(0,0,0,.2);transform:scale(.9);transition:transform .35s cubic-bezier(.175,.885,.32,1.275)}
.dm-overlay.active .dm-success-card{transform:scale(1)}
.dm-success-circle{width:72px;height:72px;border-radius:50%;background:var(--dm-green);display:grid;place-items:center;margin:0 auto 18px;animation:dm-pop .5s cubic-bezier(.175,.885,.32,1.275) forwards;box-shadow:0 8px 24px rgba(22,163,74,.3)}
.dm-success-circle svg{width:36px;height:36px;color:#fff;stroke-dasharray:50;stroke-dashoffset:50;animation:dm-draw .5s ease-out .25s forwards}
.dm-success-title{font-size:22px;font-weight:800;color:var(--dm-green);margin:0 0 6px}
.dm-success-amount{font-size:40px;font-weight:800;color:var(--dm-ink);font-family:var(--dm-mono);letter-spacing:-1px;margin:0 0 18px}
.dm-utr-box{display:flex;align-items:center;justify-content:center;gap:10px;background:var(--dm-green-bg);border:1.5px solid var(--dm-green-border);border-radius:12px;padding:14px 16px;margin-bottom:20px}
.dm-utr-box small{font-size:10px;font-weight:800;letter-spacing:1.2px;text-transform:uppercase;color:var(--dm-green)}
.dm-utr-box b{font-family:var(--dm-mono);font-size:16px;color:var(--dm-ink);letter-spacing:.5px}
.dm-utr-box button{background:var(--dm-green);border:0;color:#fff;font-size:11px;font-weight:800;padding:6px 14px;border-radius:8px;cursor:pointer;transition:all .15s;letter-spacing:.5px}
.dm-utr-box button:hover{background:#15803d;transform:scale(1.05)}
.dm-success-sub{font-size:13px;color:var(--dm-muted);margin-bottom:20px;line-height:1.5}
@keyframes dm-pop{0%{transform:scale(0);opacity:0}100%{transform:scale(1);opacity:1}}
@keyframes dm-draw{to{stroke-dashoffset:0}}
</style>
</head>
<body>

<div class="dm-wrap">
<div class="dm-card">
  <?php if ($showAmountForm): ?>
    <div class="dm-brand">
      <img src="assets/img/logo.png" alt="AdityaHost">
      <span class="dm-brand-name">Aditya<span>Host</span></span>
    </div>
    <div class="dm-eyebrow">LIVE TEST</div>
    <h1 class="dm-title">Try a test payment</h1>
    <p class="dm-sub">Enter any amount to generate a real UPI QR and see how payment confirmation works.</p>
    <form method="GET" action="demo.php" style="text-align:left">
      <input type="hidden" name="showlink" value="1">
      <label for="amount" style="display:block;font-size:13px;font-weight:600;color:var(--dm-ink);margin-bottom:6px">Amount (₹)</label>
      <input class="dm-input" type="number" id="amount" name="amount" placeholder="e.g. 1, 50, 100..." min="0.01" step="0.01" required autofocus>
      <button type="submit" class="dm-btn dm-btn-primary" style="margin-top:20px">Generate test link</button>
    </form>
    <div class="dm-divider"></div>
    <a href="index.php" class="dm-btn dm-btn-secondary">Back to Home</a>

  <?php elseif ($demoAmount === null): ?>
    <div class="dm-brand">
      <img src="assets/img/logo.png" alt="AdityaHost">
      <span class="dm-brand-name">Aditya<span>Host</span></span>
    </div>
    <div class="dm-eyebrow">OOPS</div>
    <h1 class="dm-title">Invalid amount</h1>
    <p class="dm-sub">Please enter a valid amount greater than 0.</p>
    <a href="demo.php" class="dm-btn dm-btn-primary">Try Again</a>

  <?php elseif (!empty($_GET['showlink'])): ?>
    <div class="dm-brand">
      <img src="assets/img/logo.png" alt="AdityaHost">
      <span class="dm-brand-name">Aditya<span>Host</span></span>
    </div>
    <div class="dm-eyebrow">TEST LINK READY</div>
    <h1 class="dm-title">Your test link</h1>
    <div class="dm-amount-display"><span class="dm-cur">₹</span><?= htmlspecialchars(number_format($demoAmount, 2)) ?></div>
    <p class="dm-sub">Copy this link to test on another device, or open it now to scan the QR.</p>
    <input class="dm-input" type="text" id="shareLinkInput" value="<?= htmlspecialchars($shareLink) ?>" readonly onclick="this.select();">
    <div class="dm-grid-2">
      <button class="dm-btn dm-btn-secondary" onclick="copyShareLink()">Copy Link</button>
      <a href="<?= htmlspecialchars($shareLink) ?>" target="_blank" rel="noopener" class="dm-btn dm-btn-primary">Open Link ↗</a>
    </div>

  <?php else: ?>
    <div class="dm-brand">
      <img src="assets/img/logo.png" alt="AdityaHost">
      <span class="dm-brand-name">Aditya<span>Host</span></span>
    </div>
    <div class="dm-eyebrow">LIVE TEST</div>
    <h1 class="dm-title" style="margin-bottom:4px">Test payment</h1>
    <div style="font-size:11px;font-weight:700;letter-spacing:1.6px;text-transform:uppercase;color:#94a3b8;margin-bottom:6px">Order Total</div>
    <div class="dm-amount-display" style="margin-bottom:16px"><span class="dm-cur">₹</span><?= htmlspecialchars(number_format($demoAmount, 2)) ?></div>

    <div class="dm-qr-wrap">
      <img class="dm-qr-img" id="demoQrImage" src="" alt="Loading QR...">
    </div>
    <div class="dm-qr-hint">SCAN WITH ANY UPI APP</div>

    <div class="dm-details">
      <div class="dm-row">
        <span class="dm-row-label">Merchant</span>
        <b class="dm-row-value">AdityaHost</b>
      </div>
      <div class="dm-row">
        <span class="dm-row-label">Status</span>
        <b class="dm-row-value">
          <span class="dm-pill" id="demoStatusPill">
            <span class="dm-dot"></span>
            <span id="demoStatus">Generating QR…</span>
          </span>
        </b>
      </div>
    </div>

    <a href="demo.php" class="dm-btn dm-btn-secondary" style="margin-top:20px">Try a different amount</a>
  <?php endif; ?>
</div>

<div class="dm-footer">Powered by <b>AdityaHost FamAPI</b></div>
</div>

<div class="dm-overlay" id="successOverlay">
  <div class="dm-success-card">
    <div class="dm-success-circle">
      <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="dm-success-title">Payment successful!</h2>
    <div class="dm-success-amount" id="successAmountText">₹0</div>
    <div class="dm-utr-box">
      <small>UTR</small>
      <b id="successUtrText">——————</b>
      <button onclick="copyDemoUtr()" id="demoUtrBtn">COPY</button>
    </div>
    <p class="dm-success-sub" id="successMetaText">This confirms your FamAPI gateway is working correctly.</p>
    <button class="dm-btn dm-btn-primary" style="width:auto;display:inline-flex" onclick="window.location.href='demo.php'">Run another test</button>
  </div>
</div>

<script>
function copyShareLink(){var i=document.getElementById('shareLinkInput');i.select();i.setSelectionRange(0,99999);navigator.clipboard?navigator.clipboard.writeText(i.value).then(function(){alert('Link copied!')}).catch(function(){document.execCommand('copy');alert('Link copied!')}):(document.execCommand('copy'),alert('Link copied!'));}

<?php if (!$showAmountForm && $demoAmount !== null && empty($_GET['showlink'])): ?>
var demoPollInterval=null;
fetch('api/create_demo_order.php',{method:'POST',body:new URLSearchParams({amount:<?= json_encode((string)$demoAmount) ?>})}).then(function(r){return r.json()}).then(function(d){if(d.status==='success'){document.getElementById('demoQrImage').src=d.data.qr_url;document.getElementById('demoStatus').innerText='Waiting for payment';pollDemoOrder(d.data.order_id)}else{document.getElementById('demoStatus').innerText='⚠ '+(d.message||'Could not generate QR')}}).catch(function(){document.getElementById('demoStatus').innerText='Connection error'});

function pollDemoOrder(orderId){demoPollInterval=setInterval(function(){fetch('api/check_demo_order.php',{method:'POST',body:new URLSearchParams({order_id:orderId})}).then(function(r){return r.json()}).then(function(d){if(d.status==='success'){clearInterval(demoPollInterval);showSuccessAnimation(d.data||{})}else if(d.status==='error'){document.getElementById('demoStatus').innerText='⚠ '+d.message}}).catch(function(){})},1200);}
<?php endif; ?>

function showSuccessAnimation(d){var amt=parseFloat(d.amount||<?= json_encode($demoAmount??1) ?>);document.getElementById('successAmountText').innerText='₹'+amt.toFixed(2);document.getElementById('successUtrText').innerText=d.utr||'N/A';var m=[];if(d.sender_name)m.push('Paid by '+d.sender_name);if(d.payment_time_ist)m.push(d.payment_time_ist);document.getElementById('successMetaText').innerText=m.length?m.join(' · '):'This confirms your FamAPI gateway is working correctly.';document.getElementById('successOverlay').classList.add('active');}

function copyDemoUtr(){var u=document.getElementById('successUtrText').textContent,b=document.getElementById('demoUtrBtn'),done=function(){b.textContent='COPIED ✓';setTimeout(function(){b.textContent='COPY'},1800)};if(navigator.clipboard){navigator.clipboard.writeText(u).then(done).catch(done)}else{done();}}
</script>
</body>
</html>
