<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
$pageTitle = 'My Profile';
include 'side.php';
$conn = getConnection();

// ── Admin colors already set in side.php ─────────────────────────────────────
// $adminPrimary / $adminSuccess / $adminWarning / $adminDanger / $pRgb available

/* ── BACKEND — UNCHANGED ── */
$stmt=$conn->prepare("SELECT * FROM users WHERE id=?");
$stmt->bind_param("i",$userId); $stmt->execute();
$userData=$stmt->get_result()->fetch_assoc();

if($_SERVER['REQUEST_METHOD']==='POST'&&isset($_POST['change_password'])){
    $old=sanitize($_POST['old_password']);
    $new=sanitize($_POST['new_password']);
    $con=sanitize($_POST['confirm_password']);
    if($new!==$con) setFlash('error','Passwords do not match!');
    elseif(strlen($new)<6) setFlash('error','Password must be at least 6 characters!');
    elseif(verifyPassword($old,$userData['password'])){
        $hp=hashPassword($new);
        $st=$conn->prepare("UPDATE users SET password=? WHERE id=?");
        $st->bind_param("si",$hp,$userId);
        setFlash($st->execute()?'success':'error',$st->execute()?'Password changed!':'Failed to update password.');
        redirect('profile.php');
    } else { setFlash('error','Current password is incorrect!'); }
}

if($_SERVER['REQUEST_METHOD']==='POST'&&isset($_POST['update_profile'])){
    $phone=sanitize($_POST['phone']);
    $country=sanitize($_POST['country']);
    $st=$conn->prepare("UPDATE users SET phone=?,country=? WHERE id=?");
    $st->bind_param("ssi",$phone,$country,$userId);
    setFlash($st->execute()?'success':'error',$st->execute()?'Profile updated!':'Failed to update.');
    redirect('profile.php');
}

$upline=null;
if(!empty($userData['referred_by'])){
    $st=$conn->prepare("SELECT id,username,country FROM users WHERE id=?");
    $st->bind_param("i",$userData['referred_by']); $st->execute();
    $upline=$st->get_result()->fetch_assoc();
}

$stats=$conn->query("SELECT
  (SELECT COUNT(*) FROM users WHERE referred_by=$userId) as refs,
  (SELECT COUNT(*) FROM users WHERE referred_by=$userId AND status='active') as arefs,
  (SELECT SUM(net_amount) FROM withdrawals WHERE user_id=$userId AND status='completed') as withdrawn,
  (SELECT COUNT(*) FROM transactions WHERE user_id=$userId) as txns
")->fetch_assoc();
$stats['refs']     =intval($stats['refs']??0);
$stats['arefs']    =intval($stats['arefs']??0);
$stats['withdrawn']=floatval($stats['withdrawn']??0);
$stats['txns']     =intval($stats['txns']??0);

$actQ =$conn->query("SELECT description,amount,created_at FROM transactions WHERE user_id=$userId ORDER BY created_at DESC LIMIT 5");
$ctryQ=$conn->query("SELECT name FROM countries ORDER BY name");

$flash      = getFlash();
$initials   = strtoupper(substr($userData['username'],0,2));
$cs         = $cd['currency_symbol'] ?? 'KSh';
$refLink    = (defined('SITE_URL')?SITE_URL:'').'/register.php?ref='.($userData['referral_code']??'');
$isActive   = ($userData['status']  ?? '') === 'active';
$isVerified = ($userData['verified'] ?? 0) == 1;
?>
<style>
/* ═══════════════════════════════════════════════════════════════
   EARNOVIX — Profile Page
   Uses CSS vars from side.php — no :root redeclaration
   Fully responsive: 320px → desktop
═══════════════════════════════════════════════════════════════ */

.pr { padding:14px 14px 90px; }
@media(max-width:480px) { .pr { padding:10px 10px 90px; } }

/* ── Flash — matches .sfl from store/dashboard ── */
.pr-flash {
    display:flex; align-items:center; gap:8px;
    padding:9px 13px; border-radius:0 10px 10px 0;
    font-size:12px; font-weight:600; margin-bottom:14px;
    border-left:3px solid; animation:prIn .3s ease both;
}
.pr-flash.success { background:var(--OK-bg); color:var(--OK); border-color:var(--OK); }
.pr-flash.error   { background:var(--DN-bg); color:var(--DN); border-color:var(--DN); }
.pr-flash.warning { background:var(--WN-bg); color:var(--WN); border-color:var(--WN); }

/* ── IDENTITY CARD — matches .hstat.prime + .wcard pattern ── */
.pr-idcard {
    background:var(--card); border:1px solid var(--bdr);
    border-radius:16px; padding:16px; margin-bottom:14px;
    display:flex; align-items:flex-start; gap:14px;
    transition:background .25s, border-color .25s;
    position:relative; overflow:hidden;
}
[data-theme="dark"] .pr-idcard { border-color:rgba(var(--Pr),.14); }
/* Top accent — matches .wcard::before */
.pr-idcard::before {
    content:''; position:absolute; top:0; left:0; right:0; height:3px;
    background:linear-gradient(90deg,var(--P),rgba(var(--Pr),.0));
    border-radius:16px 16px 0 0;
}

/* Avatar */
.pr-av {
    width:60px; height:60px; flex-shrink:0; border-radius:14px;
    display:flex; align-items:center; justify-content:center;
    font-size:22px; font-weight:900; color:#fff;
    position:relative; background:var(--P);
    box-shadow:0 4px 14px rgba(var(--Pr),.35);
}
[data-theme="light"] .pr-av { color:#fff; }
.pr-av.verified { box-shadow:0 0 0 3px var(--card), 0 0 0 5px var(--OK); }
.pr-av-badge {
    position:absolute; bottom:-4px; right:-4px;
    width:18px; height:18px; border-radius:50%;
    background:var(--OK); border:2px solid var(--card);
    display:flex; align-items:center; justify-content:center;
    font-size:8px; color:#fff;
}

/* Identity text */
.pr-id-info { flex:1; min-width:0; }
.pr-id-name {
    font-size:17px; font-weight:900; color:var(--txt);
    letter-spacing:-.4px; margin-bottom:4px;
    white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
}
.pr-id-email {
    font-size:11px; color:var(--txt2); margin-bottom:8px;
    display:flex; align-items:center; gap:5px; min-width:0; overflow:hidden;
}
.pr-id-email span { white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.pr-id-email i { font-size:9px; color:var(--txt3); flex-shrink:0; }

/* Tags — matches .badge-up / .sbadge pattern */
.pr-id-tags { display:flex; gap:5px; flex-wrap:wrap; }
.pr-tag {
    display:inline-flex; align-items:center; gap:4px;
    padding:3px 8px; border-radius:6px;
    font-size:9.5px; font-weight:700;
    border:1px solid var(--bdr);
    background:var(--bg3); color:var(--txt2); white-space:nowrap;
}
.pr-tag.active   { background:var(--OK-bg); color:var(--OK); border-color:rgba(34,197,94,.2); }
.pr-tag.inactive { background:var(--WN-bg); color:var(--WN); border-color:rgba(245,158,11,.2); }
.pr-tag.verified { background:var(--P-bg);  color:var(--P);  border-color:rgba(var(--Pr),.2); }

/* Ref code pill */
.pr-id-right { flex-shrink:0; }
.pr-refcode {
    display:flex; flex-direction:column; align-items:center;
    padding:10px 14px; background:var(--bg3); border:1px solid var(--bdr);
    border-radius:12px; text-align:center; min-width:90px;
    transition:background .25s;
}
.pr-refcode-lbl {
    font-size:8px; font-weight:800; letter-spacing:1.5px;
    text-transform:uppercase; color:var(--txt2); margin-bottom:4px;
}
.pr-refcode-val {
    font-size:14px; font-weight:900; color:var(--P);
    font-family:monospace; letter-spacing:1px; margin-bottom:6px;
}
/* Copy btn — matches .pr-ref-copy / .cg-btn */
.pr-copy-btn {
    padding:5px 10px; border-radius:7px;
    background:var(--P); color:#fff; border:none;
    font-size:9.5px; font-weight:700; cursor:pointer;
    font-family:inherit; transition:.15s;
    display:flex; align-items:center; gap:4px;
}
.pr-copy-btn:hover { filter:brightness(1.1); }
[data-theme="light"] .pr-copy-btn { color:#fff; }

/* Mobile: hide right ref panel, show ref tag */
.pr-refcode-mobile { display:none; }
@media(max-width:480px) {
    .pr-idcard { padding:13px 12px; gap:11px; }
    .pr-av { width:52px; height:52px; font-size:18px; border-radius:12px; }
    .pr-id-name { font-size:15px; }
    .pr-id-right { display:none; }
    .pr-refcode-mobile { display:inline-flex; }
}

/* ── 4 STAT PILLS — matches .pr-stat / .hstat pattern ── */
.pr-stats {
    display:grid; grid-template-columns:repeat(2,1fr); gap:8px; margin-bottom:14px;
}
@media(min-width:600px) { .pr-stats { grid-template-columns:repeat(4,1fr); } }

.pr-stat {
    background:var(--card); border:1px solid var(--bdr);
    border-radius:12px; padding:13px 13px 11px;
    border-bottom:3px solid transparent;
    transition:background .25s, border-color .2s;
    min-height:72px; display:flex; flex-direction:column; justify-content:space-between;
}
.pr-stat.s1 { border-bottom-color:var(--P); }
.pr-stat.s2 { border-bottom-color:var(--OK); }
.pr-stat.s3 { border-bottom-color:var(--WN); }
.pr-stat.s4 { border-bottom-color:var(--DN); }
.pr-stat-n {
    font-size:20px; font-weight:900; letter-spacing:-.5px; line-height:1;
    font-variant-numeric:tabular-nums;
    overflow:hidden; text-overflow:ellipsis; white-space:nowrap;
}
.pr-stat-n.text-val { font-size:16px; letter-spacing:0; font-weight:800; }
.pr-stat.s1 .pr-stat-n { color:var(--P);  }
.pr-stat.s2 .pr-stat-n { color:var(--OK); }
.pr-stat.s3 .pr-stat-n { color:var(--WN); }
.pr-stat.s4 .pr-stat-n { color:var(--DN); }
.pr-stat-l {
    font-size:9px; font-weight:700; letter-spacing:.8px;
    text-transform:uppercase; color:var(--txt2); margin-top:6px;
}

/* ── TWO-COL GRID ── */
.pr-grid { display:grid; grid-template-columns:1fr; gap:12px; }
@media(min-width:700px) { .pr-grid { grid-template-columns:1fr 1fr; } }

/* ── SECTION CARD — matches .chart-card / .net-card from dashboard ── */
.pr-sec {
    background:var(--card); border:1px solid var(--bdr);
    border-radius:14px; overflow:hidden;
    transition:background .25s, border-color .25s;
    width:100%;
}
.pr-sec-hdr {
    display:flex; align-items:center; gap:10px;
    padding:11px 14px; border-bottom:1px solid var(--bdr);
    background:var(--bg3); transition:background .25s;
}
/* Icon — matches .hstat-ico */
.pr-sec-ico {
    width:26px; height:26px; border-radius:7px;
    display:flex; align-items:center; justify-content:center;
    font-size:11px; color:#fff; flex-shrink:0;
}
[data-theme="light"] .pr-sec-ico { color:#fff; }
/* Title — matches .card-title */
.pr-sec-title { font-size:13px; font-weight:700; color:var(--txt); }

/* ── INFO TABLE ── */
.pr-info-row {
    display:flex; align-items:center; padding:9px 14px;
    border-bottom:1px solid var(--bdr); gap:10px; flex-wrap:wrap;
}
.pr-info-row:last-child { border-bottom:none; }
.pr-info-key {
    font-size:10px; font-weight:700; letter-spacing:.5px;
    text-transform:uppercase; color:var(--txt2);
    width:74px; flex-shrink:0;
}
.pr-info-val {
    flex:1; font-size:12.5px; font-weight:600; color:var(--txt);
    min-width:0; word-break:break-word; overflow-wrap:anywhere;
}
@media(max-width:340px) {
    .pr-info-row { flex-direction:column; align-items:flex-start; gap:2px; }
    .pr-info-key { width:auto; }
}

/* Ref link strip — matches .link-strip from dashboard */
.pr-ref-strip {
    display:flex; align-items:center; gap:6px;
    padding:8px 10px; background:var(--bg3); border:1px solid var(--bdr);
    border-radius:8px; margin:8px 14px 13px;
    transition:background .25s;
}
.pr-ref-url {
    flex:1; min-width:0; font-family:monospace; font-size:10px;
    color:var(--P); white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
}
.pr-ref-copy {
    padding:5px 11px; background:var(--P); color:#fff;
    border:none; border-radius:7px; font-size:10px; font-weight:700;
    cursor:pointer; font-family:inherit; transition:.15s; flex-shrink:0; white-space:nowrap;
}
.pr-ref-copy:hover { filter:brightness(1.1); }
[data-theme="light"] .pr-ref-copy { color:#fff; }

/* ── UPLINE CARD ── */
.pr-upline { display:flex; align-items:center; gap:12px; padding:14px; }
.pr-upline-av {
    width:42px; height:42px; border-radius:11px; flex-shrink:0;
    display:flex; align-items:center; justify-content:center;
    font-size:16px; font-weight:900; color:#fff; background:var(--P);
}
[data-theme="light"] .pr-upline-av { color:#fff; }
.pr-upline-name { font-size:13px; font-weight:700; color:var(--txt); margin-bottom:2px; }
.pr-upline-sub  { font-size:11px; color:var(--txt2); display:flex; align-items:center; gap:4px; }
.pr-upline-sub i { font-size:9px; color:var(--txt3); }

.pr-no-upline { padding:24px 14px; text-align:center; }
.pr-no-upline-ic {
    width:44px; height:44px; border-radius:12px;
    background:var(--bg3); border:1px solid var(--bdr);
    display:flex; align-items:center; justify-content:center;
    font-size:18px; color:var(--txt3); margin:0 auto 8px;
}
.pr-no-upline-t { font-size:12px; color:var(--txt2); }

/* ── FORM FIELDS — matches .pr-inp/withdraw/recharge style ── */
.pr-form-body { padding:13px 14px; box-sizing:border-box; width:100%; }
.pr-fg { margin-bottom:11px; }
.pr-fg:last-child { margin-bottom:0; }

/* Label — matches .field-lbl / .pr-lbl from other pages */
.pr-lbl {
    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;
}
.pr-lbl i { font-size:9px; color:var(--P); }

/* Input — matches register.php / login.php inputs */
.pr-inp, .pr-sel {
    width:100%; height:42px; padding:0 12px;
    background:var(--bg3); border:1px solid var(--bdr);
    border-radius:9px; color:var(--txt);
    font-size:13px; font-family:inherit; outline:none;
    transition:border-color .15s, background .15s, box-shadow .15s;
    appearance:none; -webkit-appearance:none;
    box-sizing:border-box; max-width:100%;
}
.pr-inp::placeholder { color:var(--txt3); }
.pr-inp:focus, .pr-sel:focus {
    border-color:var(--P);
    background:var(--P-bg);
    box-shadow:0 0 0 3px rgba(var(--Pr),.12);
}
.pr-inp[readonly], .pr-sel:disabled {
    opacity:.5; cursor:not-allowed; background:var(--bg3);
}
/* Custom select arrow */
.pr-sel {
    background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6'%3E%3Cpath d='M0 0l5 6 5-6z' fill='%236b7280'/%3E%3C/svg%3E");
    background-repeat:no-repeat; background-position:right 10px center;
    padding-right:28px;
}
[data-theme="dark"] .pr-sel {
    background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6'%3E%3Cpath d='M0 0l5 6 5-6z' fill='rgba(255,255,255,.4)'/%3E%3C/svg%3E");
}
[data-theme="light"] .pr-sel option,
[data-theme="light"] select option { background:#fff; color:#111; }
[data-theme="dark"]  .pr-sel option { background:#141228; color:#fff; }

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

/* Password toggle */
.pr-pw-wrap { position:relative; }
.pr-pw-wrap .pr-inp { padding-right:42px; }
.pr-pw-eye {
    position:absolute; right:11px; top:50%; transform:translateY(-50%);
    background:none; border:none; color:var(--txt3);
    cursor:pointer; font-size:13px; padding:0;
    display:flex; align-items:center; transition:.15s;
}
.pr-pw-eye:hover { color:var(--P); }

/* Submit — matches .copy-btn / .pr-submit from other pages */
.pr-submit {
    width:100%; height:42px; border:none; border-radius:10px;
    font-size:13px; font-weight:800; cursor:pointer;
    display:flex; align-items:center; justify-content:center; gap:7px;
    font-family:inherit; background:var(--P); color:#fff;
    transition:.18s; margin-top:4px;
    box-sizing:border-box; max-width:100%;
    box-shadow:0 3px 12px rgba(var(--Pr),.3);
}
.pr-submit:hover { filter:brightness(1.1); transform:translateY(-1px); box-shadow:0 5px 18px rgba(var(--Pr),.4); }
[data-theme="light"] .pr-submit { color:#fff; }
.pr-submit.amber {
    background:var(--WN);
    box-shadow:0 3px 12px rgba(245,158,11,.3);
}
.pr-submit.amber:hover { box-shadow:0 5px 18px rgba(245,158,11,.4); }

/* ── ACTIVITY LIST ── */
.pr-act-row {
    display:flex; align-items:center; gap:11px;
    padding:11px 14px; border-bottom:1px solid var(--bdr);
    transition:background .12s;
}
.pr-act-row:last-child { border-bottom:none; }
.pr-act-row:hover { background:var(--P-bg); }

/* Activity icon — matches .hstat-ico */
.pr-act-ico {
    width:32px; height:32px; border-radius:9px; flex-shrink:0;
    background:var(--P-bg); color:var(--P);
    border:1px solid rgba(var(--Pr),.2);
    display:flex; align-items:center; justify-content:center; font-size:11px;
}
.pr-act-info { flex:1; min-width:0; }
.pr-act-desc {
    font-size:12px; font-weight:600; color:var(--txt);
    white-space:nowrap; overflow:hidden; text-overflow:ellipsis; margin-bottom:2px;
}
.pr-act-time { font-size:10px; color:var(--txt2); }
.pr-act-amt  { font-size:13px; font-weight:800; color:var(--OK); flex-shrink:0; font-variant-numeric:tabular-nums; white-space:nowrap; }
.pr-act-empty { padding:24px; text-align:center; color:var(--txt2); font-size:12px; }

/* ── TOAST — identical to dashboard .db-toast ── */
#prToast {
    position:fixed; top:-80px; left:50%; transform:translateX(-50%);
    min-width:240px; 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,.25);
}
#prToast.show { top:calc(var(--hh) + 10px); }
#prToastIco {
    width:24px; height:24px; border-radius:7px;
    display:flex; align-items:center; justify-content:center;
    font-size:11px; color:#fff; flex-shrink:0;
}
[data-theme="light"] #prToastIco { color:#fff; }
#prToastMsg { font-size:12px; font-weight:600; color:var(--txt); flex:1; min-width:0; }
#prToastX {
    position:absolute; right:10px; top:50%; transform:translateY(-50%);
    background:none; border:none; font-size:17px; color:var(--txt3); cursor:pointer; padding:0;
}

/* ── Animations ── */
@keyframes prIn { from{opacity:0;transform:translateY(8px)} to{opacity:1;transform:none} }
.pr-idcard { animation:prIn .35s ease both; }
.pr-stats  { animation:prIn .35s ease .05s both; }
.pr-grid   { animation:prIn .35s ease .10s both; }
</style>

<div class="pr">

    <!-- Flash -->
    <?php if ($flash): ?>
    <div class="pr-flash <?= $flash['type'] ?>">
        <i class="fa-solid fa-<?= $flash['type']==='success'?'circle-check':($flash['type']==='error'?'circle-xmark':'triangle-exclamation') ?>"></i>
        <?= htmlspecialchars($flash['message']) ?>
    </div>
    <?php endif; ?>

    <!-- ── IDENTITY CARD ── -->
    <div class="pr-idcard">
        <div class="pr-av <?= $isVerified?'verified':'' ?>">
            <?= $initials ?>
            <?php if ($isVerified): ?>
            <div class="pr-av-badge"><i class="fa-solid fa-check"></i></div>
            <?php endif; ?>
        </div>

        <div class="pr-id-info">
            <div class="pr-id-name"><?= htmlspecialchars($userData['username']) ?></div>
            <div class="pr-id-email">
                <i class="fa-solid fa-envelope"></i>
                <span><?= htmlspecialchars($userData['email']) ?></span>
            </div>
            <div class="pr-id-tags">
                <span class="pr-tag <?= $userData['status'] ?>">
                    <i class="fa-solid fa-circle" style="font-size:6px"></i>
                    <?= ucfirst($userData['status']) ?>
                </span>
                <?php if ($isVerified): ?>
                <span class="pr-tag verified">
                    <i class="fa-solid fa-shield-check" style="font-size:9px"></i>
                    Verified
                </span>
                <?php endif; ?>
                <span class="pr-tag">
                    <i class="fa-solid fa-earth-africa" style="font-size:9px"></i>
                    <?= htmlspecialchars($userData['country'] ?? '—') ?>
                </span>
                <span class="pr-tag">
                    <i class="fa-regular fa-calendar" style="font-size:9px"></i>
                    <?= formatKenyanTime($userData['created_at'],'M Y') ?>
                </span>
                <!-- Mobile-only ref code tag -->
                <span class="pr-tag pr-refcode-mobile" style="color:var(--P);background:var(--P-bg);border-color:rgba(var(--Pr),.2)">
                    <i class="fa-solid fa-hashtag" style="font-size:9px"></i>
                    <?= htmlspecialchars($userData['referral_code'] ?? '—') ?>
                </span>
            </div>
        </div>

        <!-- Ref code panel (hidden on mobile) -->
        <div class="pr-id-right">
            <div class="pr-refcode">
                <div class="pr-refcode-lbl">Ref Code</div>
                <div class="pr-refcode-val"><?= htmlspecialchars($userData['referral_code'] ?? '—') ?></div>
                <button class="pr-copy-btn" onclick="copyRefCode()">
                    <i class="fa-regular fa-copy"></i> Copy
                </button>
            </div>
        </div>
    </div>

    <!-- ── 4 STAT PILLS ── -->
    <div class="pr-stats">
        <div class="pr-stat s1">
            <div class="pr-stat-n"><?= number_format($stats['refs']) ?></div>
            <div class="pr-stat-l"><?= $stats['arefs'] ?> active</div>
        </div>
        <div class="pr-stat s2">
            <div class="pr-stat-n"><?= $cs.' '.number_format($stats['withdrawn'],0) ?></div>
            <div class="pr-stat-l">Withdrawn</div>
        </div>
        <div class="pr-stat s3">
            <div class="pr-stat-n"><?= number_format($stats['txns']) ?></div>
            <div class="pr-stat-l">Transactions</div>
        </div>
        <div class="pr-stat s4">
            <div class="pr-stat-n text-val"><?= $isActive?'Active':'Inactive' ?></div>
            <div class="pr-stat-l">Account</div>
        </div>
    </div>

    <!-- ── MAIN GRID ── -->
    <div class="pr-grid">

        <!-- LEFT COL -->
        <div style="display:flex;flex-direction:column;gap:12px">

            <!-- Account details -->
            <div class="pr-sec">
                <div class="pr-sec-hdr">
                    <div class="pr-sec-ico" style="background:var(--P)"><i class="fa-solid fa-id-card"></i></div>
                    <span class="pr-sec-title">Account Details</span>
                </div>
                <div class="pr-info-row">
                    <span class="pr-info-key">Username</span>
                    <span class="pr-info-val"><?= htmlspecialchars($userData['username']) ?></span>
                </div>
                <div class="pr-info-row">
                    <span class="pr-info-key">Email</span>
                    <span class="pr-info-val" style="font-size:11.5px"><?= htmlspecialchars($userData['email']) ?></span>
                </div>
                <div class="pr-info-row">
                    <span class="pr-info-key">Phone</span>
                    <span class="pr-info-val"><?= htmlspecialchars($userData['phone'] ?? 'Not set') ?></span>
                </div>
                <div class="pr-info-row">
                    <span class="pr-info-key">Country</span>
                    <span class="pr-info-val"><?= htmlspecialchars($userData['country'] ?? 'Not set') ?></span>
                </div>
                <div class="pr-info-row">
                    <span class="pr-info-key">Joined</span>
                    <span class="pr-info-val"><?= formatKenyanTime($userData['created_at'],'M j, Y') ?></span>
                </div>
                <div class="pr-ref-strip">
                    <span class="pr-ref-url" id="refLinkUrl"><?= htmlspecialchars($refLink) ?></span>
                    <button class="pr-ref-copy" onclick="copyRefLink()">
                        <i class="fa-solid fa-link"></i> Copy Link
                    </button>
                </div>
            </div>

            <!-- Upline -->
            <div class="pr-sec">
                <div class="pr-sec-hdr">
                    <div class="pr-sec-ico" style="background:var(--WN)"><i class="fa-solid fa-user-tie"></i></div>
                    <span class="pr-sec-title">Referred By</span>
                </div>
                <?php if ($upline): ?>
                <div class="pr-upline">
                    <div class="pr-upline-av"><?= strtoupper(substr($upline['username'],0,2)) ?></div>
                    <div>
                        <div class="pr-upline-name"><?= htmlspecialchars($upline['username']) ?></div>
                        <div class="pr-upline-sub">
                            <i class="fa-solid fa-location-dot"></i>
                            <?= htmlspecialchars($upline['country'] ?? '—') ?>
                        </div>
                    </div>
                </div>
                <?php else: ?>
                <div class="pr-no-upline">
                    <div class="pr-no-upline-ic"><i class="fa-solid fa-user-slash"></i></div>
                    <div class="pr-no-upline-t">You joined without a referrer</div>
                </div>
                <?php endif; ?>
            </div>

            <!-- Recent activity -->
            <div class="pr-sec">
                <div class="pr-sec-hdr">
                    <div class="pr-sec-ico" style="background:var(--OK)"><i class="fa-solid fa-bolt"></i></div>
                    <span class="pr-sec-title">Recent Activity</span>
                </div>
                <?php if ($actQ && $actQ->num_rows > 0):
                    while ($a = $actQ->fetch_assoc()): ?>
                <div class="pr-act-row">
                    <div class="pr-act-ico"><i class="fa-solid fa-arrow-right-arrow-left"></i></div>
                    <div class="pr-act-info">
                        <div class="pr-act-desc"><?= htmlspecialchars($a['description']) ?></div>
                        <div class="pr-act-time"><?= timeAgoKenyan($a['created_at']) ?></div>
                    </div>
                    <?php if ($a['amount'] > 0): ?>
                    <div class="pr-act-amt">+<?= $cs.' '.number_format($a['amount'],2) ?></div>
                    <?php endif; ?>
                </div>
                    <?php endwhile;
                else: ?>
                <div class="pr-act-empty">No recent activity yet</div>
                <?php endif; ?>
            </div>

        </div><!-- /left col -->

        <!-- RIGHT COL — forms -->
        <div style="display:flex;flex-direction:column;gap:12px">

            <!-- Update profile -->
            <div class="pr-sec">
                <div class="pr-sec-hdr">
                    <div class="pr-sec-ico" style="background:var(--P)"><i class="fa-solid fa-pen"></i></div>
                    <span class="pr-sec-title">Edit Profile</span>
                </div>
                <form method="POST" class="pr-form-body">
                    <div class="pr-fg">
                        <div class="pr-lbl"><i class="fa-solid fa-phone"></i> Phone Number</div>
                        <input type="tel" name="phone" class="pr-inp"
                            value="<?= htmlspecialchars($userData['phone'] ?? '') ?>"
                            placeholder="+254700000000" readonly>
                        <div class="pr-hint"><i class="fa-solid fa-lock"></i> Contact support to change phone</div>
                    </div>
                    <div class="pr-fg">
                        <div class="pr-lbl"><i class="fa-solid fa-earth-africa"></i> Country</div>
                        <select name="country" class="pr-sel" disabled>
                            <option value="">Select country</option>
                            <?php while ($c=$ctryQ->fetch_assoc()): ?>
                            <option value="<?= htmlspecialchars($c['name']) ?>"
                                <?= ($userData['country'] ?? '')===$c['name']?'selected':'' ?>>
                                <?= htmlspecialchars($c['name']) ?>
                            </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <button type="submit" name="update_profile" class="pr-submit">
                        <i class="fa-solid fa-floppy-disk"></i> Save Changes
                    </button>
                </form>
            </div>

            <!-- Change password -->
            <div class="pr-sec">
                <div class="pr-sec-hdr">
                    <div class="pr-sec-ico" style="background:var(--DN)"><i class="fa-solid fa-lock"></i></div>
                    <span class="pr-sec-title">Change Password</span>
                </div>
                <form method="POST" class="pr-form-body" onsubmit="return prValidatePw()">
                    <div class="pr-fg">
                        <div class="pr-lbl"><i class="fa-solid fa-key"></i> Current Password</div>
                        <div class="pr-pw-wrap">
                            <input type="password" name="old_password" id="prOp" class="pr-inp" required placeholder="••••••••">
                            <button type="button" class="pr-pw-eye" onclick="prTogglePw('prOp',this)">
                                <i class="fa-solid fa-eye"></i>
                            </button>
                        </div>
                    </div>
                    <div class="pr-fg">
                        <div class="pr-lbl"><i class="fa-solid fa-lock-open"></i> New Password</div>
                        <div class="pr-pw-wrap">
                            <input type="password" name="new_password" id="prNp" class="pr-inp" minlength="6" required placeholder="••••••••">
                            <button type="button" class="pr-pw-eye" onclick="prTogglePw('prNp',this)">
                                <i class="fa-solid fa-eye"></i>
                            </button>
                        </div>
                        <div class="pr-hint">Minimum 6 characters</div>
                    </div>
                    <div class="pr-fg">
                        <div class="pr-lbl"><i class="fa-solid fa-shield-check"></i> Confirm Password</div>
                        <div class="pr-pw-wrap">
                            <input type="password" name="confirm_password" id="prCp" class="pr-inp" minlength="6" required placeholder="••••••••">
                            <button type="button" class="pr-pw-eye" onclick="prTogglePw('prCp',this)">
                                <i class="fa-solid fa-eye"></i>
                            </button>
                        </div>
                    </div>
                    <button type="submit" name="change_password" class="pr-submit amber">
                        <i class="fa-solid fa-key"></i> Update Password
                    </button>
                </form>
            </div>

        </div><!-- /right col -->
    </div><!-- /.pr-grid -->

</div><!-- /.pr -->

<!-- Toast — identical structure to dashboard .db-toast -->
<div id="prToast">
    <div id="prToastIco"></div>
    <span id="prToastMsg"></span>
    <button id="prToastX" onclick="prHideToast()">&#215;</button>
</div>

<script>
/* ── PHP → JS color injection (matches dashboard pattern) ── */
var ADMIN_P  = '<?= addslashes($adminPrimary) ?>';
var ADMIN_OK = '<?= addslashes($adminSuccess) ?>';
var ADMIN_WN = '<?= addslashes($adminWarning) ?>';
var ADMIN_DN = '<?= addslashes($adminDanger)  ?>';

var REFLINK = '<?= addslashes($refLink) ?>';
var REFCODE = '<?= addslashes($userData['referral_code'] ?? '') ?>';
var _ptt    = null;

/* ── Toast (identical to dashboard showToast) ── */
function prShowToast(msg, type) {
    type = type || 'success';
    var t   = document.getElementById('prToast');
    var ico = document.getElementById('prToastIco');
    var m   = document.getElementById('prToastMsg');
    var cols = { success:ADMIN_OK, error:ADMIN_DN, info:ADMIN_P, warning:ADMIN_WN };
    var icos = { success:'fa-circle-check', error:'fa-circle-xmark', info:'fa-circle-info', warning:'fa-triangle-exclamation' };
    var col  = cols[type] || ADMIN_P;
    t.style.borderLeftColor = col;
    ico.style.background    = col;
    ico.innerHTML = '<i class="fa-solid ' + icos[type] + '"></i>';
    m.textContent = msg;
    t.classList.add('show');
    clearTimeout(_ptt);
    _ptt = setTimeout(prHideToast, type === 'error' ? 5000 : 3000);
}
function prHideToast() {
    document.getElementById('prToast').classList.remove('show');
}

/* ── Copy helpers ── */
function copyRefCode() { prCopy(REFCODE, 'Referral code copied!'); }
function copyRefLink() { prCopy(REFLINK, 'Invite link copied!'); }

function prCopy(text, msg) {
    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(text).then(function(){ prShowToast(msg); }).catch(fb);
    } else { fb(); }
    function fb() {
        var a = document.createElement('input');
        a.value = text; a.style.cssText = 'position:fixed;left:-9999px';
        document.body.appendChild(a); a.select();
        try { document.execCommand('copy'); prShowToast(msg); }
        catch(e) { prShowToast('Copy failed','error'); }
        document.body.removeChild(a);
    }
}

/* ── Password toggle ── */
function prTogglePw(id, btn) {
    var inp  = document.getElementById(id);
    var show = inp.type === 'password';
    inp.type = show ? 'text' : 'password';
    btn.innerHTML = show
        ? '<i class="fa-solid fa-eye-slash"></i>'
        : '<i class="fa-solid fa-eye"></i>';
}

/* ── Password validation ── */
function prValidatePw() {
    var np = document.getElementById('prNp').value;
    var cp = document.getElementById('prCp').value;
    if (np !== cp)   { prShowToast('Passwords do not match!', 'error');          return false; }
    if (np.length<6) { prShowToast('Minimum 6 characters required!', 'error'); return false; }
    return true;
}
</script>

<?php include 'footer.php'; ?>