<?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 * FROM users WHERE id = ?");
$stmt->bind_param("i", $userId); $stmt->execute();
$userData = $stmt->get_result()->fetch_assoc();

if ($userData['status'] !== 'active') {
    setFlash('error', 'You must activate your own account first before paying for others.');
    redirect('dashboard.php');
}

// ── Admin color injection (same pattern as side.php / login.php) ──────────
$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);

// Currency
$cStmt = $conn->prepare("SELECT activation_fee, currency_symbol, exchange_rate FROM countries WHERE name = ?");
$cStmt->bind_param("s", $userData['country']); $cStmt->execute();
$cd = $cStmt->get_result()->fetch_assoc();
$activationFee  = intval($cd['activation_fee']  ?? 200);
$currencySymbol = $cd['currency_symbol']         ?? 'Ksh';

// ── Downline lookup (AJAX) ──────────────────────────────────────────────────
if (isset($_GET['lookup'])) {
    header('Content-Type: application/json');
    $raw = preg_replace('/[^0-9]/', '', trim($_GET['lookup']));

    $formats = [];
    if (substr($raw,0,3)==='254') {
        $formats=[$raw,'0'.substr($raw,3),'+'.$raw,substr($raw,3)];
    } elseif (substr($raw,0,1)==='0') {
        $formats=[$raw,'254'.substr($raw,1),'+254'.substr($raw,1),substr($raw,1)];
    } else {
        $formats=[$raw,'0'.$raw,'254'.$raw,'+254'.$raw];
    }

    $ld = null;
    foreach ($formats as $fmt) {
        $ls = $conn->prepare("SELECT id, username, status, referred_by, country FROM users WHERE phone = ? LIMIT 1");
        $ls->bind_param("s", $fmt); $ls->execute();
        $row = $ls->get_result()->fetch_assoc();
        if ($row) { $ld = $row; break; }
    }

    if (!$ld)                              echo json_encode(['ok'=>false,'msg'=>'No account found with this phone number.']);
    elseif ($ld['status']==='active')      echo json_encode(['ok'=>false,'msg'=>'This account is already activated.']);
    elseif ($ld['referred_by'] != $userId) echo json_encode(['ok'=>false,'msg'=>'This user was not referred by you. You can only pay for your own direct downlines.']);
    else                                   echo json_encode(['ok'=>true,'username'=>$ld['username'],'country'=>$ld['country'],'id'=>$ld['id']]);
    exit;
}

// ── Form submission ─────────────────────────────────────────────────────────
$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $downlineRaw = preg_replace('/[^0-9]/', '', trim($_POST['downline_phone'] ?? ''));
    $payerRaw    = preg_replace('/[^0-9]/', '', trim($_POST['payer_phone']    ?? ''));
    $downlineId  = intval($_POST['downline_id'] ?? 0);

    $payerPhone = $payerRaw;
    if (substr($payerPhone,0,1)==='0')       $payerPhone = '254'.substr($payerPhone,1);
    elseif (substr($payerPhone,0,3)!=='254') $payerPhone = '254'.$payerPhone;

    $dlFormats = [];
    if (substr($downlineRaw,0,3)==='254') {
        $dlFormats=[$downlineRaw,'0'.substr($downlineRaw,3),'+'.$downlineRaw,substr($downlineRaw,3)];
    } elseif (substr($downlineRaw,0,1)==='0') {
        $dlFormats=[$downlineRaw,'254'.substr($downlineRaw,1),'+254'.substr($downlineRaw,1),substr($downlineRaw,1)];
    } else {
        $dlFormats=[$downlineRaw,'0'.$downlineRaw,'254'.$downlineRaw,'+254'.$downlineRaw];
    }

    if (!$downlineId || empty($downlineRaw)) {
        $error = 'Please look up a valid downline phone number first.';
    } elseif (strlen($payerPhone) < 11) {
        $error = 'Please enter a valid M-Pesa phone number.';
    } else {
        $vd = null;
        foreach ($dlFormats as $fmt) {
            $vs = $conn->prepare("SELECT id, username, status, referred_by FROM users WHERE id = ? AND phone = ? LIMIT 1");
            $vs->bind_param("is", $downlineId, $fmt); $vs->execute();
            $row = $vs->get_result()->fetch_assoc();
            if ($row) { $vd = $row; break; }
        }

        if (!$vd)                              $error = 'Downline account not found.';
        elseif ($vd['status']==='active')      $error = 'This account is already activated.';
        elseif ($vd['referred_by'] != $userId) $error = 'This user was not referred by you.';
        else {
            $_SESSION['paying_for_user_id']  = $vd['id'];
            $_SESSION['paying_for_username'] = $vd['username'];
            $_SESSION['payer_user_id']       = $userId;

            require_once '../mpesa/stk_push.php';
            $reference = 'CLIENT_'.$userId.'_FOR_'.$vd['id'].'_'.time();
            $meta = json_encode([
                'payer_id'            => $userId,
                'activating_user_id'  => $vd['id'],
                'activating_username' => $vd['username'],
                'payment_type'        => 'client_activation'
            ]);

            $ins = $conn->prepare("INSERT INTO transactions (user_id,wallet_type,amount,type,description,reference,status,meta_json) VALUES (?,'client_activation',?,'client_activation',?,?,'pending',?)");
            $desc = 'Activation payment for @'.$vd['username'];
            $ins->bind_param("idsss", $userId, $activationFee, $desc, $reference, $meta);
            $ins->execute();

            $result = initiate_stk($payerPhone, $activationFee, $reference);

            if ($result['success']) {
                $_SESSION['checkout_request_id'] = $result['CheckoutRequestID'];
                $crid = $result['CheckoutRequestID'];
                $upd = $conn->prepare("UPDATE transactions SET reference=? WHERE user_id=? AND reference=?");
                $upd->bind_param("sis", $crid, $userId, $reference); $upd->execute();
                redirect('activation_status.php');
            } else {
                $fail = $conn->prepare("UPDATE transactions SET status='failed' WHERE user_id=? AND reference=?");
                $fail->bind_param("is", $userId, $reference); $fail->execute();
                $error = $result['message'] ?? 'Failed to initiate payment. Please try again.';
            }
        }
    }
}
?>
<!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>Pay for Client — <?= htmlspecialchars($siteName) ?></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
<style>
/* ═══════════════════════════════════════════════════════════════
   EARNOVIX — Pay for Client
   Admin Color Injection · Light/Dark Mode · Matches login.php
   Standalone page (no sidebar) — same token system
═══════════════════════════════════════════════════════════════ */

: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:flex-start;
    padding:20px 14px 40px;
    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; }

/* ── Animated grid bg (dark only) ── */
[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 toggle ── */
.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 — matches .card from login.php ── */
.pay-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"] .pay-card { border-color:rgba(var(--Pr),.14); }
@keyframes cardIn { from{opacity:0;transform:translateY(18px)} to{opacity:1;transform:translateY(0)} }

/* Top glow line */
.pay-card::before {
    content:''; position:absolute; top:0; left:10%; right:10%; height:1px;
    background:linear-gradient(90deg,transparent,rgba(var(--Pr),.5),transparent);
}

/* ── HEADER — matches .brand-row from login.php ── */
.pay-head { text-align:center; margin-bottom:16px; }

.pay-icon-ring {
    width:46px; height:46px; border-radius:50%; margin:0 auto 10px;
    border:2.5px solid var(--P);
    display:flex; align-items:center; justify-content:center;
    box-shadow:0 0 14px rgba(var(--Pr),.35);
    animation:ringSpín 8s linear infinite;
}
@keyframes ringSpín { to { filter:hue-rotate(360deg); } }
.pay-icon-inner {
    width:calc(100% - 8px); height:calc(100% - 8px); border-radius:50%;
    background:var(--P-bg);
    display:flex; align-items:center; justify-content:center;
    font-size:17px; color:var(--P);
}

.pay-title { font-size:18px; font-weight:800; color:var(--txt); letter-spacing:-.4px; margin-bottom:2px; }
.pay-sub   { font-size:11px; color:var(--txt2); }

/* ── FEE PILL — matches .mpricerow from store.php ── */
.pay-fee {
    display:flex; align-items:center; justify-content:space-between;
    background:var(--bg3); border:1px solid var(--bdr);
    border-radius:12px; padding:10px 13px; margin-bottom:12px;
    transition:background .25s;
}
.pay-fee-left { display:flex; align-items:center; gap:10px; }
.pay-fee-ico  {
    width:32px; height:32px; border-radius:9px; flex-shrink:0;
    background:var(--WN-bg); border:1px solid rgba(245,158,11,.2);
    display:flex; align-items:center; justify-content:center;
    font-size:13px; color:var(--WN);
}
.pay-fee-lbl { font-size:9px; color:var(--txt2); font-weight:700; text-transform:uppercase; letter-spacing:.5px; }
.pay-fee-amt { font-size:18px; font-weight:900; color:var(--txt); letter-spacing:-.5px; font-variant-numeric:tabular-nums; }
.pay-fee-shield { font-size:18px; color:var(--P); opacity:.6; }

/* ── WARNING STRIP — matches .notif-bar / .aw-notice ── */
.pay-warn {
    display:flex; align-items:flex-start; gap:8px;
    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:9px 12px; margin-bottom:12px;
    font-size:11px; color:var(--txt2); line-height:1.5;
}
.pay-warn i { color:var(--WN); font-size:12px; margin-top:1px; flex-shrink:0; }
.pay-warn strong { color:var(--txt); font-weight:700; }

/* ── ERROR — matches .alert-error / .rc-alert.err ── */
.pay-err {
    display:flex; align-items:flex-start; gap:9px;
    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:9px 12px; margin-bottom:12px;
    animation:fadeUp .3s ease-out;
}
@keyframes fadeUp { from{opacity:0;transform:translateY(-8px)} to{opacity:1;transform:none} }
.pay-err i       { color:var(--DN); font-size:12px; flex-shrink:0; margin-top:1px; }
.pay-err-txt     { font-size:12px; color:var(--DN); font-weight:600; flex:1; line-height:1.5; }

/* ── SECTION LABEL — matches .sec-lbl from dashboard ── */
.fsec {
    font-size:9px; font-weight:700; letter-spacing:2px; text-transform:uppercase;
    color:var(--P); opacity:.7; margin-bottom:8px;
    display:flex; align-items:center; gap:8px;
}
.fsec::after {
    content:''; flex:1; height:1px;
    background:linear-gradient(90deg,rgba(var(--Pr),.3),transparent);
}

/* ── FORM FIELDS — identical to login.php inputs ── */
.fgrp { margin-bottom:12px; }
.finp-wrap { position:relative; }
.finp-ico {
    position:absolute; left:11px; top:50%; transform:translateY(-50%);
    color:var(--txt3); font-size:12px; pointer-events:none; transition:color .15s;
}
.finp {
    width:100%; height:42px; padding:0 14px 0 34px;
    background:var(--input-bg); border:1px solid var(--input-bdr);
    border-radius:10px; color:var(--txt); font-size:13px;
    outline:none; font-family:inherit; appearance:none;
    transition:border-color .15s,box-shadow .15s,background .15s;
}
.finp:focus {
    border-color:var(--P);
    box-shadow:0 0 0 3px rgba(var(--Pr),.14);
    background:var(--P-bg);
}
.finp::placeholder { color:var(--txt3); font-size:12px; }
.finp.ok  { border-color:var(--OK);  background:var(--OK-bg); }
.finp.err { border-color:var(--DN);  background:var(--DN-bg); }
.finp.ok:focus  { box-shadow:0 0 0 3px rgba(34,197,94,.15); }
.finp.err:focus { box-shadow:0 0 0 3px rgba(239,68,68,.15); }

/* Lookup button inside input */
.finp-action {
    position:absolute; right:5px; top:50%; transform:translateY(-50%);
    height:30px; padding:0 11px; border-radius:7px;
    background:var(--P); color:#fff;
    font-size:11px; font-weight:700; border:none; cursor:pointer;
    transition:all .18s; white-space:nowrap; font-family:inherit;
}
.finp-action:hover { filter:brightness(1.1); }
.finp-action:disabled { opacity:.4; cursor:not-allowed; }
[data-theme="light"] .finp-action { color:#fff; }
.has-action .finp { padding-right:86px; }

/* Lookup result — matches .ph-saved / lookup result styles */
.lookup-result {
    margin-top:7px; border-radius:0 9px 9px 0; padding:9px 12px;
    display:flex; align-items:center; gap:9px; border-left:3px solid;
    animation:fadeUp .25s ease both;
}
.lookup-result.found    { background:var(--OK-bg); border-color:var(--OK); }
.lookup-result.not-found{ background:var(--DN-bg); border-color:var(--DN); }
.lr-ico {
    width:28px; height:28px; border-radius:8px; flex-shrink:0;
    display:flex; align-items:center; justify-content:center; font-size:12px;
}
.lookup-result.found     .lr-ico { background:var(--OK-bg); color:var(--OK); }
.lookup-result.not-found .lr-ico { background:var(--DN-bg); color:var(--DN); }
.lr-body { flex:1; min-width:0; }
.lr-name    { font-size:12px; font-weight:700; color:var(--txt); margin-bottom:1px; }
.lr-country { font-size:10px; color:var(--txt2); }
.lr-msg     { font-size:11.5px; color:var(--DN); font-weight:600; }

/* Helper text */
.fhelp {
    font-size:10px; color:var(--txt3); margin-top:4px;
    display:flex; align-items:center; gap:4px;
}
.fhelp i { font-size:9px; }

/* ── DIVIDER ── */
.pay-div {
    height:1px; margin:12px 0;
    background:linear-gradient(90deg,transparent,var(--bdr),transparent);
}

/* ── SUBMIT BUTTON — matches .copy-btn / .rc-btn ── */
.pay-btn {
    width:100%; height:46px; border-radius:12px; border:none; cursor:pointer;
    background:var(--P); color:#fff;
    font-size:14px; font-weight:800; font-family:inherit;
    display:flex; align-items:center; justify-content:center; gap:8px;
    box-shadow:0 4px 18px rgba(var(--Pr),.35);
    transition:all .2s; position:relative; overflow:hidden;
}
.pay-btn::before {
    content:''; position:absolute; top:0; left:-100%; width:100%; height:100%;
    background:linear-gradient(90deg,transparent,rgba(255,255,255,.15),transparent);
    transition:left .5s;
}
.pay-btn:hover:not(:disabled) { filter:brightness(1.1); transform:translateY(-2px); box-shadow:0 8px 24px rgba(var(--Pr),.45); }
.pay-btn:hover::before { left:100%; }
.pay-btn:active { transform:scale(.98); }
.pay-btn:disabled { opacity:.45; cursor:not-allowed; transform:none; box-shadow:none; }
[data-theme="light"] .pay-btn { color:#fff; }

/* ── BACK LINK ── */
.pay-back {
    display:flex; align-items:center; justify-content:center; gap:6px;
    margin-top:14px; color:var(--txt3); text-decoration:none;
    font-size:12px; font-weight:600; transition:color .2s;
}
.pay-back:hover { color:var(--txt2); }

/* ── Spinner ── */
.spin {
    display:inline-block; width:14px; height:14px;
    border:2px solid rgba(255,255,255,.3); border-top-color:#fff;
    border-radius:50%; animation:sp .6s linear infinite;
}
@keyframes sp { to { transform:rotate(360deg); } }
</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>

<!-- Theme toggle -->
<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="pay-card">

    <!-- Header -->
    <div class="pay-head">
        <div class="pay-icon-ring">
            <div class="pay-icon-inner"><i class="fa-solid fa-user-plus"></i></div>
        </div>
        <div class="pay-title">Pay for Client</div>
        <div class="pay-sub">Activate your direct downline's account</div>
    </div>

    <!-- Fee display -->
    <div class="pay-fee">
        <div class="pay-fee-left">
            <div class="pay-fee-ico"><i class="fa-solid fa-bolt-lightning"></i></div>
            <div>
                <div class="pay-fee-lbl">Activation Fee</div>
                <div class="pay-fee-amt"><?= $currencySymbol ?> <?= number_format($activationFee,0) ?></div>
            </div>
        </div>
        <i class="fa-solid fa-shield-check pay-fee-shield"></i>
    </div>

    <!-- Warning -->
    <div class="pay-warn">
        <i class="fa-solid fa-triangle-exclamation"></i>
        <div>
            <strong>Direct downlines only.</strong> You can only activate accounts that were directly referred by you.
        </div>
    </div>

    <!-- Error -->
    <?php if ($error): ?>
    <div class="pay-err">
        <i class="fa-solid fa-circle-exclamation"></i>
        <div class="pay-err-txt"><?= htmlspecialchars($error) ?></div>
    </div>
    <?php endif; ?>

    <!-- Form -->
    <form method="POST" id="payForm">
        <input type="hidden" name="downline_id"    id="downline_id"           value="">
        <input type="hidden" name="downline_phone"  id="downline_phone_hidden"  value="">

        <!-- Step 1 — Downline lookup -->
        <div class="fsec"><i class="fa-solid fa-magnifying-glass" style="font-size:9px"></i>Step 1 — Find Downline</div>
        <div class="fgrp">
            <div class="finp-wrap has-action">
                <i class="fa-solid fa-phone finp-ico"></i>
                <input type="tel" id="dlPhone" class="finp"
                    placeholder="07XX XXX XXX"
                    value="<?= htmlspecialchars($_POST['downline_phone_display'] ?? '') ?>"
                    autocomplete="off">
                <button type="button" class="finp-action" id="lookupBtn" onclick="lookupDownline()">
                    Look Up
                </button>
            </div>
            <div class="fhelp"><i class="fa-solid fa-circle-info"></i> Enter your downline's registered phone number</div>
            <div id="lookupResult"></div>
        </div>

        <div class="pay-div"></div>

        <!-- Step 2 — M-Pesa number -->
        <div class="fsec"><i class="fa-solid fa-sim-card" style="font-size:9px"></i>Step 2 — Your M-Pesa</div>
        <div class="fgrp">
            <div class="finp-wrap">
                <i class="fa-solid fa-sim-card finp-ico"></i>
                <input type="tel" name="payer_phone" class="finp"
                    placeholder="07XX XXX XXX"
                    value="<?= htmlspecialchars($_POST['payer_phone'] ?? $userData['phone'] ?? '') ?>">
            </div>
            <div class="fhelp"><i class="fa-solid fa-mobile-alt"></i> STK push will be sent to this number</div>
        </div>

        <!-- Submit -->
        <button type="submit" class="pay-btn" id="submitBtn" disabled>
            <i class="fa-solid fa-lock-open"></i>
            Pay <?= $currencySymbol ?> <?= number_format($activationFee,0) ?> via M-Pesa
        </button>
    </form>

    <a href="dashboard.php" class="pay-back">
        <i class="fa-solid fa-arrow-left"></i> Back to Dashboard
    </a>

</div>

<script>
/* ── Theme engine (identical to login.php) ── */
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);
};

/* ── Downline lookup ── */
(function(){
    var foundId = 0;

    window.lookupDownline = function() {
        var phone = document.getElementById('dlPhone').value.trim();
        if (!phone) { return; }

        var btn = document.getElementById('lookupBtn');
        var inp = document.getElementById('dlPhone');
        var res = document.getElementById('lookupResult');
        var sub = document.getElementById('submitBtn');

        btn.disabled = true;
        btn.innerHTML = '<span class="spin"></span>';
        res.innerHTML = '';
        inp.className = 'finp';
        sub.disabled  = true;
        foundId = 0;
        document.getElementById('downline_id').value          = '';
        document.getElementById('downline_phone_hidden').value = '';

        fetch('pay.php?lookup=' + encodeURIComponent(phone))
            .then(function(r){ return r.json(); })
            .then(function(d){
                btn.disabled    = false;
                btn.textContent = 'Look Up';

                if (d.ok) {
                    inp.className = 'finp ok';
                    foundId = d.id;
                    document.getElementById('downline_id').value           = d.id;
                    document.getElementById('downline_phone_hidden').value = phone;
                    sub.disabled = false;

                    res.innerHTML =
                        '<div class="lookup-result found">' +
                            '<div class="lr-ico"><i class="fa-solid fa-circle-check"></i></div>' +
                            '<div class="lr-body">' +
                                '<div class="lr-name"><i class="fa-solid fa-user" style="font-size:10px;margin-right:4px;opacity:.6"></i>' + esc(d.username) + '</div>' +
                                '<div class="lr-country"><i class="fa-solid fa-earth-africa" style="font-size:9px;margin-right:3px"></i>' + esc(d.country) + ' &nbsp;·&nbsp; Inactive — ready to activate</div>' +
                            '</div>' +
                        '</div>';
                } else {
                    inp.className = 'finp err';
                    res.innerHTML =
                        '<div class="lookup-result not-found">' +
                            '<div class="lr-ico"><i class="fa-solid fa-circle-xmark"></i></div>' +
                            '<div class="lr-body"><div class="lr-msg">' + esc(d.msg) + '</div></div>' +
                        '</div>';
                }
            })
            .catch(function(){
                btn.disabled    = false;
                btn.textContent = 'Look Up';
                res.innerHTML =
                    '<div class="lookup-result not-found">' +
                        '<div class="lr-ico"><i class="fa-solid fa-wifi"></i></div>' +
                        '<div class="lr-body"><div class="lr-msg">Network error. Please try again.</div></div>' +
                    '</div>';
            });
    };

    function esc(s) {
        return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    }

    document.getElementById('dlPhone').addEventListener('keydown', function(e){
        if (e.key === 'Enter') { e.preventDefault(); lookupDownline(); }
    });

    document.getElementById('payForm').addEventListener('submit', function(){
        var btn = document.getElementById('submitBtn');
        btn.disabled = true;
        btn.innerHTML = '<span class="spin"></span> Sending STK Push…';
    });

    /* Input icon color on focus — matches login.php */
    document.querySelectorAll('.finp').forEach(function(inp){
        inp.addEventListener('focus', function(){
            var ico = this.parentElement.querySelector('.finp-ico');
            if (ico) ico.style.color = 'var(--P)';
        });
        inp.addEventListener('blur', function(){
            var ico = this.parentElement.querySelector('.finp-ico');
            if (ico) ico.style.color = 'var(--txt3)';
        });
    });
}());
</script>
</body>
</html>