<?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 || in_array($userData['status'], ['deleted','suspended'])) {
    session_destroy(); redirect('../login.php');
}
if ($userData['status'] === 'inactive') {
    setFlash('warning','Please activate your account first.'); redirect('activate.php');
}

// Auto-create wallet_recharges table if missing
$conn->query("CREATE TABLE IF NOT EXISTS `wallet_recharges` (
  `id`                  INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  `user_id`             INT UNSIGNED NOT NULL,
  `amount`              DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `phone`               VARCHAR(20) NOT NULL DEFAULT '',
  `checkout_request_id` VARCHAR(100) NOT NULL DEFAULT '',
  `mpesa_receipt`       VARCHAR(50)  DEFAULT NULL,
  `status`              ENUM('pending','completed','failed') NOT NULL DEFAULT 'pending',
  `created_at`          DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `completed_at`        DATETIME DEFAULT NULL,
  INDEX `idx_user`      (`user_id`),
  INDEX `idx_ref`       (`checkout_request_id`),
  INDEX `idx_status`    (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

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

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

$wStmt = $conn->prepare("SELECT main_wallet FROM wallets WHERE user_id = ?");
$wStmt->bind_param("i", $userId); $wStmt->execute();
$walletRow   = $wStmt->get_result()->fetch_assoc();
$mainBalance = floatval($walletRow['main_wallet'] ?? 0);

$minDeposit = intval(getSetting('min_deposit', 50));
$maxDeposit = intval(getSetting('max_deposit', 50000));
$presets    = [50, 100, 200, 500, 1000, 2000];

// ── Clear session ──────────────────────────────────────────────────
if (isset($_GET['clear_session'])) {
    unset($_SESSION['recharge_ref'], $_SESSION['recharge_amount'], $_SESSION['recharge_phone']);
    header('Content-Type: application/json'); echo '{"ok":true}'; exit;
}

// ── Poll status ────────────────────────────────────────────────────
if (isset($_GET['poll_status'])) {
    header('Content-Type: application/json');
    $ref = $_GET['ref'] ?? '';
    if (!$ref) { echo json_encode(['status'=>'error']); exit; }
    $ps = $conn->prepare("SELECT status, amount FROM wallet_recharges WHERE user_id=? AND checkout_request_id=? LIMIT 1");
    $ps->bind_param("is", $userId, $ref); $ps->execute();
    $row = $ps->get_result()->fetch_assoc();
    echo json_encode($row ?: ['status'=>'not_found']);
    exit;
}

// ── POST: initiate STK push ────────────────────────────────────────
$error   = null;
$pending = false;
$txRef   = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount   = intval(preg_replace('/[^0-9]/', '', $_POST['amount'] ?? 0));
    $payerRaw = preg_replace('/[^0-9]/', '', trim($_POST['payer_phone'] ?? ''));

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

    if ($amount < $minDeposit) {
        $error = "Minimum deposit is {$currencySymbol} {$minDeposit}.";
    } elseif ($amount > $maxDeposit) {
        $error = "Maximum deposit is {$currencySymbol} ".number_format($maxDeposit).".";
    } elseif (strlen($payerPhone) < 12) {
        $error = 'Please enter a valid M-Pesa phone number.';
    } else {
        $tempRef = 'RCH_'.$userId.'_'.time();
        $ins = $conn->prepare("INSERT INTO wallet_recharges (user_id, amount, phone, checkout_request_id, status) VALUES (?, ?, ?, ?, 'pending')");
        $ins->bind_param("idss", $userId, $amount, $payerPhone, $tempRef);
        $ins->execute();

        require_once '../mpesa/stk_push.php';
        $result = initiate_stk($payerPhone, $amount, $tempRef);

        if ($result['success']) {
            $crid = $result['CheckoutRequestID'] ?? $tempRef;
            $upd = $conn->prepare("UPDATE wallet_recharges SET checkout_request_id=? WHERE checkout_request_id=? AND user_id=?");
            $upd->bind_param("ssi", $crid, $tempRef, $userId); $upd->execute();
            $txRef   = $crid;
            $pending = true;
            $_SESSION['recharge_ref']    = $txRef;
            $_SESSION['recharge_amount'] = $amount;
            $_SESSION['recharge_phone']  = $payerPhone;
        } else {
            $conn->query("UPDATE wallet_recharges SET status='failed' WHERE checkout_request_id='{$conn->real_escape_string($tempRef)}'");
            $error = $result['message'] ?? 'Failed to initiate M-Pesa payment. Try again.';
        }
    }
}

// ── Resume pending from session ────────────────────────────────────
if (!$pending && !empty($_SESSION['recharge_ref'])) {
    $chk = $conn->prepare("SELECT status FROM wallet_recharges WHERE user_id=? AND checkout_request_id=? LIMIT 1");
    $chk->bind_param("is", $userId, $_SESSION['recharge_ref']); $chk->execute();
    $chkRow = $chk->get_result()->fetch_assoc();
    if ($chkRow && $chkRow['status'] === 'pending') {
        $pending = true;
        $txRef   = $_SESSION['recharge_ref'];
    } else {
        unset($_SESSION['recharge_ref'], $_SESSION['recharge_amount'], $_SESSION['recharge_phone']);
    }
}

$pendingAmount = $_SESSION['recharge_amount'] ?? 0;
$pendingPhone  = $_SESSION['recharge_phone']  ?? '';
?>
<!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>Recharge Wallet — <?= htmlspecialchars($siteName) ?></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
<style>
/* ═══════════════════════════════════════════════════════════════
   EARNOVIX — Recharge Page
   Admin Color Injection · Light/Dark Mode · Matches side.php
   Standalone page (no sidebar) — same token system as login.php
═══════════════════════════════════════════════════════════════ */

: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 WRAPPER ── */
.rc {
    width: 100%; max-width: 420px;
    position: relative; z-index: 1;
    animation: cardIn .5s cubic-bezier(.22,1,.36,1) both;
}
@keyframes cardIn { from{opacity:0;transform:translateY(18px)} to{opacity:1;transform:translateY(0)} }

/* ── BALANCE BANNER — matches .hstat.prime from dashboard ── */
.rc-balance {
    border-radius: 16px 16px 0 0;
    padding: 20px 20px 18px;
    background: var(--card);
    border: 1px solid var(--bdr);
    border-bottom: none;
    position: relative; overflow: hidden;
    transition: background .25s, border-color .25s;
}
[data-theme="dark"] .rc-balance {
    background: linear-gradient(145deg, #0e0c1a 0%, #141228 100%);
    border-color: rgba(var(--Pr),.18);
}
/* Top glow line */
.rc-balance::before {
    content: ''; position: absolute; top: 0; left: 10%; right: 10%; height: 1px;
    background: linear-gradient(90deg, transparent, rgba(var(--Pr),.6), transparent);
}
/* Mesh glow */
.rc-balance::after {
    content: ''; position: absolute; inset: 0; pointer-events: none;
    background:
        radial-gradient(ellipse 60% 50% at 15% 20%, rgba(var(--Pr),.06) 0%, transparent 60%),
        radial-gradient(ellipse 40% 55% at 85% 75%, rgba(var(--Pr),.04) 0%, transparent 60%);
}

.rc-bal-top {
    display: flex; align-items: center; justify-content: space-between;
    margin-bottom: 14px; position: relative; z-index: 1;
}
/* Label — matches .hstat-lbl */
.rc-bal-label {
    font-size: 9px; font-weight: 700; letter-spacing: 2px;
    text-transform: uppercase; color: var(--P); opacity: .7;
}
/* Icon — matches .hstat-ico */
.rc-bal-icon {
    width: 28px; height: 28px; border-radius: 8px;
    background: var(--P-bg); border: 1px solid rgba(var(--Pr),.2);
    display: flex; align-items: center; justify-content: center;
    font-size: 12px; color: var(--P);
}

/* Big number — matches .hstat-val */
.rc-bal-amount {
    font-size: 36px; font-weight: 900; letter-spacing: -2px; line-height: 1;
    color: var(--txt); position: relative; z-index: 1; margin-bottom: 4px;
    font-variant-numeric: tabular-nums;
}
.rc-bal-currency { font-size: 16px; font-weight: 700; color: var(--txt2); }
.rc-bal-sub {
    font-size: 11px; color: var(--txt2);
    position: relative; z-index: 1;
}

/* ── FORM AREA — matches .chart-card ── */
.rc-form {
    background: var(--card); border: 1px solid var(--bdr);
    border-top: none; border-radius: 0 0 16px 16px;
    padding: 18px 18px 16px;
    box-shadow: var(--shadow);
    transition: background .25s, border-color .25s;
}
[data-theme="dark"] .rc-form { border-color: rgba(var(--Pr),.14); }

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

/* ── Presets — matches .aw-qbtn / .cur-btn from dashboard ── */
.rc-presets {
    display: grid; grid-template-columns: repeat(3,1fr); gap: 7px; margin-bottom: 14px;
}
.rc-preset {
    height: 38px; border-radius: 10px;
    border: 1px solid var(--bdr); background: var(--bg3);
    color: var(--txt2); font-size: 12px; font-weight: 700;
    cursor: pointer; font-family: inherit; transition: all .18s;
    display: flex; align-items: center; justify-content: center;
    -webkit-tap-highlight-color: transparent;
}
.rc-preset:hover { border-color: rgba(var(--Pr),.35); color: var(--P); background: var(--P-bg); }
.rc-preset.on { background: var(--P); color: #fff; border-color: transparent; box-shadow: 0 3px 14px rgba(var(--Pr),.35); }
[data-theme="light"] .rc-preset.on { color: #fff; }

/* ── Amount input ── */
.rc-amt-wrap { position: relative; margin-bottom: 6px; }
.rc-amt-prefix {
    position: absolute; left: 13px; top: 50%; transform: translateY(-50%);
    font-size: 13px; font-weight: 800; color: var(--txt3); pointer-events: none;
}
.rc-amt-input {
    width: 100%; height: 52px; padding: 0 14px 0 42px;
    background: var(--input-bg); border: 1px solid var(--input-bdr);
    border-radius: 12px; color: var(--txt);
    font-size: 20px; font-weight: 800; outline: none;
    transition: border-color .2s, box-shadow .2s, background .2s;
    letter-spacing: -.5px; -webkit-appearance: none; font-family: inherit;
}
.rc-amt-input:focus {
    border-color: var(--P);
    box-shadow: 0 0 0 3px rgba(var(--Pr),.14);
    background: var(--P-bg);
}
.rc-amt-input::placeholder { color: var(--txt3); font-size: 15px; font-weight: 400; letter-spacing: 0; }

.rc-amt-limits {
    font-size: 10.5px; color: var(--txt3); margin-top: 5px;
    display: flex; align-items: center; gap: 5px;
}
.rc-amt-limits i { font-size: 9px; }

/* ── Phone input ── */
.rc-phone-wrap { position: relative; margin-bottom: 12px; }
.rc-phone-ico {
    position: absolute; left: 13px; top: 50%; transform: translateY(-50%);
    font-size: 13px; color: var(--txt3); pointer-events: none;
}
.rc-phone-input {
    width: 100%; height: 44px; padding: 0 14px 0 38px;
    background: var(--input-bg); border: 1px solid var(--input-bdr);
    border-radius: 10px; color: var(--txt); font-size: 13.5px;
    outline: none; font-family: inherit;
    transition: border-color .2s, box-shadow .2s, background .2s;
}
.rc-phone-input:focus {
    border-color: var(--P);
    box-shadow: 0 0 0 3px rgba(var(--Pr),.14);
    background: var(--P-bg);
}
.rc-phone-input::placeholder { color: var(--txt3); }

/* ── M-Pesa hint — matches .mpesa-info from store.php ── */
.rc-net-hint {
    display: flex; align-items: center; gap: 10px;
    padding: 9px 12px; border-radius: 0 9px 9px 0;
    margin-bottom: 14px;
    background: var(--OK-bg); border: 1px solid rgba(34,197,94,.2);
    border-left: 3px solid var(--OK);
    font-size: 11px; color: var(--txt2); line-height: 1.5;
}
.rc-net-ico {
    width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;
    background: var(--OK); display: flex; align-items: center; justify-content: center;
    font-size: 12px; color: #fff; font-weight: 900;
}
.rc-net-txt strong { color: var(--txt); font-weight: 700; }

/* ── Alerts — matches dashboard .alert / .notif-bar ── */
.rc-alert {
    display: flex; align-items: flex-start; gap: 9px;
    border-radius: 0 9px 9px 0; padding: 10px 12px; margin-bottom: 12px;
    animation: fadeUp .3s ease both;
    border-left: 3px solid;
}
.rc-alert.err  { background: var(--DN-bg); border-color: var(--DN); }
.rc-alert.warn { background: var(--WN-bg); border-color: var(--WN); }
.rc-alert.ok   { background: var(--OK-bg); border-color: var(--OK); }
.rc-alert-ico { font-size: 13px; margin-top: 1px; flex-shrink: 0; }
.rc-alert.err  .rc-alert-ico { color: var(--DN); }
.rc-alert.warn .rc-alert-ico { color: var(--WN); }
.rc-alert.ok   .rc-alert-ico { color: var(--OK); }
.rc-alert-title { font-size: 12px; font-weight: 700; line-height: 1.4; }
.rc-alert.err  .rc-alert-title { color: var(--DN); }
.rc-alert.warn .rc-alert-title { color: var(--WN); }
.rc-alert.ok   .rc-alert-title { color: var(--OK); }
.rc-alert-sub { font-size: 11px; color: var(--txt2); line-height: 1.5; margin-top: 2px; }

/* ── Submit button — matches .copy-btn / .aw-submit ── */
.rc-btn {
    width: 100%; height: 48px; border-radius: 13px; border: none;
    cursor: pointer; background: var(--P); color: #fff;
    font-size: 14.5px; 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; -webkit-tap-highlight-color: transparent;
    position: relative; overflow: hidden;
}
.rc-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;
}
.rc-btn:hover { filter: brightness(1.1); transform: translateY(-2px); box-shadow: 0 8px 24px rgba(var(--Pr),.45); }
.rc-btn:hover::before { left: 100%; }
.rc-btn:active { transform: scale(.98); }
.rc-btn:disabled { opacity: .45; cursor: not-allowed; transform: none; box-shadow: none; }
[data-theme="light"] .rc-btn { color: #fff; }

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

/* ── Pending state ── */
.rc-pending {
    border-radius: 12px; padding: 22px 18px; text-align: center;
    background: var(--P-bg); border: 1px solid rgba(var(--Pr),.2);
    margin-bottom: 14px; animation: fadeUp .4s ease both;
}

/* Spinner ring — uses --P */
.rc-pending-ring {
    width: 64px; height: 64px; border-radius: 50%; margin: 0 auto 14px;
    border: 3px solid rgba(var(--Pr),.2); border-top-color: var(--P);
    animation: spinRing 1s linear infinite;
    display: flex; align-items: center; justify-content: center;
}
@keyframes spinRing { to { transform: rotate(360deg); } }
.rc-pending-inner {
    width: 44px; height: 44px; border-radius: 50%;
    background: var(--P-bg);
    display: flex; align-items: center; justify-content: center;
    font-size: 18px; color: var(--P);
}
.rc-pending-title { font-size: 15px; font-weight: 800; color: var(--txt); margin-bottom: 4px; }
.rc-pending-sub   { font-size: 12px; color: var(--txt2); line-height: 1.6; margin-bottom: 14px; }
.rc-pending-info  {
    display: flex; align-items: center; justify-content: center; gap: 10px;
    padding: 10px 14px; border-radius: 10px;
    background: var(--bg3); border: 1px solid var(--bdr);
    font-size: 12.5px; color: var(--txt2); margin-bottom: 14px;
}
.rc-pending-info strong { color: var(--txt); font-weight: 800; }

/* Steps — matches .rc-step from old file */
.rc-steps { display: flex; flex-direction: column; gap: 7px; margin-bottom: 14px; }
.rc-step {
    display: flex; align-items: center; gap: 10px;
    padding: 9px 12px; border-radius: 9px;
    background: var(--bg3); border: 1px solid var(--bdr);
    font-size: 11.5px; color: var(--txt2); transition: background .25s;
}
.rc-step-num {
    width: 22px; height: 22px; border-radius: 50%; flex-shrink: 0;
    background: var(--P-bg); color: var(--P);
    display: flex; align-items: center; justify-content: center;
    font-size: 10px; font-weight: 800;
}
.rc-step strong { color: var(--txt); }

/* Cancel button */
.rc-cancel {
    width: 100%; height: 40px; border-radius: 10px;
    border: 1px solid var(--bdr); background: transparent;
    color: var(--txt2); font-size: 12.5px; font-weight: 600;
    cursor: pointer; font-family: inherit; transition: all .2s;
}
.rc-cancel:hover { border-color: rgba(239,68,68,.4); color: var(--DN); }

/* ── Done state ── */
.rc-done { text-align: center; padding: 28px 18px; animation: cardIn .5s cubic-bezier(.22,1,.36,1) both; }
.rc-done-ico {
    width: 72px; height: 72px; border-radius: 50%; margin: 0 auto 16px;
    background: var(--OK); display: flex; align-items: center; justify-content: center;
    font-size: 30px; color: #fff;
    box-shadow: 0 0 30px rgba(34,197,94,.45), 0 0 60px rgba(34,197,94,.2);
    animation: doneScale .5s cubic-bezier(.34,1.56,.64,1) .1s both;
}
@keyframes doneScale { from{transform:scale(0)} to{transform:scale(1)} }
.rc-done-title  { font-size: 20px; font-weight: 900; color: var(--txt); margin-bottom: 5px; }
.rc-done-sub    { font-size: 12.5px; color: var(--txt2); margin-bottom: 20px; }
.rc-done-amount { font-size: 36px; font-weight: 900; letter-spacing: -2px; color: var(--OK); margin-bottom: 4px; font-variant-numeric: tabular-nums; }
.rc-done-label  { font-size: 12px; color: var(--txt2); margin-bottom: 24px; }

/* Done button */
.rc-done-btn {
    display: inline-flex; align-items: center; gap: 7px;
    padding: 12px 28px; background: var(--OK); color: #fff;
    border-radius: 12px; font-size: 13px; font-weight: 800;
    text-decoration: none; box-shadow: 0 6px 20px rgba(34,197,94,.35);
    transition: filter .15s, transform .15s;
}
.rc-done-btn:hover { filter: brightness(1.1); transform: translateY(-1px); }
[data-theme="light"] .rc-done-btn { color: #fff; }

/* Back link */
.rc-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;
}
.rc-back:hover { color: var(--txt2); }

/* Spinner */
.spin {
    display: inline-block; width: 16px; height: 16px;
    border: 2.5px solid rgba(255,255,255,.3); border-top-color: #fff;
    border-radius: 50%; animation: sp .65s linear infinite;
}
@keyframes sp { to { transform: rotate(360deg); } }

/* Animations */
@keyframes fadeUp { from{opacity:0;transform:translateY(8px)} to{opacity:1;transform:translateY(0)} }
.rc-balance { animation: fadeUp .4s ease both .03s; }
.rc-form    { animation: fadeUp .4s ease both .07s; }
</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="rc">

    <!-- ── BALANCE BANNER ── -->
    <div class="rc-balance">
        <div class="rc-bal-top">
            <span class="rc-bal-label"><i class="fa-solid fa-wallet" style="margin-right:5px"></i>Main Wallet</span>
            <div class="rc-bal-icon"><i class="fa-solid fa-coins"></i></div>
        </div>
        <div class="rc-bal-amount">
            <span class="rc-bal-currency"><?= $currencySymbol ?> </span><?= number_format($mainBalance, 2) ?>
        </div>
        <div class="rc-bal-sub">Current balance &nbsp;·&nbsp; <?= htmlspecialchars($userData['username']) ?></div>
    </div>

    <!-- ── FORM AREA ── -->
    <div class="rc-form">

        <?php if ($pending && $txRef): ?>
        <!-- ═══ PENDING STATE ═══ -->
        <div class="rc-pending">
            <div style="position:relative;display:flex;align-items:center;justify-content:center;margin-bottom:14px">
                <div class="rc-pending-ring"></div>
                <div class="rc-pending-inner" style="position:absolute">
                    <i class="fa-solid fa-mobile-screen" style="font-size:16px"></i>
                </div>
            </div>
            <div class="rc-pending-title">Check Your Phone</div>
            <div class="rc-pending-sub">
                M-Pesa prompt sent to<br>
                <strong style="color:var(--txt)"><?= htmlspecialchars(substr_replace($pendingPhone,'XXXXX',3,5)) ?></strong><br>
                Enter your M-Pesa PIN to complete the deposit.
            </div>
            <div class="rc-pending-info">
                <i class="fa-solid fa-coins" style="color:var(--WN)"></i>
                Depositing <strong><?= $currencySymbol ?> <?= number_format($pendingAmount) ?></strong> → Main Wallet
            </div>
        </div>

        <div class="rc-steps">
            <div class="rc-step">
                <div class="rc-step-num">1</div>
                <div>A popup appeared — <strong>enter your M-Pesa PIN</strong></div>
            </div>
            <div class="rc-step">
                <div class="rc-step-num">2</div>
                <div><strong>Wait 20–60 seconds</strong>. Do not close this page.</div>
            </div>
            <div class="rc-step">
                <div class="rc-step-num">3</div>
                <div>Your <strong>main wallet</strong> is credited automatically on success.</div>
            </div>
        </div>

        <div id="pollBox" style="display:none">
            <div class="rc-alert warn">
                <i class="fa-solid fa-clock rc-alert-ico"></i>
                <div>
                    <div class="rc-alert-title" id="pollTitle">Waiting for payment…</div>
                    <div class="rc-alert-sub" id="pollSub">Checking automatically every 5 seconds</div>
                </div>
            </div>
        </div>
        <div id="pollDone"></div>

        <button class="rc-cancel" onclick="cancelRecharge()">
            <i class="fa-solid fa-xmark" style="margin-right:6px"></i>Cancel / Try Again
        </button>

        <?php else: ?>
        <!-- ═══ ENTRY FORM ═══ -->

        <?php if ($error): ?>
        <div class="rc-alert err">
            <i class="fa-solid fa-circle-exclamation rc-alert-ico"></i>
            <div><div class="rc-alert-title"><?= htmlspecialchars($error) ?></div></div>
        </div>
        <?php endif; ?>

        <div class="rc-sec"><i class="fa-solid fa-coins" style="font-size:9px"></i>Deposit Amount</div>

        <div class="rc-presets">
            <?php foreach ($presets as $p): ?>
            <button type="button" class="rc-preset" onclick="setAmt(<?= $p ?>)">
                <?= $currencySymbol ?> <?= number_format($p) ?>
            </button>
            <?php endforeach; ?>
        </div>

        <form method="POST" id="rcForm">
            <div class="rc-amt-wrap">
                <span class="rc-amt-prefix"><?= $currencySymbol ?></span>
                <input type="number" name="amount" id="rcAmount" class="rc-amt-input"
                    placeholder="Enter amount"
                    min="<?= $minDeposit ?>" max="<?= $maxDeposit ?>"
                    oninput="onAmt(this.value)" required>
            </div>
            <div class="rc-amt-limits">
                <i class="fa-solid fa-circle-info"></i>
                Min <?= $currencySymbol ?> <?= number_format($minDeposit) ?> &nbsp;·&nbsp; Max <?= $currencySymbol ?> <?= number_format($maxDeposit) ?>
            </div>

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

            <div class="rc-sec"><i class="fa-solid fa-sim-card" style="font-size:9px"></i>M-Pesa Number</div>

            <div class="rc-phone-wrap">
                <i class="fa-solid fa-sim-card rc-phone-ico"></i>
                <input type="tel" name="payer_phone" id="rcPhone" class="rc-phone-input"
                    placeholder="07XX XXX XXX"
                    value="<?= htmlspecialchars($userData['phone'] ?? '') ?>" required>
            </div>

            <div class="rc-net-hint">
                <div class="rc-net-ico">M</div>
                <div class="rc-net-txt">
                    <strong>M-Pesa STK Push</strong> — you'll get a payment prompt on this number.
                    Enter your <strong>M-Pesa PIN</strong> to confirm.
                    Money goes directly to your <strong>Main Wallet</strong>.
                </div>
            </div>

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

            <button type="submit" class="rc-btn" id="rcBtn">
                <i class="fa-solid fa-bolt-lightning"></i>
                Deposit <span id="rcBtnAmt"><?= $currencySymbol ?> <?= $minDeposit ?></span> to Main Wallet
            </button>
        </form>
        <?php endif; ?>

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

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

/* ── PHP → JS ── */
var CS      = '<?= addslashes($currencySymbol) ?>';
var MIN     = <?= $minDeposit ?>;
var MAX     = <?= $maxDeposit ?>;
var PENDING = <?= $pending ? 'true' : 'false' ?>;
var TX_REF  = '<?= addslashes($txRef ?? '') ?>';
var ADMIN_P = '<?= addslashes($adminPrimary) ?>';
var ADMIN_OK= '<?= addslashes($adminSuccess) ?>';
var ADMIN_WN= '<?= addslashes($adminWarning) ?>';
var ADMIN_DN= '<?= addslashes($adminDanger)  ?>';

/* ── Presets ── */
function setAmt(v) {
    document.querySelectorAll('.rc-preset').forEach(function(b) {
        b.classList.toggle('on', b.textContent.replace(/[^0-9]/g,'') == v);
    });
    var inp = document.getElementById('rcAmount');
    if (inp) { inp.value = v; onAmt(v); }
}

function onAmt(v) {
    var n = parseInt(v) || 0;
    document.querySelectorAll('.rc-preset').forEach(function(b) {
        b.classList.toggle('on', b.textContent.replace(/[^0-9]/g,'') == n);
    });
    var el = document.getElementById('rcBtnAmt');
    if (el) el.textContent = CS + ' ' + (n > 0 ? n.toLocaleString() : MIN);
}

/* ── Form submit ── */
var rcForm = document.getElementById('rcForm');
if (rcForm) {
    rcForm.addEventListener('submit', function(e) {
        var v = parseInt(document.getElementById('rcAmount').value) || 0;
        if (v < MIN) { e.preventDefault(); showInlineErr('Minimum deposit is '+CS+' '+MIN); return; }
        if (v > MAX) { e.preventDefault(); showInlineErr('Maximum is '+CS+' '+MAX.toLocaleString()); return; }
        var p = document.getElementById('rcPhone').value.replace(/\D/g,'');
        if (p.length < 9) { e.preventDefault(); showInlineErr('Enter a valid M-Pesa phone number.'); return; }
        var btn = document.getElementById('rcBtn');
        btn.disabled = true;
        btn.innerHTML = '<span class="spin"></span> Sending STK Push…';
    });
}

function showInlineErr(msg) {
    var e = document.getElementById('inlineErr');
    if (e) e.remove();
    var d = document.createElement('div');
    d.id = 'inlineErr'; d.className = 'rc-alert err'; d.style.marginBottom = '10px';
    d.innerHTML = '<i class="fa-solid fa-circle-exclamation rc-alert-ico"></i><div><div class="rc-alert-title">'+msg+'</div></div>';
    rcForm.prepend(d);
    d.scrollIntoView({behavior:'smooth', block:'nearest'});
}

/* ── Polling ── */
if (PENDING && TX_REF) {
    var attempts    = 0;
    var maxAttempts = 60;
    var pollBox     = document.getElementById('pollBox');
    var pollTitle   = document.getElementById('pollTitle');
    var pollSub     = document.getElementById('pollSub');
    var pollDone    = document.getElementById('pollDone');
    var pollIv;

    function doPoll() {
        attempts++;
        if (pollSub) pollSub.textContent = 'Checking… (' + (maxAttempts - attempts) + 's remaining)';

        fetch('recharge.php?poll_status=1&ref=' + encodeURIComponent(TX_REF))
            .then(function(r) { return r.json(); })
            .then(function(d) {
                if (d.status === 'completed') {
                    clearInterval(pollIv);
                    fetch('recharge.php?clear_session=1');
                    if (pollBox) pollBox.style.display = 'none';

                    var ring  = document.querySelector('.rc-pending');
                    var steps = document.querySelector('.rc-steps');
                    var canc  = document.querySelector('.rc-cancel');
                    if (ring)  ring.style.display  = 'none';
                    if (steps) steps.style.display = 'none';
                    if (canc)  canc.style.display  = 'none';

                    if (pollDone) {
                        var amt = parseFloat(d.amount).toLocaleString('en',{minimumFractionDigits:2,maximumFractionDigits:2});
                        pollDone.innerHTML =
                            '<div class="rc-done">' +
                            '<div class="rc-done-ico"><i class="fa-solid fa-check"></i></div>' +
                            '<div class="rc-done-title">Deposit Successful! 🎉</div>' +
                            '<div class="rc-done-sub">Your main wallet has been credited</div>' +
                            '<div class="rc-done-amount">' + CS + ' ' + amt + '</div>' +
                            '<div class="rc-done-label">Added to Main Wallet</div>' +
                            '<a href="dashboard.php" class="rc-done-btn">' +
                            '<i class="fa-solid fa-house"></i>Go to Dashboard</a>' +
                            '</div>';
                    }

                } else if (d.status === 'failed') {
                    clearInterval(pollIv);
                    if (pollBox) {
                        var alertEl = pollBox.querySelector('.rc-alert');
                        if (alertEl) { alertEl.className = 'rc-alert err'; alertEl.style.borderColor = ADMIN_DN; }
                        if (pollTitle) pollTitle.textContent = 'Payment failed or cancelled.';
                        if (pollSub)   pollSub.textContent   = 'Click "Cancel / Try Again" to start over.';
                        pollBox.style.display = 'block';
                    }
                } else if (attempts >= maxAttempts) {
                    clearInterval(pollIv);
                    if (pollBox) {
                        if (pollTitle) pollTitle.textContent = 'Timed out — please check your history.';
                        if (pollSub)   pollSub.textContent   = 'If you paid, your wallet will be credited once confirmed.';
                        pollBox.style.display = 'block';
                    }
                } else {
                    if (pollBox) pollBox.style.display = 'block';
                }
            })
            .catch(function() {});
    }

    setTimeout(function() { doPoll(); pollIv = setInterval(doPoll, 5000); }, 5000);
}

function cancelRecharge() {
    fetch('recharge.php?clear_session=1').finally(function() {
        window.location.href = 'recharge.php';
    });
}
</script>
</body>
</html>