<?php
require_once '../config/database.php';
require_once '../includes/functions.php';

if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['user_id'])) { redirect('../login.php'); }

$userId = $_SESSION['user_id'];
$conn   = getConnection();

$checkoutRequestID = $_SESSION['checkout_request_id'] ?? null;
if (!$checkoutRequestID) {
    if (isset($_SESSION['paying_for_user_id'])) { redirect('pay_for_client.php'); }
    else { redirect('activate.php'); }
}

$isClientActivation = isset($_SESSION['paying_for_user_id']);
$payingForUserId    = $_SESSION['paying_for_user_id']  ?? null;
$payingForUsername  = $_SESSION['paying_for_username'] ?? null;

require_once '../mpesa/stk_push.php';

$transactionStatus = checkTransactionStatus($checkoutRequestID);
$txStatus   = $transactionStatus['found'] ? $transactionStatus['status'] : 'pending';
$failReason = $transactionStatus['reason'] ?? '';

if ($txStatus === 'failed') {
    if (in_array($failReason, ['cancelled_by_user','cancelled','timeout'])) {
        $txStatus = 'cancelled';
    }
}

if ($txStatus === 'pending') {
    $createdAt = $transactionStatus['created_at'] ?? null;
    if (!$createdAt) {
        $tsStmt = $conn->prepare("SELECT created_at FROM transactions WHERE reference=? LIMIT 1");
        $tsStmt->bind_param("s", $checkoutRequestID); $tsStmt->execute();
        $tsRow = $tsStmt->get_result()->fetch_assoc();
        $createdAt = $tsRow['created_at'] ?? null;
    }
    if ($createdAt && (time() - strtotime($createdAt)) > 180) {
        $expMeta = json_encode(['reason'=>'timeout','expired_at'=>date('Y-m-d H:i:s')]);
        $expStmt = $conn->prepare("UPDATE transactions SET status='failed', meta_json=? WHERE reference=? AND status='pending'");
        $expStmt->bind_param("ss", $expMeta, $checkoutRequestID); $expStmt->execute();
        $txStatus = 'cancelled'; $failReason = 'timeout';
        unset($_SESSION['checkout_request_id']);
    }
}

if ($txStatus === 'completed') {
    $targetId   = ($isClientActivation && $payingForUserId) ? $payingForUserId : $userId;
    $updateStmt = $conn->prepare("UPDATE users SET status='active' WHERE id=?");
    $updateStmt->bind_param("i", $targetId); $updateStmt->execute();
    if ($isClientActivation) { unset($_SESSION['paying_for_user_id'], $_SESSION['paying_for_username']); }
    unset($_SESSION['checkout_request_id']);
}

if (in_array($txStatus, ['cancelled','failed','cancelled_by_user','timeout'])) {
    unset($_SESSION['checkout_request_id']);
}

$adminPrimary = getSetting('theme_color',   '#00e5ff');
$adminSuccess = getSetting('success_color', '#22c55e');
$adminWarning = getSetting('warning_color', '#f59e0b');
$adminDanger  = getSetting('danger_color',  '#ef4444');

function toRgb($hex) {
    $hex = ltrim($hex, '#');
    if (strlen($hex) === 3) $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
    return hexdec(substr($hex,0,2)).','.hexdec(substr($hex,2,2)).','.hexdec(substr($hex,4,2));
}
$pRgb = toRgb($adminPrimary);

$siteName      = getSiteName();
$siteLogo      = getSetting('site_logo', '');
$hasCustomLogo = !empty($siteLogo) && file_exists('../uploads/logos/'.$siteLogo);

$isPending   = $txStatus === 'pending';
$isCompleted = $txStatus === 'completed';
$isFailed    = $txStatus === 'failed';
$isCancelled = in_array($txStatus, ['cancelled','cancelled_by_user','timeout'])
            || in_array($failReason, ['cancelled_by_user','cancelled','timeout']);
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
<title>Activation Status — <?php echo htmlspecialchars($siteName); ?></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
<style>
:root {
    --P:  <?php echo $adminPrimary; ?>;
    --OK: #22c55e;
    --WN: #f59e0b;
    --DN: #ef4444;
    --Pr: <?php echo $pRgb; ?>;
}
:root,[data-theme="dark"]{
    --bg1:#07060f;--bg2:#0e0c1a;--bg3:#141228;
    --bdr:rgba(255,255,255,0.07);--bdr-p:rgba(var(--Pr),0.22);
    --txt:rgba(255,255,255,0.90);--txt2:rgba(255,255,255,0.50);--txt3:rgba(255,255,255,0.22);
    --P-bg:rgba(var(--Pr),0.10);--OK-bg:rgba(34,197,94,0.10);--WN-bg:rgba(245,158,11,0.10);--DN-bg:rgba(239,68,68,0.12);
    --card:#0e0c1a;--card2:#141228;--shadow:0 4px 24px rgba(0,0,0,0.5);
    color-scheme:dark;
}
[data-theme="light"]{
    --bg1:#f4f4f6;--bg2:#ffffff;--bg3:#f4f4f6;
    --bdr:rgba(0,0,0,0.09);--bdr-p:rgba(var(--Pr),0.30);
    --txt:#111118;--txt2:#5a5a72;--txt3:#9898b0;
    --P-bg:rgba(var(--Pr),0.08);--OK-bg:rgba(22,163,74,0.08);--WN-bg:rgba(180,120,0,0.08);--DN-bg:rgba(200,30,80,0.08);
    --card:#ffffff;--card2:#f4f4f6;--shadow:0 2px 16px rgba(0,0,0,0.08);
    color-scheme:light;
}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
html,body{height:100%}
body{
    font-family:system-ui,-apple-system,'Segoe UI',sans-serif;
    font-size:13px;color:var(--txt);background:var(--bg1);
    -webkit-font-smoothing:antialiased;min-height:100vh;
    display:flex;flex-direction:column;align-items:center;justify-content:center;
    padding:20px 14px;position:relative;overflow-x:hidden;
    transition:background .25s,color .25s;
}
::-webkit-scrollbar{width:4px}
::-webkit-scrollbar-thumb{background:rgba(var(--Pr),.25);border-radius:4px}

[data-theme="dark"] body::before{
    content:'';position:fixed;inset:0;z-index:0;pointer-events:none;
    background-image:linear-gradient(rgba(var(--Pr),.04) 1px,transparent 1px),linear-gradient(90deg,rgba(var(--Pr),.04) 1px,transparent 1px);
    background-size:40px 40px;
    mask-image:radial-gradient(ellipse 80% 80% at 50% 50%,black 30%,transparent 100%);
    animation:gridPulse 8s ease-in-out infinite alternate;
}
@keyframes gridPulse{from{opacity:.4}to{opacity:.9}}
[data-theme="dark"] body::after{
    content:'';position:fixed;inset:0;z-index:0;pointer-events:none;
    background:radial-gradient(ellipse 60% 40% at 20% 20%,rgba(var(--Pr),.07) 0%,transparent 60%),radial-gradient(ellipse 50% 35% at 80% 75%,rgba(var(--Pr),.05) 0%,transparent 55%);
}

.theme-btn{position:fixed;top:12px;right:12px;z-index:999;width:36px;height:36px;border-radius:9px;background:var(--card);border:1px solid var(--bdr);cursor:pointer;color:var(--txt2);display:flex;align-items:center;justify-content:center;font-size:13px;transition:all .18s}
.theme-btn:hover{color:var(--P);border-color:var(--bdr-p);background:var(--P-bg)}

/* ── CARD ── */
.card{width:100%;max-width:400px;background:var(--card);border:1px solid var(--bdr);border-radius:18px;padding:24px 20px 20px;box-shadow:var(--shadow);position:relative;z-index:1;text-align:center;transition:background .25s,border-color .25s;animation:cardIn .55s cubic-bezier(.34,1.56,.64,1) both}
[data-theme="dark"] .card{border-color:rgba(var(--Pr),.14)}

/* Card entry — overshoot bounce */
@keyframes cardIn{
    0%  {opacity:0;transform:translateY(28px) scale(.96)}
    60% {opacity:1;transform:translateY(-4px)  scale(1.01)}
    80% {transform:translateY(2px) scale(.995)}
    100%{transform:translateY(0)   scale(1)}
}
.card::before{content:'';position:absolute;top:0;left:10%;right:10%;height:1px;background:linear-gradient(90deg,transparent,rgba(var(--Pr),.5),transparent)}

/* ── BRAND ── */
.brand-row{display:flex;align-items:center;gap:10px;margin-bottom:14px;text-align:left}
.brand-ring{width:36px;height:36px;flex-shrink:0;border-radius:50%;border:2.5px solid var(--P);display:flex;align-items:center;justify-content:center;box-shadow:0 0 12px rgba(var(--Pr),.35);animation:ringSpín 8s linear infinite}
@keyframes ringSpín{to{filter:hue-rotate(360deg)}}
.brand-dot{width:9px;height:9px;border-radius:50%;background:var(--P)}
.brand-logo-img{width:100%;height:100%;border-radius:50%;object-fit:cover}
.brand-name{font-size:15px;font-weight:800;color:var(--txt);letter-spacing:.3px}
.brand-sub{font-size:10px;color:var(--txt2);font-weight:600;letter-spacing:.5px}
.brand-divider{height:1px;margin:0 0 20px;background:linear-gradient(90deg,transparent,rgba(var(--Pr),.35),transparent)}

/* ── STATUS ICON WRAP ── */
.status-wrap{width:72px;height:72px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;margin-bottom:14px;font-size:28px;position:relative}
.status-wrap.pending  {background:var(--P-bg); color:var(--P) }
.status-wrap.success  {background:var(--OK-bg);color:var(--OK)}
.status-wrap.failed   {background:var(--DN-bg);color:var(--DN)}
.status-wrap.cancelled{background:var(--WN-bg);color:var(--WN)}

/* Ripple ring — starts slightly inward, fades out as it expands */
.status-wrap::before{
    content:'';position:absolute;inset:-6px;border-radius:50%;
    border:2px solid currentColor;opacity:0;
    animation:rippleRing 2.2s ease-out infinite;
}
@keyframes rippleRing{
    0%  {transform:scale(.85);opacity:.5}
    50% {opacity:.2}
    100%{transform:scale(1.5);opacity:0}
}

/* ── SUCCESS — cinematic scale-in + rotation overshoot ── */
.anim-success{
    animation:successPop .55s cubic-bezier(.34,1.7,.64,1) both;
}
@keyframes successPop{
    0%  {transform:scale(0) rotate(-20deg);opacity:0}
    60% {transform:scale(1.18) rotate(6deg);opacity:1}
    80% {transform:scale(.94) rotate(-2deg)}
    100%{transform:scale(1)   rotate(0)}
}
/* Second radiating ring only on success */
.status-wrap.success::after{
    content:'';position:absolute;inset:-14px;border-radius:50%;
    border:2px solid var(--OK);opacity:0;
    animation:successRing2 1.8s ease-out .25s infinite;
}
@keyframes successRing2{
    0%  {transform:scale(.8);opacity:.45}
    100%{transform:scale(1.75);opacity:0}
}

/* ── PENDING — smooth morphing orbit (no CSS spin choppiness) ── */
.anim-pending{
    animation:orbitPulse 1.6s cubic-bezier(.45,0,.55,1) infinite;
}
@keyframes orbitPulse{
    0%  {transform:rotate(0deg)   scale(1);   opacity:1}
    25% {transform:rotate(90deg)  scale(1.1); opacity:.8}
    50% {transform:rotate(180deg) scale(1);   opacity:1}
    75% {transform:rotate(270deg) scale(1.1); opacity:.8}
    100%{transform:rotate(360deg) scale(1);   opacity:1}
}
/* Breathing glow on pending wrap */
.status-wrap.pending{
    animation:pendingBreath 2.6s ease-in-out infinite;
}
@keyframes pendingBreath{
    0%,100%{box-shadow:0 0 0 0 rgba(var(--Pr),.3),  0 0 0 7px  rgba(var(--Pr),.1)}
    50%    {box-shadow:0 0 0 4px rgba(var(--Pr),.2), 0 0 0 16px rgba(var(--Pr),.05)}
}

/* ── CANCELLED — gravity drop from above with skid landing ── */
.anim-cancelled{
    animation:gravityDrop .65s cubic-bezier(.55,-.5,.65,1.4) both;
}
@keyframes gravityDrop{
    0%  {transform:translateY(-28px) rotate(15deg)  scale(.7); opacity:0}
    55% {transform:translateY(5px)   rotate(-5deg)  scale(1.04);opacity:1}
    75% {transform:translateY(-3px)  rotate(2deg)   scale(.98)}
    100%{transform:translateY(0)     rotate(0)      scale(1);  opacity:1}
}

/* ── FAILED — electric flash + persistent micro-jitter ── */
.anim-failed{
    animation:
        electricFlash .5s ease both,
        jitter 3.5s ease-in-out .6s infinite;
}
@keyframes electricFlash{
    0%  {transform:scale(1.25);opacity:0;filter:brightness(4)}
    15% {transform:scale(.85); opacity:1;filter:brightness(2.5)}
    30% {transform:scale(1.12);          filter:brightness(1.8)}
    50% {transform:scale(.96);           filter:brightness(1.3)}
    70% {transform:scale(1.04);          filter:brightness(1.1)}
    100%{transform:scale(1);            filter:brightness(1)}
}
@keyframes jitter{
    0%,88%,100%{transform:translate(0,0)   rotate(0)}
    90%        {transform:translate(-3px,1px) rotate(-.6deg)}
    92%        {transform:translate(3px,-1px) rotate(.6deg)}
    94%        {transform:translate(-2px,2px) rotate(0)}
    96%        {transform:translate(2px,-2px)}
    98%        {transform:translate(-1px,1px)}
}

/* ── STATUS TITLE & MSG ── */
.status-title{font-size:18px;font-weight:800;margin-bottom:8px;letter-spacing:-.3px}
.status-title.pending  {color:var(--P) }
.status-title.success  {color:var(--OK)}
.status-title.failed   {color:var(--DN)}
.status-title.cancelled{color:var(--WN)}
.status-msg{font-size:12.5px;color:var(--txt2);line-height:1.7}

/* Username pill */
.username-pill{display:inline-block;background:var(--P-bg);color:var(--P);border:1px solid rgba(var(--Pr),.25);padding:2px 11px;border-radius:20px;font-size:12px;font-weight:700;margin:3px 0}

/* Info boxes */
.tip-box{background:var(--P-bg);border:1px solid rgba(var(--Pr),.2);border-left:3px solid var(--P);border-radius:0 9px 9px 0;padding:10px 13px;margin-top:14px;font-size:11.5px;color:var(--txt2);line-height:1.65;text-align:left}
.tip-box strong{color:var(--P);font-weight:700}
.cancel-box{background:var(--WN-bg);border:1px solid rgba(245,158,11,.2);border-left:3px solid var(--WN);border-radius:0 9px 9px 0;padding:12px 14px;margin-top:14px;font-size:11.5px;color:var(--txt2);line-height:1.7;text-align:left}
.cancel-box strong{color:var(--WN);font-weight:700}

/* Animated dots */
.dots span{display:inline-block;animation:blink 1.4s infinite both}
.dots span:nth-child(2){animation-delay:.2s}
.dots span:nth-child(3){animation-delay:.4s}
@keyframes blink{0%,60%,100%{opacity:.2}30%{opacity:1}}

/* Progress bar */
.progress-track{width:100%;height:3px;background:var(--bg3);border-radius:2px;overflow:hidden;margin-top:14px}
.progress-fill{height:100%;border-radius:2px;width:0}
.progress-fill.run-ok     {animation:prog 3s linear forwards;background:var(--OK)}
.progress-fill.run-warning{animation:prog 3s linear forwards;background:var(--WN)}
.progress-fill.run-danger {animation:prog 5s linear forwards;background:var(--DN)}
@keyframes prog{to{width:100%}}

/* Countdown */
.countdown{display:inline-flex;align-items:center;justify-content:center;width:34px;height:34px;border-radius:50%;color:#fff;font-size:14px;font-weight:800;margin-top:12px;font-variant-numeric:tabular-nums}
[data-theme="light"] .countdown{color:#fff}
.countdown.ok     {background:var(--OK);box-shadow:0 0 14px rgba(34,197,94,.4)}
.countdown.warning{background:var(--WN);box-shadow:0 0 14px rgba(245,158,11,.4)}
.countdown.danger {background:var(--DN);box-shadow:0 0 14px rgba(239,68,68,.4)}

.refresh-note{font-size:11.5px;color:var(--txt3);margin-top:12px}

/* Retry button */
.retry-btn{display:inline-flex;align-items:center;justify-content:center;gap:7px;width:100%;height:44px;margin-top:16px;background:var(--WN);color:#fff;border:none;border-radius:10px;font-family:inherit;font-size:13px;font-weight:800;text-decoration:none;cursor:pointer;box-shadow:0 4px 16px rgba(245,158,11,.35);transition:filter .15s,transform .15s}
.retry-btn:hover{filter:brightness(1.1);transform:translateY(-1px);color:#fff}
[data-theme="light"] .retry-btn{color:#fff}

/* Toast */
.db-toast{position:fixed;top:-80px;left:50%;transform:translateX(-50%);min-width:260px;max-width:calc(100vw - 28px);background:var(--card2);border:1px solid rgba(var(--Pr),.3);border-left:4px solid var(--P);border-radius:10px;padding:10px 38px 10px 12px;z-index:9999;display:flex;align-items:center;gap:9px;transition:top .4s cubic-bezier(.34,1.56,.64,1);box-shadow:0 8px 32px rgba(0,0,0,.3)}
.db-toast.show{top:14px}
.t-dot{width:22px;height:22px;border-radius:7px;display:flex;align-items:center;justify-content:center;font-size:11px;color:#fff;flex-shrink:0}
[data-theme="light"] .t-dot{color:#fff}
.t-txt{font-size:12px;font-weight:600;color:var(--txt);flex:1}
.t-cls{position:absolute;right:10px;top:50%;transform:translateY(-50%);background:none;border:none;font-size:17px;color:var(--txt3);cursor:pointer}

@media(max-width:380px){.card{padding:20px 15px;border-radius:14px}}
</style>
</head>
<body>
<script>
(function(){
    var t=localStorage.getItem('ev_theme')||'dark';
    document.documentElement.setAttribute('data-theme',t);
    var ico=document.getElementById('theme-ico');
    if(ico) ico.className=t==='dark'?'fa-solid fa-sun':'fa-solid fa-moon';
})();
</script>

<button class="theme-btn" id="theme-btn" onclick="toggleTheme()" aria-label="Toggle theme">
    <i id="theme-ico" class="fa-solid fa-moon"></i>
</button>

<div class="card">
    <div class="brand-row">
        <div class="brand-ring">
            <?php if ($hasCustomLogo): ?>
            <img class="brand-logo-img" src="../uploads/logos/<?php echo htmlspecialchars($siteLogo); ?>" alt="">
            <?php else: ?>
            <div class="brand-dot"></div>
            <?php endif; ?>
        </div>
        <div>
            <div class="brand-name"><?php echo htmlspecialchars($siteName); ?></div>
            <div class="brand-sub">Activation Status</div>
        </div>
    </div>
    <div class="brand-divider"></div>

    <?php if ($isCompleted): ?>
    <div class="status-wrap success">
        <i class="fa-solid fa-check anim-success"></i>
    </div>
    <h1 class="status-title success"><?php echo $isClientActivation ? 'Client Activated! 🎉' : 'Account Activated! 🎉'; ?></h1>
    <p class="status-msg">
        <?php if ($isClientActivation && $payingForUsername): ?>
            Account successfully activated for<br>
            <span class="username-pill">@<?php echo htmlspecialchars($payingForUsername); ?></span><br>
            They can now start earning.
        <?php else: ?>
            Your account is now active.<br>You have full access to all features.
        <?php endif; ?>
    </p>
    <div class="countdown ok" id="counter">3</div>
    <div class="progress-track"><div class="progress-fill run-ok"></div></div>

    <?php elseif ($isCancelled): ?>
    <div class="status-wrap cancelled">
        <i class="fa-solid fa-xmark anim-cancelled"></i>
    </div>
    <h1 class="status-title cancelled">Payment Cancelled</h1>
    <p class="status-msg">You cancelled the M-Pesa prompt.<br>No money was deducted from your account.</p>
    <div class="cancel-box">
        <strong>What happened?</strong><br>
        You dismissed or timed out the M-Pesa PIN prompt. Your account has <strong>not</strong> been charged — you can try again safely.
    </div>
    <a href="activate.php" class="retry-btn"><i class="fa-solid fa-rotate-right"></i> Try Again</a>
    <div class="countdown warning" id="counter">5</div>
    <div class="progress-track"><div class="progress-fill run-warning"></div></div>

    <?php elseif ($isFailed): ?>
    <div class="status-wrap failed">
        <i class="fa-solid fa-times anim-failed"></i>
    </div>
    <h1 class="status-title failed">Payment Failed</h1>
    <p class="status-msg">The payment could not be completed.<br>Please check your M-Pesa balance and try again.</p>
    <a href="activate.php" class="retry-btn"><i class="fa-solid fa-rotate-right"></i> Try Again</a>
    <div class="countdown danger" id="counter">5</div>
    <div class="progress-track"><div class="progress-fill run-danger"></div></div>

    <?php else: ?>
    <div class="status-wrap pending">
        <i class="fa-solid fa-spinner anim-pending"></i>
    </div>
    <h1 class="status-title pending">Processing<span class="dots"><span>.</span><span>.</span><span>.</span></span></h1>
    <p class="status-msg">
        Check your phone and enter your<br>
        <strong style="color:var(--P);font-weight:800">M-Pesa PIN</strong> when prompted.
    </p>
    <div class="tip-box">
        <strong>Tip:</strong> The M-Pesa prompt may take up to 30 seconds. This page refreshes automatically every 5 seconds.
    </div>
    <p class="refresh-note">Auto-refreshing in <span id="refreshCount">5</span>s</p>
    <?php endif; ?>

</div>

<div class="db-toast" id="db-toast">
    <div class="t-dot" id="t-dot"></div>
    <span class="t-txt" id="t-txt"></span>
    <button class="t-cls" onclick="hideToast()">&#215;</button>
</div>

<script>
function applyTheme(t,animate){
    var html=document.documentElement;
    if(animate) html.style.transition='background .25s,color .25s';
    html.setAttribute('data-theme',t);
    localStorage.setItem('ev_theme',t);
    var ico=document.getElementById('theme-ico');
    if(ico) ico.className=t==='dark'?'fa-solid fa-sun':'fa-solid fa-moon';
}
window.toggleTheme=function(){
    var cur=document.documentElement.getAttribute('data-theme')||'dark';
    applyTheme(cur==='dark'?'light':'dark',true);
};

var ADMIN_P ='<?php echo addslashes($adminPrimary); ?>';
var ADMIN_OK='<?php echo addslashes($adminSuccess); ?>';
var ADMIN_WN='<?php echo addslashes($adminWarning); ?>';
var ADMIN_DN='<?php echo addslashes($adminDanger);  ?>';

function showToast(type,msg){
    var t=document.getElementById('db-toast'),dot=document.getElementById('t-dot'),txt=document.getElementById('t-txt');
    var cols={success:ADMIN_OK,error:ADMIN_DN,info:ADMIN_P,warning:ADMIN_WN};
    var col=cols[type]||ADMIN_P;
    t.className='db-toast show';t.style.borderLeftColor=col;
    dot.style.background=col;
    dot.innerHTML=type==='success'?'&#10003;':type==='error'?'&#10007;':'&#9432;';
    txt.textContent=msg;
    setTimeout(hideToast,4500);
}
function hideToast(){document.getElementById('db-toast').classList.remove('show');}

(function(){
    <?php if ($isCompleted): ?>
    var count=3,el=document.getElementById('counter');
    var iv=setInterval(function(){count--;if(el)el.textContent=count;if(count<=0){clearInterval(iv);
        location.href='<?php echo $isClientActivation ? "dashboard.php?client_activated=success" : "dashboard.php?activated=success"; ?>';}},1000);
    <?php elseif ($isCancelled): ?>
    var count=5,el=document.getElementById('counter');
    var iv=setInterval(function(){count--;if(el)el.textContent=count;if(count<=0){clearInterval(iv);location.href='activate.php';}},1000);
    <?php elseif ($isFailed): ?>
    var count=5,el=document.getElementById('counter');
    var iv=setInterval(function(){count--;if(el)el.textContent=count;if(count<=0){clearInterval(iv);
        location.href='<?php echo $isClientActivation ? "pay.php" : "activate.php"; ?>';}},1000);
    <?php else: ?>
    var secs=5,el=document.getElementById('refreshCount');
    var t=setInterval(function(){secs--;if(el)el.textContent=secs;if(secs<=0){clearInterval(t);location.reload();}},1000);
    <?php endif; ?>
}());
</script>
</body>
</html>