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

// ── Admin colors already set in side.php — $adminPrimary/$adminSuccess etc. available ──

define('HASHBACK_API_KEY',            '');
define('HASHBACK_SECURITY_CREDENTIAL','');
define('HASHBACK_ENABLED',            false);

function hashback_send($withdrawal_id, $amount, $phone) {
    $msisdn = preg_replace('/\D/', '', $phone);
    if (strlen($msisdn) === 12 && substr($msisdn, 0, 3) === '254') $msisdn = '0' . substr($msisdn, 3);
    if (!preg_match('/^0[17]\d{8}$/', $msisdn)) { error_log("HASHBACK: Invalid phone [{$phone}] for WD#{$withdrawal_id}"); return ['success'=>false,'message'=>'Invalid phone number format.','tx_ref'=>'','unknown'=>false]; }
    $send_amount = (int) round(floatval($amount));
    if ($send_amount <= 0) return ['success'=>false,'message'=>'Amount must be greater than zero.','tx_ref'=>'','unknown'=>false];
    $payload = json_encode(['api_key'=>HASHBACK_API_KEY,'msisdn'=>$msisdn,'amount'=>$send_amount,'SecurityCredential'=>HASHBACK_SECURITY_CREDENTIAL]);
    $curl = curl_init();
    curl_setopt_array($curl,[CURLOPT_URL=>'https://api.hashback.co.ke/V2/processwithdrawal',CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>45,CURLOPT_CONNECTTIMEOUT=>15,CURLOPT_FOLLOWLOCATION=>false,CURLOPT_CUSTOMREQUEST=>'POST',CURLOPT_POSTFIELDS=>$payload,CURLOPT_HTTPHEADER=>['Content-Type: application/json','Accept: application/json'],CURLOPT_SSL_VERIFYPEER=>true,CURLOPT_SSL_VERIFYHOST=>2]);
    $response=curl_exec($curl); $http_code=curl_getinfo($curl,CURLINFO_HTTP_CODE); $curl_errno=curl_errno($curl); $curl_error=curl_error($curl); curl_close($curl);
    error_log("HASHBACK [WD#{$withdrawal_id}] HTTP {$http_code} errno={$curl_errno}: ".substr($response,0,300));
    if ($curl_errno>0) return ['success'=>false,'message'=>'Network error — payment status unknown. Do NOT retry without checking.','tx_ref'=>'','unknown'=>true];
    $data=json_decode($response,true);
    if ($http_code===200&&!empty($data['success'])) { $tx_ref=$data['details']['transaction_reference']??''; return ['success'=>true,'message'=>$data['message']??'Sent.','tx_ref'=>$tx_ref,'unknown'=>false]; }
    $err='Payment gateway error.'; if(!empty($data['message'])) $err=htmlspecialchars(strip_tags($data['message']),ENT_QUOTES,'UTF-8');
    error_log("HASHBACK REJECTED [WD#{$withdrawal_id}]: {$err}"); return ['success'=>false,'message'=>$err,'tx_ref'=>'','unknown'=>false];
}

$userCountry = $userData['country'] ?? 'Kenya';
$stmt = $conn->prepare("SELECT * FROM countries WHERE name=? AND status='active'");
$stmt->bind_param("s",$userCountry); $stmt->execute();
$cs = $stmt->get_result()->fetch_assoc();
if (!$cs) { $stmt=$conn->prepare("SELECT * FROM countries WHERE name='Kenya'"); $stmt->execute(); $cs=$stmt->get_result()->fetch_assoc(); }
if (!$cs) $cs = ['currency_symbol'=>'KSh','exchange_rate'=>1,'min_withdrawal'=>100,'withdrawal_fee'=>10,'id'=>0];
$cSym    = $cs['currency_symbol'] ?? 'KSh';
$minW    = floatval($cs['min_withdrawal']  ?? 100);
$flatFee = floatval($cs['withdrawal_fee']  ?? 10);

$tieredFees = [];
if (($cs['id']??0) > 0) {
    $stmt=$conn->prepare("SELECT * FROM withdrawal_fee_tiers WHERE country_id=? ORDER BY min_amount ASC");
    $stmt->bind_param("i",$cs['id']); $stmt->execute();
    $r=$stmt->get_result(); while($t=$r->fetch_assoc()) $tieredFees[]=$t;
}

$wq = $conn->query("SELECT wallet_type FROM wallet_withdrawal_settings WHERE status='enabled'");
$enabledTypes = [];
if ($wq && $wq->num_rows > 0) { while ($r=$wq->fetch_assoc()) $enabledTypes[]=$r['wallet_type']; }
else $enabledTypes = ['main_wallet','referral_wallet','bonus_wallet','video_wallet','trivia_wallet','survey_wallet','ads_wallet','spin_wallet','blog_wallet','meme_wallet','chat_wallet','transcription_wallet'];

$walletTypeToShort = ['referral_wallet'=>'referral','bonus_wallet'=>'bonus','video_wallet'=>'video','trivia_wallet'=>'trivia','survey_wallet'=>'survey','ads_wallet'=>'ads','spin_wallet'=>'spin','blog_wallet'=>'blog','meme_wallet'=>'meme','chat_wallet'=>'chat','transcription_wallet'=>'transcription','main_wallet'=>'main'];

// Use design-system tokens where possible, specific hex for unique per-wallet accents
$walletMeta = [
    'main_wallet'          => ['name'=>'Main',      'icon'=>'fa-vault',                  'color'=>'var(--P)'],
    'referral_wallet'      => ['name'=>'Affiliate', 'icon'=>'fa-sitemap',               'color'=>'#8b5cf6'],
    'bonus_wallet'         => ['name'=>'Bonus',     'icon'=>'fa-coins',                 'color'=>'var(--OK)'],
    'video_wallet'         => ['name'=>'Video',     'icon'=>'fa-film',                  'color'=>'#ef4444'],
    'trivia_wallet'        => ['name'=>'Trivia',    'icon'=>'fa-bolt',                  'color'=>'#a855f7'],
    'survey_wallet'        => ['name'=>'Survey',    'icon'=>'fa-magnifying-glass-chart','color'=>'#06b6d4'],
    'ads_wallet'           => ['name'=>'Ads',       'icon'=>'fa-tower-broadcast',       'color'=>'#8b5cf6'],
    'spin_wallet'          => ['name'=>'Spin',      'icon'=>'fa-dharmachakra',          'color'=>'#14b8a6'],
    'blog_wallet'          => ['name'=>'Blog',      'icon'=>'fa-rss',                   'color'=>'var(--OK)'],
    'meme_wallet'          => ['name'=>'Meme',      'icon'=>'fa-masks-theater',         'color'=>'#ec4899'],
    'chat_wallet'          => ['name'=>'Chat',      'icon'=>'fa-comments',              'color'=>'#3b82f6'],
    'transcription_wallet' => ['name'=>'Transcribe','icon'=>'fa-wave-square',           'color'=>'#f97316'],
];

ensureWalletExists($conn,$userId);
$stmt = $conn->prepare("SELECT * FROM wallets WHERE user_id=? LIMIT 1");
$stmt->bind_param("i",$userId); $stmt->execute();
$uw = $stmt->get_result()->fetch_assoc();

$availWallets=[]; $refIdx=-1; $defaultIdx=0;
if ($uw) {
    $idx=0;
    foreach ($enabledTypes as $wt) {
        if (isset($walletMeta[$wt])) {
            $bal = floatval($uw[$wt]??0);
            $availWallets[] = ['type'=>$wt,'short'=>$walletTypeToShort[$wt]??$wt,'name'=>$walletMeta[$wt]['name'],'icon'=>$walletMeta[$wt]['icon'],'color'=>$walletMeta[$wt]['color'],'balance'=>$bal,'can_withdraw'=>$bal>=$minW];
            if ($wt==='referral_wallet') $refIdx=$idx;
            $idx++;
        }
    }
}

$hasWithdrawable=false;
foreach ($availWallets as $i=>$w) { if($w['can_withdraw']){$hasWithdrawable=true;if(!isset($fw)){$defaultIdx=$i;$fw=true;}}}
if ($refIdx>=0 && ($availWallets[$refIdx]['can_withdraw']??false)) $defaultIdx=$refIdx;

if ($_SERVER['REQUEST_METHOD']==='POST') {
    $wCol=sanitize($_POST['wallet_type']??''); $amount=floatval($_POST['amount']??0); $phone=sanitize($_POST['phone_number']??'');
    if (!in_array($wCol,$enabledTypes)){$_SESSION['notif']=['type'=>'error','message'=>'Wallet disabled.'];header('Location: '.$_SERVER['PHP_SELF']);exit;}
    $wShort=$walletTypeToShort[$wCol]??null; $wColumn=$wShort?getWalletColumn($wShort):null;
    if (!$wShort||!$wColumn){$_SESSION['notif']=['type'=>'error','message'=>'Invalid wallet type.'];header('Location: '.$_SERVER['PHP_SELF']);exit;}
    if ($amount<$minW){$_SESSION['notif']=['type'=>'error','message'=>'Min withdrawal: '.$cSym.' '.number_format($minW,2)];header('Location: '.$_SERVER['PHP_SELF']);exit;}
    $curBal=floatval($uw[$wCol]??0);
    if ($curBal<$amount){$_SESSION['notif']=['type'=>'error','message'=>'Insufficient balance.'];header('Location: '.$_SERVER['PHP_SELF']);exit;}
    $fee=$flatFee; foreach($tieredFees as $tier){if($amount>=$tier['min_amount']&&$amount<=$tier['max_amount']){$fee=$tier['fee'];break;}}
    $net=$amount-$fee;
    if ($net<=0){$_SESSION['notif']=['type'=>'error','message'=>'Amount too low after fees.'];header('Location: '.$_SERVER['PHP_SELF']);exit;}
    $dupCheck=$conn->prepare("SELECT id FROM withdrawals WHERE user_id=? AND wallet_type=? AND amount=? AND requested_at>DATE_SUB(NOW(),INTERVAL 60 SECOND) LIMIT 1");$dupCheck->bind_param("isd",$userId,$wShort,$amount);$dupCheck->execute();
    if ($dupCheck->get_result()->num_rows>0){$_SESSION['notif']=['type'=>'error','message'=>'Duplicate request — please wait.'];header('Location: '.$_SERVER['PHP_SELF']);exit;}
    $wname=$walletMeta[$wCol]['name']??$wCol;
    $conn->begin_transaction(); $wid=null;
    try{
        $debitDesc="Withdrawal from {$wname}: {$cSym} ".number_format($net,2)." (Fee: {$cSym} ".number_format($fee,2).")"; $tmpRef="WD-PENDING-{$userId}-".time();
        $debitOk=debitWallet($userId,$wShort,$amount,$debitDesc,$tmpRef); if(!$debitOk) throw new Exception('Wallet debit failed.');
        $stmt=$conn->prepare("INSERT INTO withdrawals (user_id,wallet_type,amount,fee,net_amount,phone_number,status,country,requested_at) VALUES (?,?,?,?,?,?,'pending',?,NOW())");$stmt->bind_param("isdddss",$userId,$wShort,$amount,$fee,$net,$phone,$userCountry);if(!$stmt->execute())throw new Exception('Withdrawal insert failed: '.$conn->error);
        $wid=$conn->insert_id; $conn->query("UPDATE transactions SET reference='WD-{$wid}' WHERE reference='{$tmpRef}' AND user_id={$userId} ORDER BY id DESC LIMIT 1"); $conn->commit();
    } catch(Exception $e) { $conn->rollback(); error_log("Withdrawal DB error: ".$e->getMessage()); $_SESSION['notif']=['type'=>'error','message'=>'Failed to process. Please try again.']; header('Location: '.$_SERVER['PHP_SELF']); exit; }
    $auto_sent=false;
    if (HASHBACK_ENABLED) {
        $api_result=hashback_send($wid,$net,$phone);
        if ($api_result['success']){$tx_ref=$conn->real_escape_string($api_result['tx_ref']);$conn->query("UPDATE withdrawals SET status='completed',hashback_reference='{$tx_ref}',hashback_status='SENT',processed_at=NOW() WHERE id={$wid}");$auto_sent=true;}
        elseif(!empty($api_result['unknown'])){$conn->query("UPDATE withdrawals SET status='completed',hashback_status='NETWORK_ERROR',processed_at=NOW() WHERE id={$wid}");$auto_sent=true;}
        else{$err=$conn->real_escape_string($api_result['message']);$conn->query("UPDATE withdrawals SET hashback_status='API_ERROR',hashback_result_desc='{$err}' WHERE id={$wid}");}
    }
    @require_once '../includes/email.php';
    if (function_exists('sendWithdrawalRequestedEmail')) sendWithdrawalRequestedEmail($userData['email'],$userData['username'],$wid,$amount,$fee,$net,$phone,$wname,$cSym);
    if (!$auto_sent && function_exists('sendWithdrawalNotificationAdmin')) sendWithdrawalNotificationAdmin($wid);
    if ($auto_sent) $_SESSION['notif']=['type'=>'success','message'=>'Sent!','amount'=>$amount,'net'=>$net,'currency'=>$cSym,'auto'=>true];
    else            $_SESSION['notif']=['type'=>'success','message'=>'Submitted!','amount'=>$amount,'net'=>$net,'currency'=>$cSym,'auto'=>false];
    header('Location: '.$_SERVER['PHP_SELF']); exit;
}
$notif = $_SESSION['notif'] ?? null; unset($_SESSION['notif']);
?>
<style>
/* ═══════════════════════════════════════════════════════════════
   EARNOVIX — Withdraw (ATM Interface)
   Uses CSS vars from side.php — no :root redeclaration
═══════════════════════════════════════════════════════════════ */

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

/* ── ATM SCREEN — matches .hstat.prime from dashboard ── */
.aw-screen {
    background:var(--bg3); border:1px solid var(--bdr);
    border-radius:16px; padding:20px 20px 16px;
    margin-bottom:12px; position:relative; overflow:hidden;
    cursor:pointer; transition:background .25s, border-color .25s;
}
[data-theme="dark"] .aw-screen { border-color:rgba(var(--Pr),.18); }
/* Subtle grid pattern — terminal feel */
.aw-screen::before {
    content:''; position:absolute; inset:0; pointer-events:none;
    background-image:
        repeating-linear-gradient(0deg, transparent, transparent 28px,
        rgba(var(--Pr),.04) 28px, rgba(var(--Pr),.04) 29px);
}
.aw-screen-top {
    display:flex; align-items:center; justify-content:space-between;
    margin-bottom:12px;
}

/* Active wallet chip — matches .ppill from header */
.aw-wallet-chip {
    display:flex; align-items:center; gap:7px;
    padding:5px 10px 5px 6px; border-radius:20px;
    border:1px solid var(--bdr); background:var(--card);
    font-size:11px; font-weight:700; color:var(--txt);
    transition:all .2s; cursor:pointer; position:relative; z-index:1;
}
.aw-wallet-chip:hover { border-color:rgba(var(--Pr),.3); }
.aw-wallet-chip-ico {
    width:22px; height:22px; border-radius:7px;
    display:flex; align-items:center; justify-content:center;
    font-size:10px; color:#fff; flex-shrink:0;
}
.aw-wallet-chip-arr { font-size:9px; color:var(--txt3); margin-left:2px; }

/* Screen label — matches .hstat-lbl */
.aw-screen-lbl {
    font-size:9px; font-weight:700; letter-spacing:1.5px;
    text-transform:uppercase; color:var(--txt2);
    position:relative; z-index:1;
    display:flex; align-items:center; gap:5px;
}

/* Big number display — matches .hstat-val */
.aw-amount-display {
    position:relative; z-index:1;
    min-height:64px; display:flex; align-items:flex-end;
    gap:8px; margin-bottom:6px;
}
.aw-currency {
    font-size:18px; font-weight:700; color:var(--txt2); padding-bottom:6px; flex-shrink:0;
}
.aw-amount-num {
    font-size:48px; font-weight:900; color:var(--txt);
    letter-spacing:-2px; line-height:1;
    font-variant-numeric:tabular-nums; transition:color .15s;
}
.aw-amount-num.has-val { color:var(--P); }

/* Balance line */
.aw-balance-line {
    display:flex; align-items:center; justify-content:space-between;
    font-size:10.5px; color:var(--txt2);
    position:relative; z-index:1;
    padding-top:8px; border-top:1px solid var(--bdr);
}
.aw-balance-line b { color:var(--txt); font-weight:700; }
.aw-max-link {
    font-size:10px; font-weight:800; color:var(--P);
    background:none; border:none; cursor:pointer; font-family:inherit; padding:0;
    display:flex; align-items:center; gap:3px;
}
.aw-max-link:hover { text-decoration:underline; }

/* ── QUICK AMOUNT BUTTONS — matches .cur-btn from dashboard ── */
.aw-quick {
    display:grid; grid-template-columns:repeat(4,1fr); gap:6px; margin-bottom:12px;
}
.aw-qbtn {
    height:36px; border-radius:9px;
    background:var(--card); border:1px solid var(--bdr);
    color:var(--txt2); font-size:11px; font-weight:700;
    cursor:pointer; font-family:inherit; transition:all .15s;
    display:flex; align-items:center; justify-content:center;
}
.aw-qbtn:hover  { border-color:rgba(var(--Pr),.35); color:var(--P); background:var(--P-bg); }
.aw-qbtn.active { background:var(--P); color:#fff; border-color:transparent; }
[data-theme="light"] .aw-qbtn.active { color:#fff; }

/* ── SECTION LABEL — matches dashboard .sec-lbl ── */
.aw-wallets-lbl {
    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;
}
.aw-wallets-lbl::after {
    content:''; flex:1; height:1px;
    background:linear-gradient(90deg,rgba(var(--Pr),.3),transparent);
}

/* ── WALLET CHIPS — horizontal scroll ── */
.aw-wallets {
    display:flex; gap:7px; overflow-x:auto; padding-bottom:4px;
    margin-bottom:12px; scrollbar-width:none; -webkit-overflow-scrolling:touch;
}
.aw-wallets::-webkit-scrollbar { display:none; }

/* Each chip — matches .wcard structure */
.aw-wchip {
    display:flex; align-items:center; gap:7px;
    padding:8px 12px 8px 9px; border-radius:11px;
    border:1px solid var(--bdr); background:var(--card);
    cursor:pointer; flex-shrink:0; transition:all .15s;
    position:relative;
}
.aw-wchip::before {
    content:''; position:absolute; top:0; left:0; right:0;
    height:2.5px; border-radius:11px 11px 0 0;
    background:var(--wc, var(--P)); opacity:0; transition:opacity .15s;
}
.aw-wchip.sel::before { opacity:1; }
.aw-wchip:hover:not(.disabled) { border-color:rgba(var(--Pr),.28); transform:translateY(-1px); }
.aw-wchip.sel { border-color:var(--wc, rgba(var(--Pr),.35)); }
.aw-wchip.disabled { opacity:.4; cursor:not-allowed; }
.aw-wchip input[type=radio] { display:none; }
.aw-wchip-ico {
    width:28px; height:28px; border-radius:8px;
    display:flex; align-items:center; justify-content:center;
    font-size:12px; color:#fff; flex-shrink:0;
}
.aw-wchip-name { font-size:11px; font-weight:700; color:var(--txt); white-space:nowrap; }
.aw-wchip-bal  { font-size:10px; color:var(--txt2); font-variant-numeric:tabular-nums; white-space:nowrap; }
.aw-wchip-dot {
    position:absolute; top:5px; right:5px;
    width:7px; height:7px; border-radius:50%;
    background:var(--wc, var(--P)); display:none;
}
.aw-wchip.sel .aw-wchip-dot { display:block; }

/* ── CONFIRM DRAWER — matches .chart-card / .hstat structure ── */
.aw-confirm {
    background:var(--card); border:1px solid var(--bdr);
    border-radius:14px; overflow:hidden; margin-bottom:12px;
    transition:background .25s, border-color .25s; display:none;
}
[data-theme="dark"] .aw-confirm { border-color:rgba(var(--Pr),.14); }
.aw-confirm.show { display:block; animation:fadeUp .25s ease both; }
.aw-confirm-hdr {
    display:flex; align-items:center; justify-content:space-between;
    padding:11px 16px; background:var(--bg3); border-bottom:1px solid var(--bdr);
    transition:background .25s;
}
.aw-confirm-title { font-size:12px; font-weight:700; color:var(--txt); display:flex; align-items:center; gap:6px; }
.aw-confirm-title i { color:var(--P); }
.aw-confirm-body { padding:14px 16px; }

/* Receipt rows */
.aw-rcpt { display:flex; flex-direction:column; gap:0; margin-bottom:14px; }
.aw-rcpt-row {
    display:flex; justify-content:space-between; align-items:center;
    padding:8px 0; border-bottom:1px dashed var(--bdr); font-size:12px;
}
.aw-rcpt-row:last-child { border-bottom:2px solid var(--bdr); padding-bottom:10px; }
.aw-rcpt-row.total { border-bottom:none; padding-top:10px; }
.aw-rcpt-k { color:var(--txt2); font-weight:500; }
.aw-rcpt-v { font-weight:700; color:var(--txt); font-variant-numeric:tabular-nums; }
.aw-rcpt-v.big { font-size:17px; font-weight:900; color:var(--P); letter-spacing:-.3px; }

/* Phone row inside confirm — matches .aw-phone section */
.aw-phone-row {
    display:flex; align-items:center; gap:9px;
    padding:10px 12px; border-radius:10px;
    background:var(--bg3); border:1px solid var(--bdr);
    margin-bottom:14px; transition:background .25s;
}
.aw-phone-ico {
    width:32px; height:32px; border-radius:9px;
    background:var(--P-bg); border:1px solid rgba(var(--Pr),.2);
    display:flex; align-items:center; justify-content:center;
    font-size:13px; color:var(--P); flex-shrink:0;
}
.aw-phone-lbl { font-size:9px; color:var(--txt2); font-weight:600; text-transform:uppercase; letter-spacing:.5px; }
.aw-phone-num { font-size:13px; font-weight:700; color:var(--txt); }
.aw-phone-edit {
    margin-left:auto; font-size:10px; color:var(--P);
    text-decoration:none; font-weight:700;
    display:flex; align-items:center; gap:3px; flex-shrink:0; opacity:.8;
}
.aw-phone-edit:hover { opacity:1; }

/* ── SUBMIT BUTTON — matches .copy-btn / .btn-submit ── */
.aw-submit {
    width:100%; height:50px; border:none; border-radius:13px;
    font-size:15px; font-weight:800; cursor:pointer;
    display:flex; align-items:center; justify-content:center; gap:9px;
    font-family:inherit; background:var(--P); color:#fff;
    transition:all .18s; letter-spacing:.2px;
    box-shadow:0 4px 18px rgba(var(--Pr),.35);
}
.aw-submit:hover:not(:disabled) { filter:brightness(1.12); transform:translateY(-2px); box-shadow:0 6px 22px rgba(var(--Pr),.45); }
.aw-submit:active:not(:disabled) { transform:scale(.99); }
.aw-submit:disabled {
    background:var(--bg3); color:var(--txt3);
    border:1px solid var(--bdr); cursor:not-allowed;
    box-shadow:none; transform:none;
}
[data-theme="light"] .aw-submit:not(:disabled) { color:#fff; }

/* ── NOTICE — matches .act-bar from dashboard ── */
.aw-notice {
    display:flex; align-items:center; gap:9px;
    padding:10px 13px; border-radius:10px; margin-bottom:12px;
    background:var(--WN-bg); border:1px solid rgba(245,158,11,.2);
    border-left:3px solid var(--WN);
    border-radius:0 10px 10px 0;
    font-size:11px; font-weight:600; color:var(--WN);
}

/* Hidden form */
#awForm { display:none; }

/* ── TOAST — identical to dashboard .db-toast ── */
.aw-toast {
    position:fixed; top:-90px; left:50%; transform:translateX(-50%);
    min-width:270px; max-width:calc(100vw - 28px);
    border-radius:10px; padding:10px 42px 10px 12px;
    z-index:9999; display:flex; align-items:center; gap:10px;
    transition:top .4s cubic-bezier(.34,1.56,.64,1);
    box-shadow:0 8px 32px rgba(0,0,0,.3);
    background:var(--card2); border:1px solid rgba(var(--Pr),.3);
    border-left:4px solid var(--P);
}
.aw-toast.show { top:calc(var(--hh) + 10px); }
.aw-toast-ico {
    width:28px; height:28px; border-radius:8px;
    display:flex; align-items:center; justify-content:center;
    font-size:12px; color:#fff; flex-shrink:0;
}
.aw-toast-title { font-size:12px; font-weight:700; color:var(--txt); margin-bottom:1px; }
.aw-toast-msg   { font-size:11px; color:var(--txt2); line-height:1.4; }
.aw-toast-cls {
    position:absolute; right:10px; top:50%; transform:translateY(-50%);
    background:none; border:none; font-size:18px; color:var(--txt3); cursor:pointer;
}

/* ── SUCCESS MODAL — matches .congrats from dashboard ── */
.aw-modal-bg {
    position:fixed; inset:0; z-index:5000;
    background:rgba(0,0,0,.6);
    display:none; align-items:center; justify-content:center; padding:20px;
}
.aw-modal {
    width:100%; max-width:360px;
    background:var(--card); border:1px solid var(--bdr);
    border-radius:20px; overflow:hidden;
    box-shadow:0 40px 100px rgba(0,0,0,.5);
    animation:awPop .4s cubic-bezier(.34,1.56,.64,1);
    transition:background .25s, border-color .25s;
}
[data-theme="dark"] .aw-modal { border-color:rgba(var(--Pr),.18); }
.aw-modal-head {
    padding:28px 24px 22px; text-align:center;
    position:relative; overflow:hidden;
}
/* Decorative circles in head */
.aw-modal-head::before {
    content:''; position:absolute; top:-30px; right:-30px;
    width:100px; height:100px; border-radius:50%;
    background:rgba(255,255,255,.1); pointer-events:none;
}
.aw-modal-head::after {
    content:''; position:absolute; bottom:-40px; left:-20px;
    width:80px; height:80px; border-radius:50%;
    background:rgba(255,255,255,.07); pointer-events:none;
}
.aw-modal-emoji {
    font-size:50px; margin-bottom:12px; display:block;
    position:relative; z-index:1;
    animation:smBounce .6s .2s cubic-bezier(.34,1.56,.64,1) both;
}
.aw-modal-h { font-size:22px; font-weight:900; color:#fff; letter-spacing:-.5px; position:relative; z-index:1; }
.aw-modal-s { font-size:12px; color:rgba(255,255,255,.8); margin-top:5px; position:relative; z-index:1; }
.aw-modal-body { padding:16px 20px 0; }
.aw-modal-amt {
    background:var(--bg3); border:1px solid var(--bdr);
    border-radius:12px; padding:14px; text-align:center; margin-bottom:12px;
    transition:background .25s;
}
.aw-modal-amt-lbl { font-size:9px; font-weight:800; letter-spacing:2px; text-transform:uppercase; color:var(--txt2); margin-bottom:5px; }
.aw-modal-amt-num { font-size:32px; font-weight:900; color:var(--P); letter-spacing:-1.5px; font-variant-numeric:tabular-nums; }
.aw-modal-info { font-size:12px; color:var(--txt2); line-height:1.7; text-align:center; padding:0 4px; margin-bottom:16px; }
.aw-modal-actions { display:flex; gap:8px; padding:0 20px 20px; }

/* Modal buttons — matches .cg-btn / .act-btn */
.aw-modal-btn {
    flex:1; height:44px; border-radius:11px; border:none;
    font-size:13px; font-weight:700; cursor:pointer; font-family:inherit;
    display:flex; align-items:center; justify-content:center; gap:6px;
    text-decoration:none; transition:.15s;
}
.aw-modal-btn.primary { background:var(--P); color:#fff; }
.aw-modal-btn.primary:hover { filter:brightness(1.1); }
[data-theme="light"] .aw-modal-btn.primary { color:#fff; }
.aw-modal-btn.ghost { background:var(--bg3); color:var(--txt); border:1px solid var(--bdr); }
.aw-modal-btn.ghost:hover { border-color:rgba(var(--Pr),.3); color:var(--P); }

/* ── Animations ── */
@keyframes fadeUp  { from{opacity:0;transform:translateY(10px)} to{opacity:1;transform:translateY(0)} }
@keyframes awPop   { from{opacity:0;transform:scale(.85) translateY(12px)} to{opacity:1;transform:none} }
@keyframes smBounce{ from{transform:scale(.3) rotate(-10deg)} 60%{transform:scale(1.2) rotate(5deg)} to{transform:scale(1) rotate(0)} }

.aw-screen    { animation:fadeUp .3s ease both; }
.aw-quick     { animation:fadeUp .3s ease .04s both; }
.aw-wallets-lbl,
.aw-wallets   { animation:fadeUp .3s ease .08s both; }
</style>

<div class="aw">

<?php if (!$hasWithdrawable && !empty($availWallets)): ?>
<div class="aw-notice">
    <i class="fa-solid fa-circle-info" style="flex-shrink:0"></i>
    Minimum withdrawal is <?= $cSym.' '.number_format($minW,2) ?>. Keep earning to unlock.
</div>
<?php endif; ?>

<?php if (empty($availWallets)): ?>
<div style="text-align:center;padding:40px 20px;background:var(--card);border:1px solid var(--bdr);border-radius:14px">
    <i class="fa-solid fa-wallet" style="font-size:36px;color:var(--txt3);display:block;margin-bottom:10px"></i>
    <div style="font-size:14px;font-weight:700;color:var(--txt)">No wallets available</div>
    <div style="font-size:12px;color:var(--txt2);margin-top:4px">Complete tasks to start earning.</div>
</div>
<?php else: ?>

<!-- ── ATM SCREEN ── -->
<div class="aw-screen" id="awScreen">
    <div class="aw-screen-top">
        <div class="aw-wallet-chip" id="activeChip" onclick="scrollToWallets()">
            <div class="aw-wallet-chip-ico" id="activeChipIco"
                 style="background:<?= $availWallets[$defaultIdx]['color']??'var(--P)' ?>">
                <i class="fa-solid <?= $availWallets[$defaultIdx]['icon']??'fa-wallet' ?>" id="activeChipIcon"></i>
            </div>
            <span id="activeChipName"><?= $availWallets[$defaultIdx]['name']??'Wallet' ?></span>
            <i class="fa-solid fa-chevron-down aw-wallet-chip-arr"></i>
        </div>
        <span class="aw-screen-lbl">
            <?php if (HASHBACK_ENABLED): ?>
            <i class="fa-solid fa-bolt" style="color:var(--OK)"></i>Instant
            <?php else: ?>
            <i class="fa-solid fa-paper-plane"></i>Withdraw
            <?php endif; ?>
        </span>
    </div>

    <div class="aw-amount-display">
        <span class="aw-currency"><?= $cSym ?></span>
        <span class="aw-amount-num" id="displayAmt">0.00</span>
    </div>

    <div class="aw-balance-line">
        <span>Balance: <b id="balDisplay"><?= $cSym.' '.number_format($availWallets[$defaultIdx]['balance']??0,2) ?></b></span>
        <button class="aw-max-link" onclick="setMax()">
            <i class="fa-solid fa-arrow-up-right-from-square" style="font-size:9px"></i> MAX
        </button>
    </div>
</div>

<!-- ── QUICK AMOUNTS ── -->
<?php
$qAmounts = [100,200,500,1000];
if ($minW > 100) $qAmounts = [intval($minW), intval($minW*2), intval($minW*5), intval($minW*10)];
?>
<div class="aw-quick">
    <?php foreach ($qAmounts as $qa): ?>
    <button class="aw-qbtn" onclick="quickAmt(<?= $qa ?>)">
        <?= $cSym.' '.number_format($qa,0) ?>
    </button>
    <?php endforeach; ?>
</div>

<!-- Hidden input for keyboard entry -->
<input type="number" id="hiddenAmt"
       style="position:absolute;opacity:0;pointer-events:none;width:1px;height:1px"
       min="<?= $minW ?>" step="0.01">

<!-- ── WALLET CHIPS ── -->
<div class="aw-wallets-lbl">Select Wallet</div>
<div class="aw-wallets" id="walletsRow">
<?php foreach ($availWallets as $i => $w): ?>
<div class="aw-wchip <?= $i===$defaultIdx?'sel':'' ?>"
     id="wchip_<?= $w['type'] ?>"
     style="--wc:<?= $w['color'] ?>"
     onclick="selectW('<?= $w['type'] ?>',<?= $w['balance'] ?>,'<?= addslashes($w['name']) ?>','<?= $w['icon'] ?>','<?= $w['color'] ?>',this)">
    <input type="radio" value="<?= $w['type'] ?>" <?= $i===$defaultIdx?'checked':'' ?>>
    <div class="aw-wchip-ico" style="background:<?= $w['color'] ?>">
        <i class="fa-solid <?= $w['icon'] ?>"></i>
    </div>
    <div>
        <div class="aw-wchip-name"><?= $w['name'] ?></div>
        <div class="aw-wchip-bal"><?= $cSym.' '.number_format($w['balance'],2) ?></div>
    </div>
    <span class="aw-wchip-dot"></span>
    <?php if (!$w['can_withdraw']): ?>
    <span style="font-size:9px;color:var(--WN);font-weight:700;flex-shrink:0;margin-left:2px">Low</span>
    <?php endif; ?>
</div>
<?php endforeach; ?>
</div>

<!-- ── CONFIRM DRAWER ── -->
<div class="aw-confirm" id="awConfirm">
    <div class="aw-confirm-hdr">
        <span class="aw-confirm-title"><i class="fa-solid fa-receipt"></i>Transfer Summary</span>
        <span style="font-size:10px;color:var(--txt2)">Review before sending</span>
    </div>
    <div class="aw-confirm-body">
        <div class="aw-rcpt">
            <div class="aw-rcpt-row">
                <span class="aw-rcpt-k">Gross amount</span>
                <span class="aw-rcpt-v" id="rcptGross">—</span>
            </div>
            <div class="aw-rcpt-row">
                <span class="aw-rcpt-k">Processing fee</span>
                <span class="aw-rcpt-v" style="color:var(--DN)" id="rcptFee">—</span>
            </div>
            <div class="aw-rcpt-row">
                <span class="aw-rcpt-k">From wallet</span>
                <span class="aw-rcpt-v" id="rcptWallet">—</span>
            </div>
            <div class="aw-rcpt-row total">
                <span class="aw-rcpt-k" style="font-weight:700;color:var(--txt)">You receive</span>
                <span class="aw-rcpt-v big" id="rcptNet">—</span>
            </div>
        </div>
        <div class="aw-phone-row">
            <div class="aw-phone-ico"><i class="fa-solid fa-sim-card"></i></div>
            <div>
                <div class="aw-phone-lbl">M-Pesa</div>
                <div class="aw-phone-num"><?= htmlspecialchars($userData['phone']??'Not set') ?></div>
            </div>
            <a href="profile.php" class="aw-phone-edit">
                <i class="fa-solid fa-pen" style="font-size:9px"></i> Edit
            </a>
        </div>
    </div>
</div>

<!-- ── SUBMIT ── -->
<button class="aw-submit" id="awSubmitBtn">
    <?php if (HASHBACK_ENABLED): ?>
        <i class="fa-solid fa-bolt"></i> Send Instantly
    <?php else: ?>
        <i class="fa-solid fa-paper-plane"></i> Submit Withdrawal
    <?php endif; ?>
</button>

<form method="POST" id="awForm">
    <input type="hidden" name="wallet_type"  id="fWalletType" value="<?= $availWallets[$defaultIdx]['type']??'' ?>">
    <input type="hidden" name="amount"        id="fAmount"     value="">
    <input type="hidden" name="phone_number"  value="<?= htmlspecialchars($userData['phone']??'') ?>">
</form>

<?php endif; ?>
</div><!-- /.aw -->

<!-- ── TOAST ── -->
<div class="aw-toast" id="awToast">
    <div class="aw-toast-ico" id="awToastIco"></div>
    <div style="flex:1;min-width:0">
        <div class="aw-toast-title" id="awToastTitle"></div>
        <div class="aw-toast-msg"   id="awToastMsg"></div>
    </div>
    <button class="aw-toast-cls" onclick="hideToast()">&#215;</button>
</div>

<!-- ── SUCCESS MODAL ── -->
<div class="aw-modal-bg" id="awSuccessModal">
    <div class="aw-modal">
        <div class="aw-modal-head" id="smHead">
            <span class="aw-modal-emoji" id="smEmoji">🎉</span>
            <div class="aw-modal-h" id="smH"></div>
            <div class="aw-modal-s" id="smS"></div>
        </div>
        <div class="aw-modal-body">
            <div class="aw-modal-amt">
                <div class="aw-modal-amt-lbl" id="smAmtLbl"></div>
                <div class="aw-modal-amt-num" id="smAmtNum"></div>
            </div>
            <div class="aw-modal-info" id="smInfo"></div>
        </div>
        <div class="aw-modal-actions">
            <a href="withdrawal_history.php" class="aw-modal-btn ghost">
                <i class="fa-solid fa-clock-rotate-left" style="font-size:11px"></i> History
            </a>
            <button onclick="closeSuccessModal()" class="aw-modal-btn primary">
                <i class="fa-solid fa-plus" style="font-size:11px"></i> New Request
            </button>
        </div>
    </div>
</div>

<?php if ($notif): ?>
<script>
window.addEventListener('DOMContentLoaded', function(){
    <?php if ($notif['type']==='success'): ?>
    showSuccessModal(
        <?= json_encode(($notif['currency']??$cSym).' '.number_format($notif['net']??0,2)) ?>,
        <?= !empty($notif['auto'])?'true':'false' ?>
    );
    <?php else: ?>
    showToast('Withdrawal Failed', <?= json_encode($notif['message']) ?>, 'error');
    <?php endif; ?>
});
</script>
<?php endif; ?>

<script>
/* ── PHP → JS constants ── */
var CS      = '<?= addslashes($cSym) ?>';
var TFEES   = <?= json_encode($tieredFees) ?>;
var FLAT    = <?= $flatFee ?>;
var MINW    = <?= $minW ?>;
var IS_AUTO = <?= HASHBACK_ENABLED?'true':'false' ?>;
var ADMIN_P = '<?= addslashes($adminPrimary) ?>';
var ADMIN_OK= '<?= addslashes($adminSuccess) ?>';
var ADMIN_DN= '<?= addslashes($adminDanger)  ?>';
var ADMIN_WN= '<?= addslashes($adminWarning) ?>';

var selBal    = <?= floatval($availWallets[$defaultIdx]['balance']??0) ?>;
var selWallet = '<?= addslashes($availWallets[$defaultIdx]['type']??'') ?>';
var selName   = '<?= addslashes($availWallets[$defaultIdx]['name']??'') ?>';
var curAmt    = 0;
var _tt       = null;

/* ── Toast (identical to dashboard/store pattern) ── */
function showToast(title, msg, type) {
    var t   = document.getElementById('awToast');
    var ico = document.getElementById('awToastIco');
    var ttl = document.getElementById('awToastTitle');
    var tm  = document.getElementById('awToastMsg');
    var cols  = {success:ADMIN_OK, error:ADMIN_DN, warning:ADMIN_WN, info:ADMIN_P};
    var icons = {success:'fa-circle-check', error:'fa-circle-xmark', warning:'fa-triangle-exclamation', info:'fa-circle-info'};
    var col = cols[type] || ADMIN_P;
    t.style.borderLeftColor = col;
    ico.style.background    = col;
    ico.innerHTML = '<i class="fa-solid '+icons[type]+'"></i>';
    ttl.textContent = title;
    tm.textContent  = msg;
    t.classList.add('show');
    clearTimeout(_tt);
    _tt = setTimeout(hideToast, type==='error' ? 7000 : 4000);
}
function hideToast() { document.getElementById('awToast').classList.remove('show'); }

/* ── Success Modal ── */
function showSuccessModal(amtStr, isInstant) {
    var m  = document.getElementById('awSuccessModal');
    var hd = document.getElementById('smHead');
    document.getElementById('smEmoji').textContent  = isInstant ? '⚡' : '🎉';
    document.getElementById('smH').textContent      = isInstant ? 'Money Sent!' : 'Submitted!';
    document.getElementById('smS').textContent      = isInstant ? 'M-Pesa transfer initiated' : 'Queued for processing';
    document.getElementById('smAmtLbl').textContent = isInstant ? 'Amount Sent' : 'You Will Receive';
    document.getElementById('smAmtNum').textContent = amtStr;
    document.getElementById('smInfo').textContent   = isInstant
        ? 'Your M-Pesa transfer is on the way. You should receive a confirmation SMS shortly.'
        : 'Your withdrawal has been received and will be processed by our team within 24 hours.';
    hd.style.background = isInstant
        ? 'linear-gradient(135deg,' + ADMIN_P + ',#8b5cf6)'
        : 'linear-gradient(135deg,' + ADMIN_OK + ',#059669)';
    m.style.display = 'flex';
    document.body.style.overflow = 'hidden';
    setTimeout(closeSuccessModal, 18000);
}
function closeSuccessModal() {
    var m = document.getElementById('awSuccessModal');
    m.style.opacity = '0'; m.style.transition = 'opacity .22s';
    setTimeout(function(){ m.style.display='none'; m.style.opacity='1'; document.body.style.overflow=''; }, 230);
}

/* ── Wallet select ── */
function selectW(type, bal, name, icon, color, el) {
    document.querySelectorAll('.aw-wchip').forEach(function(c){ c.classList.remove('sel'); });
    el.classList.add('sel');
    selBal = bal; selWallet = type; selName = name;
    document.getElementById('fWalletType').value = type;
    document.getElementById('activeChipIco').style.background  = color;
    document.getElementById('activeChipIcon').className = 'fa-solid ' + icon;
    document.getElementById('activeChipName').textContent = name;
    document.getElementById('balDisplay').textContent = CS + ' ' + bal.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g,',');
    document.getElementById('rcptWallet').textContent = name + ' Wallet';
    updateDisplay(curAmt);
    if (bal === 0) showToast('Empty Wallet', name + ' wallet has no balance.', 'warning');
}
function scrollToWallets() {
    document.getElementById('walletsRow').scrollIntoView({behavior:'smooth',block:'nearest'});
}

/* ── Amount logic ── */
function getFee(amt) {
    if (TFEES && TFEES.length)
        for (var i=0; i<TFEES.length; i++)
            if (amt >= parseFloat(TFEES[i].min_amount) && amt <= parseFloat(TFEES[i].max_amount))
                return parseFloat(TFEES[i].fee);
    return FLAT;
}
function fmt(n) {
    return CS + ' ' + n.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g,',');
}

function updateDisplay(amt) {
    curAmt = amt;
    var disp    = document.getElementById('displayAmt');
    var confirm = document.getElementById('awConfirm');
    var btn     = document.getElementById('awSubmitBtn');

    disp.textContent = amt > 0 ? amt.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g,',') : '0.00';
    disp.classList.toggle('has-val', amt > 0);

    if (amt > 0) {
        var fee = getFee(amt), net = amt - fee;
        document.getElementById('rcptGross').textContent  = fmt(amt);
        document.getElementById('rcptFee').textContent    = '− '+fmt(fee);
        document.getElementById('rcptNet').textContent    = net > 0 ? fmt(net) : '—';
        document.getElementById('rcptWallet').textContent = selName + ' Wallet';
        confirm.classList.add('show');
        document.getElementById('fAmount').value = amt.toFixed(2);

        if (amt < MINW) {
            btn.disabled = true; btn.style.background = ADMIN_WN;
            btn.innerHTML = '<i class="fa-solid fa-triangle-exclamation"></i> Min is '+CS+' '+MINW.toFixed(0);
        } else if (amt > selBal) {
            btn.disabled = true; btn.style.background = ADMIN_DN;
            btn.innerHTML = '<i class="fa-solid fa-triangle-exclamation"></i> Exceeds Balance';
        } else if (net <= 0) {
            btn.disabled = true; btn.style.background = ADMIN_DN;
            btn.innerHTML = '<i class="fa-solid fa-triangle-exclamation"></i> Too Low After Fee';
        } else {
            btn.disabled = false; btn.style.background = ADMIN_P;
            btn.innerHTML = IS_AUTO
                ? '<i class="fa-solid fa-bolt"></i> Send '+fmt(net)+' Instantly'
                : '<i class="fa-solid fa-paper-plane"></i> Submit · Receive '+fmt(net);
        }
    } else {
        confirm.classList.remove('show');
        btn.disabled = false; btn.style.background = ADMIN_P;
        btn.innerHTML = IS_AUTO
            ? '<i class="fa-solid fa-bolt"></i> Send Instantly'
            : '<i class="fa-solid fa-paper-plane"></i> Submit Withdrawal';
    }

    document.querySelectorAll('.aw-qbtn').forEach(function(b) {
        var v = parseFloat(b.textContent.replace(/[^0-9.]/g,''));
        b.classList.toggle('active', Math.abs(v-amt) < 0.01);
    });
    /* active chip color for quick buttons */
    document.querySelectorAll('.aw-qbtn.active').forEach(function(b){
        b.style.background = ADMIN_P;
        b.style.color = '#fff';
        b.style.borderColor = 'transparent';
    });
    document.querySelectorAll('.aw-qbtn:not(.active)').forEach(function(b){
        b.style.background = '';
        b.style.color = '';
        b.style.borderColor = '';
    });
}

function quickAmt(v) { updateDisplay(Math.min(v, selBal > 0 ? Math.min(v,selBal) : v)); }
function setMax()    { updateDisplay(selBal); }

/* ── Submit ── */
document.getElementById('awSubmitBtn').addEventListener('click', function() {
    if (this.disabled) return;
    if (curAmt <= 0) {
        showToast('Enter Amount', 'Tap the amount area and type how much you want to withdraw.', 'info');
        document.getElementById('hiddenAmt').focus();
        return;
    }
    document.getElementById('awForm').submit();
    this.disabled = true;
    this.style.background = 'var(--bg3)';
    this.style.color = 'var(--txt3)';
    this.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Processing…';
});

/* Tap screen → focus hidden input for keyboard */
document.getElementById('awScreen').addEventListener('click', function() {
    var inp = document.getElementById('hiddenAmt');
    inp.style.cssText = 'position:fixed;top:10px;left:50%;opacity:.01;width:80px;height:30px;font-size:16px;z-index:9999;border:none;outline:none';
    inp.focus();
});

document.getElementById('hiddenAmt').addEventListener('input', function() {
    updateDisplay(parseFloat(this.value) || 0);
});

document.addEventListener('keydown', function(e) {
    if (e.key==='Escape') { closeSuccessModal(); hideToast(); }
});

if (window.history.replaceState) window.history.replaceState(null, null, window.location.href);

/* Init wallet label */
document.getElementById('rcptWallet').textContent = '<?= addslashes($availWallets[$defaultIdx]['name']??'') ?> Wallet';
</script>

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