<?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();

$stmt = $conn->prepare("SELECT u.*, c.activation_fee, c.currency_symbol, c.currency_code,
    c.exchange_rate, c.status as country_status,
    c.activation_instructions, c.contact_email, c.contact_phone
    FROM users u LEFT JOIN countries c ON u.country = c.name WHERE u.id = ?");
$stmt->bind_param("i", $userId); $stmt->execute();
$userData = $stmt->get_result()->fetch_assoc();
if (!$userData) { session_destroy(); redirect('../login.php'); }
if ($userData['status'] === 'active') { setFlash('info','Your account is already active!'); redirect('store.php'); }

$activationFee  = floatval($userData['activation_fee']  ?? 200);
$currencySymbol = $userData['currency_symbol']           ?? 'KSH';
$currencyCode   = $userData['currency_code']             ?? 'KES';
$exchangeRate   = max(0.000001, floatval($userData['exchange_rate'] ?? 1));
$countryStatus  = $userData['country_status']            ?? 'inactive';
$error          = '';

// ── Admin color injection ──────────────────────────────────────────────────
$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);

// ════════════════════════════════════════════════════════════════════════════
// PARSE ACTIVATION INSTRUCTIONS — detect clickable payment links
//
// Admin can embed links using the format:
//   [Pay Now|https://pay.example.com/link]
//   [Buy via PayPal|https://paypal.me/xxxxx]
//   [Airtel Money|https://airtel.pg/pay/xxxx]
//
// OR just bare URLs which we auto-link:
//   https://pay.pesapal.com/transaction/...
// ════════════════════════════════════════════════════════════════════════════
function parseActivationInstructions($raw) {
    if (empty($raw)) return '';

    // 1. Convert [Label|URL] to styled button
    $parsed = preg_replace_callback(
        '/\[([^\]|]+)\|([^\]]+)\]/',
        function($m) {
            $label = htmlspecialchars(trim($m[1]));
            $url   = htmlspecialchars(trim($m[2]), ENT_QUOTES);
            return '<a href="'.$url.'" target="_blank" rel="noopener" class="instr-pay-btn">'
                 . '<i class="fa-solid fa-arrow-up-right-from-square"></i> '.$label.'</a>';
        },
        htmlspecialchars($raw, ENT_QUOTES | ENT_HTML5)
    );

    // 2. Auto-link bare URLs (not already linked)
    $parsed = preg_replace_callback(
        '/(?<!href=["\'])(?<!">)(https?:\/\/[^\s<"\']+)/i',
        function($m) {
            $url = htmlspecialchars($m[1], ENT_QUOTES);
            $display = strlen($m[1]) > 50 ? substr($m[1], 0, 47).'…' : $m[1];
            return '<a href="'.$url.'" target="_blank" rel="noopener" class="instr-link">'
                 . htmlspecialchars($display).'</a>';
        },
        $parsed
    );

    return nl2br($parsed);
}

$activationInstructionsParsed = parseActivationInstructions($userData['activation_instructions'] ?? '');

// ── Auto-activation for free countries ───────────────────────────────────
if ($countryStatus === 'active' && $activationFee <= 1) {
    $logDir = dirname(__DIR__).'/logs'; $logFile = $logDir.'/activation.txt';
    if (!is_dir($logDir)) @mkdir($logDir, 0755, true);
    $log = function($msg) use ($logFile,$userId){ @file_put_contents($logFile,"[".date("Y-m-d H:i:s")."] user#$userId – $msg\n",FILE_APPEND); };
    $log("Auto-activation triggered. fee=$activationFee country={$userData['country']}");

    $hasUpdatedAt = false;
    $colCheck = $conn->query("SHOW COLUMNS FROM users LIKE 'updated_at'");
    if ($colCheck && $colCheck->num_rows > 0) $hasUpdatedAt = true;
    $sql = $hasUpdatedAt
        ? "UPDATE users SET status='active', activation_date=NOW(), updated_at=NOW() WHERE id=?"
        : "UPDATE users SET status='active', activation_date=NOW() WHERE id=?";
    $stmt = $conn->prepare($sql);
    if (!$stmt) { $error='Database error [ERR:PREP]'; $log("FAILED:".$conn->error); }
    else {
        $stmt->bind_param("i",$userId);
        if (!$stmt->execute()) { $error='Database error [ERR:EXEC]'; $log("FAILED:".$stmt->error); }
        else $log("SUCCESS:status=active");
    }

    if (!$error) {
        try {
            $txCols=[]; $cr=$conn->query("SHOW COLUMNS FROM transactions");
            if($cr){while($c=$cr->fetch_assoc())$txCols[]=$c['Field'];}
            $ref='AUTO-ACT-'.$userId.'-'.time(); $desc=$activationFee==0?'Free activation':'Auto-activation'; $amt=floatval($activationFee);
            $fields=['user_id','amount','description']; $types='ids'; $vals=[$userId,$amt,$desc];
            if(in_array('type',$txCols)){$fields[]='type';$types.='s';$vals[]='activation';}
            if(in_array('reference',$txCols)){$fields[]='reference';$types.='s';$vals[]=$ref;}
            if(in_array('status',$txCols)){$fields[]='status';$types.='s';$vals[]='completed';}
            if(in_array('created_at',$txCols)){$fields[]='created_at';$types.='s';$vals[]=date('Y-m-d H:i:s');}
            $ph=implode(',',array_fill(0,count($fields),'?')); $fld=implode(',',$fields);
            $txStmt=$conn->prepare("INSERT INTO transactions ($fld) VALUES ($ph)");
            if($txStmt){$txStmt->bind_param($types,...$vals);$txStmt->execute();}
        } catch(Exception $e) { $log("TX exception:".$e->getMessage()); }
    }

    if (!$error && !empty($userData['referred_by'])) {
        try {
            $cStmt=$conn->prepare("SELECT id FROM countries WHERE name=? LIMIT 1");
            $cStmt->bind_param("s",$userData['country']); $cStmt->execute();
            $cRow=$cStmt->get_result()->fetch_assoc(); $countryId=$cRow?(int)$cRow['id']:0;
            if($countryId>0) distributeReferralCommissions($userId,$userData['referred_by'],$countryId);
        } catch(Exception $e) { $log("Referral exception:".$e->getMessage()); }
    }

    if (!$error) { $_SESSION['user_status']='active'; $log("Auto-activation success"); define('AUTO_ACTIVATED',true); }
}

if ($userData['country']==='Kenya' && file_exists('../mpesa/stk_push.php'))
    require_once '../mpesa/stk_push.php';

if ($_SERVER['REQUEST_METHOD']==='POST' && $userData['country']==='Kenya') {
    $phoneNumber = sanitize($_POST['phone_number']);
    if (empty($phoneNumber)) { $error='Phone number is required'; }
    else {
        $phoneNumber = preg_replace('/\D/','',$phoneNumber);
        if (substr($phoneNumber,0,1)==='0')          $phoneNumber='254'.substr($phoneNumber,1);
        elseif (substr($phoneNumber,0,4)==='+254')   $phoneNumber=substr($phoneNumber,1);
        elseif (substr($phoneNumber,0,1)==='7'||substr($phoneNumber,0,1)==='1') $phoneNumber='254'.$phoneNumber;
        if (strlen($phoneNumber)!==12) { $error='Invalid phone number. Should be 12 digits (254...)'; }
        else {
            if ($activationFee<=0) { $error='Invalid activation fee. Please contact admin.'; }
            else {
                if (function_exists('processActivationPayment')) {
                    $result = processActivationPayment($userId,$phoneNumber,$activationFee);
                    if ($result['success']) { $_SESSION['checkout_request_id']=$result['checkout_request_id']; header('Location: activate.php?payment=initiated'); exit(); }
                    else { $error=$result['message']; }
                } else { $error='MPESA payment system not configured. Contact admin.'; }
            }
        }
    }
}
?>
<!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>Activate Account — <?= 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:  <?= $adminPrimary ?>;
    --OK: #22c55e;
    --WN: #f59e0b;
    --DN: #ef4444;
    --Pr: <?= $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);
    --input-bg:rgba(255,255,255,0.05);--input-bdr:rgba(255,255,255,0.12);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);
    --input-bg:rgba(0,0,0,0.03);--input-bdr:rgba(0,0,0,0.12);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{width:100%;max-width:420px;background:var(--card);border:1px solid var(--bdr);border-radius:18px;
    padding:22px 20px 18px;box-shadow:var(--shadow);position:relative;z-index:1;
    transition:background .25s,border-color .25s;animation:cardIn .5s cubic-bezier(.22,1,.36,1) both}
[data-theme="dark"] .card{border-color:rgba(var(--Pr),.14)}
@keyframes cardIn{from{opacity:0;transform:translateY(18px)}to{opacity:1;transform:translateY(0)}}
.card::before{content:'';position:absolute;top:0;left:10%;right:10%;height:1px;
    background:linear-gradient(90deg,transparent,rgba(var(--Pr),.5),transparent);border-radius:1px}
.brand-row{display:flex;align-items:center;gap:10px;margin-bottom:14px}
.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-text{flex:1;min-width:0}
.brand-name{font-size:15px;font-weight:800;color:var(--txt);letter-spacing:.3px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.brand-sub{font-size:10px;color:var(--txt2);font-weight:600;letter-spacing:.5px;margin-top:1px}
.brand-divider{height:1px;margin:0 0 16px;background:linear-gradient(90deg,transparent,rgba(var(--Pr),.35),transparent)}
.sec-lbl{font-size:9px;font-weight:700;letter-spacing:2px;text-transform:uppercase;color:var(--P);
    opacity:.7;margin-bottom:14px;display:flex;align-items:center;gap:8px}
.sec-lbl::after{content:'';flex:1;height:1px;background:linear-gradient(90deg,rgba(var(--Pr),.3),transparent)}
.status-box{border-radius:0 10px 10px 0;padding:12px 14px;margin-bottom:14px;border-left:3px solid;
    display:flex;flex-direction:column;gap:4px;animation:fadeUp .3s ease both}
@keyframes fadeUp{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}
.status-box.ok{background:var(--OK-bg);border-color:var(--OK)}
.status-box.wn{background:var(--WN-bg);border-color:var(--WN)}
.status-box.dn{background:var(--DN-bg);border-color:var(--DN)}
.status-box.pri{background:var(--P-bg);border-color:var(--P)}
.box-lbl{font-size:9px;font-weight:800;text-transform:uppercase;letter-spacing:1.5px;margin-bottom:2px}
.status-box.ok  .box-lbl{color:var(--OK)}
.status-box.wn  .box-lbl{color:var(--WN)}
.status-box.dn  .box-lbl{color:var(--DN)}
.status-box.pri .box-lbl{color:var(--P)}
.fee-amount{font-size:28px;font-weight:900;letter-spacing:-1px;line-height:1;color:var(--txt);font-variant-numeric:tabular-nums}
.box-note{font-size:11.5px;color:var(--txt2)}

/* ── SUCCESS BANNER ── */
.success-banner{background:var(--OK-bg);border:1px solid rgba(34,197,94,.25);border-radius:14px;
    padding:20px 16px 16px;margin-bottom:14px;text-align:center;animation:fadeUp .4s ease both}
.sb-icon-wrap{position:relative;width:58px;height:58px;margin:0 auto 14px}
.sb-icon-ring{position:absolute;inset:0;border-radius:50%;border:2px solid rgba(34,197,94,.45);animation:ringPulse 1.8s ease-out infinite}
@keyframes ringPulse{0%{transform:scale(1);opacity:.8}100%{transform:scale(1.55);opacity:0}}
.sb-icon{position:relative;z-index:1;width:58px;height:58px;border-radius:50%;background:var(--OK);
    display:flex;align-items:center;justify-content:center;font-size:22px;color:#fff;box-shadow:0 6px 20px rgba(34,197,94,.4)}
.sb-badge{display:inline-block;background:var(--P);color:#fff;font-size:9px;font-weight:800;letter-spacing:1.5px;
    text-transform:uppercase;padding:2px 10px;border-radius:20px;margin-bottom:8px}
[data-theme="light"] .sb-badge{color:#fff}
.sb-title{font-size:17px;font-weight:800;color:var(--OK);margin-bottom:5px}
.sb-sub{font-size:12px;color:var(--txt2);line-height:1.65;margin-bottom:14px}
.sb-details{background:var(--bg3);border:1px solid rgba(34,197,94,.2);border-radius:10px;padding:8px 12px;margin-bottom:14px;text-align:left;transition:background .25s}
.sb-row{display:flex;align-items:center;justify-content:space-between;padding:6px 0;border-bottom:1px solid var(--bdr);font-size:12px}
.sb-row:last-child{border-bottom:none}
.sb-row-k{color:var(--txt2);display:flex;align-items:center;gap:6px;font-weight:500}
.sb-row-k i{font-size:10px;color:var(--OK)}
.sb-row-v{font-weight:700;color:var(--txt)}
.free-tag{background:var(--OK-bg);color:var(--OK);padding:1px 9px;border-radius:20px;font-size:10.5px;font-weight:800;border:1px solid rgba(34,197,94,.2)}
.active-tag{display:inline-flex;align-items:center;gap:5px;background:var(--OK-bg);color:var(--OK);padding:2px 9px;border-radius:20px;font-size:10.5px;font-weight:700;border:1px solid rgba(34,197,94,.2)}
.active-dot{width:6px;height:6px;border-radius:50%;background:var(--OK);animation:blink 1.4s ease-in-out infinite}
@keyframes blink{0%,100%{opacity:1}50%{opacity:.3}}
.sb-redirect{margin-bottom:12px}
.sb-redirect-txt{font-size:11.5px;color:var(--txt2);font-weight:500;margin-bottom:7px}
.sb-redirect-txt strong{color:var(--OK)}
.sb-progress-track{height:4px;background:var(--bg3);border-radius:3px;overflow:hidden}
.sb-progress-fill{height:100%;border-radius:3px;background:var(--OK);animation:countdownBar 4s linear forwards}
@keyframes countdownBar{from{width:100%}to{width:0%}}
.sb-btn{display:flex;align-items:center;justify-content:center;gap:7px;width:100%;height:42px;border:none;border-radius:10px;
    background:var(--OK);color:#fff;font-size:13px;font-weight:800;cursor:pointer;font-family:inherit;
    text-decoration:none;box-shadow:0 4px 14px rgba(34,197,94,.35);transition:filter .15s,transform .15s}
.sb-btn:hover{filter:brightness(1.1);transform:translateY(-1px)}
[data-theme="light"] .sb-btn{color:#fff}

/* ── ERROR BOX ── */
.err-box{background:var(--DN-bg);border:1px solid rgba(239,68,68,.22);border-left:3px solid var(--DN);
    border-radius:0 9px 9px 0;padding:10px 12px;font-size:12px;color:var(--DN);
    margin-bottom:12px;line-height:1.7;animation:fadeUp .3s ease both}

/* ── FORM ── */
.fg{margin-bottom:12px}
.flbl{font-size:10px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:var(--txt2);margin-bottom:5px;display:flex;align-items:center;gap:5px}
.flbl i{font-size:9px;color:var(--P)}
.finp{width:100%;height:42px;padding:0 12px;background:var(--input-bg);border:1px solid var(--input-bdr);
    border-radius:10px;color:var(--txt);font-size:14px;font-weight:700;text-align:center;letter-spacing:1px;
    outline:none;font-family:inherit;appearance:none;transition:border-color .15s,box-shadow .15s,background .15s}
.finp::placeholder{color:var(--txt3);font-size:12px;font-weight:400;letter-spacing:0}
.finp:focus{border-color:var(--P);box-shadow:0 0 0 3px rgba(var(--Pr),.14);background:var(--P-bg)}
.fhint{font-size:10px;color:var(--txt3);text-align:center;margin-top:4px}
.btn-submit{width:100%;height:44px;border:none;border-radius:10px;background:var(--P);color:#fff;
    font-size:14px;font-weight:800;cursor:pointer;font-family:inherit;display:flex;align-items:center;justify-content:center;gap:8px;
    box-shadow:0 4px 18px rgba(var(--Pr),.35);transition:all .18s;margin-top:4px}
.btn-submit:hover:not(:disabled){filter:brightness(1.1);transform:translateY(-1px);box-shadow:0 6px 22px rgba(var(--Pr),.45)}
.btn-submit:disabled{opacity:.45;cursor:not-allowed;transform:none;box-shadow:none}
[data-theme="light"] .btn-submit{color:#fff}
.spinner{display:none;width:16px;height:16px;border:2px solid rgba(255,255,255,.3);border-top-color:#fff;border-radius:50%;animation:spin .6s linear infinite}
.btn-submit.loading .btn-lbl{display:none}
.btn-submit.loading .spinner{display:block}
@keyframes spin{to{transform:rotate(360deg)}}
.retry-btn{display:flex;align-items:center;justify-content:center;gap:7px;width:100%;height:42px;background:var(--P);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 14px rgba(var(--Pr),.3);margin-bottom:10px;transition:.15s}
.retry-btn:hover{filter:brightness(1.1);color:#fff}

/* ── INSTRUCTIONS & PAYMENT LINKS ── */
.instr-block{margin-top:10px;padding-top:10px;border-top:1px solid rgba(245,158,11,.2);
    font-size:12px;line-height:1.8;color:var(--txt2)}
.instr-pay-btn{display:inline-flex;align-items:center;gap:6px;padding:8px 16px;margin:6px 4px 2px 0;
    background:var(--P);color:#fff;border-radius:10px;font-size:13px;font-weight:800;text-decoration:none;
    box-shadow:0 3px 12px rgba(var(--Pr),.35);transition:all .2s;vertical-align:middle}
[data-theme="light"] .instr-pay-btn{color:#fff}
.instr-pay-btn:hover{filter:brightness(1.1);transform:translateY(-1px);box-shadow:0 5px 18px rgba(var(--Pr),.5)}
.instr-link{color:var(--P);text-decoration:underline;word-break:break-all;font-weight:600;font-size:11px}
.instr-link:hover{opacity:.8}

/* ── Payment link section header ── */
.pay-link-header{display:flex;align-items:center;gap:7px;margin-top:14px;margin-bottom:8px;
    font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:1.5px;color:var(--WN)}
.pay-link-header::after{content:'';flex:1;height:1px;background:rgba(245,158,11,.25)}

.contact-block{margin-top:10px;padding-top:10px;border-top:1px solid rgba(245,158,11,.2)}
.contact-lbl{font-size:9px;font-weight:800;text-transform:uppercase;letter-spacing:1.5px;color:var(--WN);margin-bottom:8px}
.contact-item{display:flex;align-items:center;gap:7px;margin-bottom:6px;font-size:12px}
.contact-item i{color:var(--WN);width:13px;flex-shrink:0}
.contact-item a{color:var(--txt2);text-decoration:none;font-weight:500;word-break:break-all;transition:color .15s}
.contact-item a:hover{color:var(--WN)}
.dn-desc{font-size:12px;color:var(--DN);line-height:1.6}

.card-footer{text-align:center;margin-top:14px;padding-top:12px;border-top:1px solid var(--bdr)}
.card-footer a{font-size:12px;color:var(--txt3);text-decoration:none;font-weight:500;
    display:inline-flex;align-items:center;gap:5px;transition:color .15s}
.card-footer a:hover{color:var(--txt2)}

/* ── 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;min-width:0}
.t-cls{position:absolute;right:10px;top:50%;transform:translateY(-50%);background:none;border:none;font-size:17px;color:var(--txt3);cursor:pointer}
.inline-spin{width:14px;height:14px;border:2px solid rgba(var(--Pr),.25);border-top-color:var(--P);border-radius:50%;animation:spin .7s linear infinite;display:inline-block}
@media(max-width:380px){.card{padding:18px 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">

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

    <div class="brand-divider"></div>

    <?php if ($countryStatus !== 'active'): ?>
    <!-- ── Country not configured ── -->
    <div class="sec-lbl"><i class="fa-solid fa-triangle-exclamation" style="font-size:9px"></i>Not Available</div>
    <div class="status-box dn">
        <div class="box-lbl">Country Not Configured</div>
        <p class="dn-desc">Your country (<strong><?= htmlspecialchars($userData['country']) ?></strong>) is not yet available. Please contact support.</p>
    </div>

    <?php elseif ($activationFee <= 1): ?>
    <!-- ── Free / auto-activation ── -->
    <?php if ($error): ?>
    <div class="sec-lbl"><i class="fa-solid fa-circle-xmark" style="font-size:9px"></i>Activation Failed</div>
    <div class="err-box">
        <strong><i class="fa-solid fa-triangle-exclamation" style="margin-right:5px"></i>Auto-activation failed</strong><br>
        <?= htmlspecialchars($error) ?><br>
        <small style="opacity:.7">Try refreshing or contact support.</small>
    </div>
    <a href="activate.php" class="retry-btn"><i class="fa-solid fa-rotate-right"></i> Retry Activation</a>

    <?php elseif (defined('AUTO_ACTIVATED') && AUTO_ACTIVATED): ?>
    <!-- SUCCESS -->
    <div class="success-banner">
        <div class="sb-icon-wrap">
            <div class="sb-icon-ring"></div>
            <div class="sb-icon"><i class="fa-solid fa-check"></i></div>
        </div>
        <div class="sb-badge">Free Account</div>
        <h2 class="sb-title">You're Activated! 🎉</h2>
        <p class="sb-sub">Your account has been activated at no charge.<br>Welcome to <?= htmlspecialchars($siteName) ?>!</p>
        <div class="sb-details">
            <div class="sb-row">
                <span class="sb-row-k"><i class="fa-solid fa-user"></i>Account</span>
                <span class="sb-row-v"><?= htmlspecialchars($userData['username'] ?? '') ?></span>
            </div>
            <div class="sb-row">
                <span class="sb-row-k"><i class="fa-solid fa-earth-africa"></i>Country</span>
                <span class="sb-row-v"><?= htmlspecialchars($userData['country']) ?></span>
            </div>
            <div class="sb-row">
                <span class="sb-row-k"><i class="fa-solid fa-tag"></i>Fee</span>
                <span class="sb-row-v"><span class="free-tag">FREE</span></span>
            </div>
            <div class="sb-row">
                <span class="sb-row-k"><i class="fa-solid fa-circle-check"></i>Status</span>
                <span class="sb-row-v"><span class="active-tag"><span class="active-dot"></span>Active</span></span>
            </div>
        </div>
        <div class="sb-redirect">
            <div class="sb-redirect-txt">Redirecting in <strong id="countdownNum">4</strong>s…</div>
            <div class="sb-progress-track"><div class="sb-progress-fill"></div></div>
        </div>
        <a href="dashboard.php" class="sb-btn"><i class="fa-solid fa-gauge-high"></i> Go to Dashboard Now</a>
    </div>

    <?php else: ?>
    <div class="sec-lbl"><i class="fa-solid fa-bolt" style="font-size:9px"></i>Activating</div>
    <div class="status-box pri">
        <div class="box-lbl">Free Activation</div>
        <div style="display:flex;align-items:center;gap:8px;margin-top:4px;font-size:12px;color:var(--txt2)">
            <span class="inline-spin"></span> Processing your free activation…
        </div>
    </div>
    <?php endif; ?>

    <?php elseif ($userData['country'] === 'Kenya'): ?>
    <!-- ── Kenya M-Pesa ── -->
    <div class="sec-lbl"><i class="fa-solid fa-sim-card" style="font-size:9px"></i>M-Pesa Payment</div>
    <div class="status-box ok">
        <div class="box-lbl">Activation Fee</div>
        <div class="fee-amount"><?= htmlspecialchars($currencySymbol.' '.number_format($activationFee,2)) ?></div>
        <div class="box-note">One-time payment · Instant activation</div>
    </div>

    <?php if ($error): ?>
    <div class="err-box"><i class="fa-solid fa-circle-exclamation" style="margin-right:5px"></i><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <form method="POST" id="activateForm" novalidate>
        <div class="fg">
            <div class="flbl"><i class="fa-solid fa-sim-card"></i>M-Pesa Phone Number</div>
            <input type="tel" class="finp" id="phoneNumber" name="phone_number"
                value="<?= htmlspecialchars($userData['phone'] ?? '') ?>"
                placeholder="0712 345 678" autocomplete="tel">
            <div class="fhint">Accepts: 07XX… · 254XX… · +254XX…</div>
        </div>
        <button type="submit" class="btn-submit" id="submitBtn">
            <i class="fa-solid fa-lock" style="font-size:12px"></i>
            <span class="btn-lbl">Pay &amp; Activate Account</span>
            <div class="spinner"></div>
        </button>
    </form>

    <?php else: ?>
    <!-- ── OTHER COUNTRIES — manual / link-based activation ── -->
    <div class="sec-lbl"><i class="fa-solid fa-globe" style="font-size:9px"></i>Manual Activation</div>
    <div class="status-box wn">
        <div class="box-lbl">
            Activation Fee — <?= htmlspecialchars($userData['country']) ?>
        </div>
        <div class="fee-amount"><?= htmlspecialchars($currencySymbol.' '.number_format($activationFee,2)) ?></div>

        <?php if (!empty($activationInstructionsParsed)): ?>
        <?php
        // Check if there are payment buttons in instructions (has instr-pay-btn)
        $hasPayButtons = strpos($activationInstructionsParsed, 'instr-pay-btn') !== false;
        $hasAutoLinks  = strpos($activationInstructionsParsed, 'instr-link') !== false;
        ?>

        <?php if ($hasPayButtons || $hasAutoLinks): ?>
        <div class="pay-link-header">
            <i class="fa-solid fa-credit-card" style="font-size:9px"></i>
            Pay via link
        </div>
        <?php endif; ?>

        <div class="instr-block"><?= $activationInstructionsParsed ?></div>

        <?php else: ?>
        <div class="box-note" style="margin-top:6px">Contact support to complete activation.</div>
        <?php endif; ?>

        <?php if (!empty($userData['contact_email']) || !empty($userData['contact_phone'])): ?>
        <div class="contact-block">
            <div class="contact-lbl">Contact Support</div>
            <?php if (!empty($userData['contact_email'])): ?>
            <div class="contact-item">
                <i class="fa-solid fa-envelope"></i>
                <a href="mailto:<?= htmlspecialchars($userData['contact_email']) ?>"><?= htmlspecialchars($userData['contact_email']) ?></a>
            </div>
            <?php endif; ?>
            <?php if (!empty($userData['contact_phone'])): ?>
            <div class="contact-item">
                <i class="fa-solid fa-phone"></i>
                <a href="tel:<?= htmlspecialchars($userData['contact_phone']) ?>"><?= htmlspecialchars($userData['contact_phone']) ?></a>
            </div>
            <div class="contact-item">
                <i class="fa-brands fa-whatsapp" style="color:#25D366"></i>
                <a href="https://wa.me/<?= preg_replace('/[^0-9]/','',$userData['contact_phone']) ?>" target="_blank">
                    WhatsApp Support
                </a>
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <div class="card-footer">
        <a href="logout.php"><i class="fa-solid fa-arrow-left" style="font-size:10px"></i> Sign Out</a>
    </div>

</div>

<!-- Toast -->
<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  = '<?= addslashes($adminPrimary) ?>';
var ADMIN_OK = '<?= addslashes($adminSuccess) ?>';
var ADMIN_WN = '<?= addslashes($adminWarning) ?>';
var ADMIN_DN = '<?= addslashes($adminDanger)  ?>';
var _tt = null;

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 icos={success:'&#10003;',error:'&#10007;',info:'&#9432;',warning:'&#9888;'};
    var col = cols[type] || ADMIN_P;
    clearTimeout(_tt); t.className='db-toast show';
    t.style.borderLeftColor=col; dot.style.background=col;
    dot.innerHTML=icos[type]||'&#9432;'; txt.textContent=msg;
    _tt=setTimeout(hideToast, type==='error'?6000:4000);
}
function hideToast() { document.getElementById('db-toast').classList.remove('show'); }

var phoneInput = document.getElementById('phoneNumber');
if (phoneInput) {
    phoneInput.addEventListener('input', function(){
        var v = this.value.replace(/\D/g,'');
        if (v && !v.startsWith('254') && !v.startsWith('0')) v = '0' + v;
        this.value = v;
    });
}

var form = document.getElementById('activateForm');
if (form) {
    form.addEventListener('submit', function(e){
        var phone = phoneInput.value.replace(/\D/g,'');
        if (phone.length < 9 || phone.length > 13) {
            e.preventDefault(); showToast('error','Please enter a valid phone number'); return;
        }
        var btn = document.getElementById('submitBtn');
        btn.classList.add('loading'); btn.disabled = true;
    });
}

<?php if ($error && $activationFee > 1): ?>
showToast('error', <?= json_encode($error) ?>);
<?php endif; ?>

window.addEventListener('DOMContentLoaded', function(){
    var p = new URLSearchParams(location.search);
    if (p.get('payment') === 'initiated') {
        history.replaceState({}, document.title, location.pathname);
        showToast('info', 'Check your phone for the M-Pesa prompt…');
        setTimeout(function(){ location.href = 'activation_status.php'; }, 2500);
    }
    if (p.get('activated') === '1') {
        history.replaceState({}, document.title, location.pathname);
        showToast('success', 'Account activated! Welcome aboard.');
    }

    var countdownEl = document.getElementById('countdownNum');
    if (countdownEl) {
        var secs = 4;
        var interval = setInterval(function(){
            secs--;
            countdownEl.textContent = secs;
            if (secs <= 0) { clearInterval(interval); location.href = 'dashboard.php'; }
        }, 1000);
    }
});
</script>
</body>
</html>