<?php
require_once 'db.php';
require_once 'auth_check.php';
require_once 'currency.php';

if (session_status() === PHP_SESSION_NONE) session_start();

$uid = $user_id;

function get_setting_w($conn, $key, $default = '') {
    $stmt = $conn->prepare("SELECT key_value FROM settings WHERE key_name=? LIMIT 1");
    $stmt->bind_param("s", $key);
    $stmt->execute();
    $r = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $r['key_value'] ?? $default;
}

$min_withdraw = (float) get_setting_w($conn, 'min_withdraw',     '500');
$max_withdraw = (float) get_setting_w($conn, 'max_withdraw',     '5000000');
$fee_pct      = (float) get_setting_w($conn, 'withdraw_fee_pct', '2');

// ── Reload fresh user data kila request ──────────────────────
$ustmt = $conn->prepare("SELECT * FROM users WHERE id=? LIMIT 1");
$ustmt->bind_param("i", $uid);
$ustmt->execute();
$u = $ustmt->get_result()->fetch_assoc();
$ustmt->close();

$balance          = (float)($u['balance']          ?? 0);
$security_deposit = (float)($u['security_deposit'] ?? 0);

// ── Handle POST ───────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount       = (float) ($_POST['amount']       ?? 0);
    $method_id    = (int)   ($_POST['method_id']    ?? 0);
    $account_ref  = trim(   $_POST['account_ref']   ?? '');
    $account_name = trim(   $_POST['account_name']  ?? '');
    $fund_pass    = trim(   $_POST['fund_password'] ?? '');
    $error        = '';

    $fee        = round($amount * $fee_pct / 100, 4);
    $net_amount = round($amount - $fee, 4);

    // ── Validations ────────────────────────────────────────
    if ($amount <= 0) {
        $error = 'Please enter a valid withdrawal amount.';
    } elseif ($amount < $min_withdraw) {
        $error = "Minimum withdrawal is " . number_format($min_withdraw, 0) . " {$currency}.";
    } elseif ($amount > $max_withdraw) {
        $error = "Maximum withdrawal per request is " . number_format($max_withdraw, 0) . " {$currency}.";
    } elseif ($amount > $balance) {
        $error = "Insufficient balance. Your available balance is " . number_format($balance, 2) . " {$currency}.";
    } elseif (!$method_id) {
        $error = 'Please select a withdrawal method.';
    } elseif (empty($account_ref)) {
        $error = 'Please enter your receiving account / phone number.';
    }

    // Fund password check
    if (!$error && !empty($u['fund_password'])) {
        if (empty($fund_pass)) {
            $error = 'Fund password is required to withdraw.';
        } elseif (!password_verify($fund_pass, $u['fund_password'])) {
            $error = 'Incorrect fund password. Please try again.';
        }
    }

    // Payment method check
    $mrow = null;
    if (!$error) {
        $stmt = $conn->prepare("SELECT name FROM payment_methods WHERE id=? AND active=1 LIMIT 1");
        $stmt->bind_param("i", $method_id);
        $stmt->execute();
        $mrow = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        if (!$mrow) $error = 'Invalid payment method selected.';
    }

    if (!$error) {
        $fp_ok = !empty($u['fund_password']) ? 1 : 0;

        $conn->begin_transaction();
        try {
            // ✅ Atomic deduct — double-check balance kwenye DB level
            $stmt = $conn->prepare("UPDATE users SET balance = balance - ? WHERE id = ? AND balance >= ?");
            $stmt->bind_param("did", $amount, $uid, $amount);
            $stmt->execute();
            if ($stmt->affected_rows !== 1) {
                throw new Exception('Insufficient balance. Please refresh and try again.');
            }
            $stmt->close();

            // Insert withdrawal
            $stmt2 = $conn->prepare("INSERT INTO withdrawals
                (user_id,amount,fee,net_amount,method,account_ref,account_name,fund_password_ok,status,created_at)
                VALUES (?,?,?,?,?,?,?,?,'pending',NOW())");
            $stmt2->bind_param("idddsssi",
                $uid, $amount, $fee, $net_amount,
                $mrow['name'], $account_ref, $account_name, $fp_ok);
            $stmt2->execute();
            $stmt2->close();

            // Log
            $desc = "Withdrawal request via {$mrow['name']} – pending";
            $stmt3 = $conn->prepare("INSERT INTO account_logs (user_id,type,category,amount,description)
                                     VALUES (?,'expense','withdraw',?,?)");
            $stmt3->bind_param("ids", $uid, $amount, $desc);
            $stmt3->execute();
            $stmt3->close();

            $conn->commit();

            // ✅ PRG — redirect ili kuzuia duplicate kwa refresh
            $net_fmt = number_format($net_amount, 2);
            $fee_fmt = number_format($fee, 2);
            $amt_fmt = number_format($amount, 2);
            $_SESSION['wd_success'] = "Withdrawal of {$amt_fmt} {$currency} submitted! "
                . "Fee: {$fee_fmt} {$currency}. "
                . "You will receive {$net_fmt} {$currency} within 24 hours.";
            header('Location: withdraw.php');
            exit;

        } catch (Exception $e) {
            $conn->rollback();
            $_SESSION['wd_error'] = 'Transaction failed: ' . $e->getMessage();
            header('Location: withdraw.php');
            exit;
        }
    } else {
        // Validation error — redirect na flash
        $_SESSION['wd_error'] = $error;
        header('Location: withdraw.php');
        exit;
    }
}

// ── Flash messages ────────────────────────────────────────────
$success = $_SESSION['wd_success'] ?? '';
$error   = $_SESSION['wd_error']   ?? '';
unset($_SESSION['wd_success'], $_SESSION['wd_error']);

// ── Fetch payment methods ─────────────────────────────────────
$methods = [];
$mres = $conn->query("SELECT * FROM payment_methods WHERE active=1 ORDER BY sort_order ASC");
while ($row = $mres->fetch_assoc()) $methods[] = $row;

// ── Fetch recent withdrawals ──────────────────────────────────
$recent_wds = [];
$wstmt = $conn->prepare("SELECT * FROM withdrawals WHERE user_id=? ORDER BY created_at DESC LIMIT 10");
$wstmt->bind_param("i", $uid);
$wstmt->execute();
$wres = $wstmt->get_result();
while ($row = $wres->fetch_assoc()) $recent_wds[] = $row;
$wstmt->close();

$has_fund_pass = !empty($u['fund_password']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>WFM – Withdraw</title>
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
:root{
  --green:#2d7a3a;--green-lt:#3eaabb;
  --red:#e53935;--red-lt:#fdecea;
  --gold:#f5c518;--gold2:#c9960a;
  --text:#1a2a0a;--muted:#6a7a5a;--border:#e0ecd8;
  --r:14px;--r-sm:10px;
  --shadow:0 2px 16px rgba(0,50,0,.10);
}
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Outfit',sans-serif;background:linear-gradient(155deg,#b8cba8 0%,#8faa7a 55%,#5a8050 100%);min-height:100vh;padding-bottom:90px}

/* Top Bar */
.top-bar{position:sticky;top:0;z-index:200;background:rgba(18,46,18,.85);backdrop-filter:blur(14px);
  padding:13px 16px;display:flex;align-items:center;gap:10px;border-bottom:1px solid rgba(255,255,255,.1)}
.top-bar h1{font-size:17px;font-weight:700;color:#fff;flex:1;letter-spacing:-.2px}
.tab-btns{display:flex;gap:6px}
.tab-btn{padding:5px 14px;border-radius:20px;font-size:12px;font-weight:700;
  text-decoration:none;border:1.5px solid rgba(255,255,255,.35);color:rgba(255,255,255,.75)}
.tab-btn.active{background:var(--gold);color:#7a5000;border-color:var(--gold)}

/* Balance Banner */
.bal-banner{margin:14px 14px 0;background:linear-gradient(135deg,#1e3a1e,#2d5a2d);
  border-radius:var(--r);padding:18px 20px;display:flex;
  position:relative;overflow:hidden;box-shadow:0 4px 20px rgba(0,0,0,.18)}
.bal-banner::after{content:'';position:absolute;top:-40px;right:-40px;width:130px;height:130px;
  border-radius:50%;background:rgba(255,255,255,.04)}
.bb-col{flex:1;text-align:center;position:relative;z-index:1}
.bb-col+.bb-col{border-left:1px solid rgba(255,255,255,.1)}
.bb-lbl{font-size:10px;font-weight:600;color:rgba(255,255,255,.5);text-transform:uppercase;letter-spacing:.7px;margin-bottom:8px}
.bb-val{font-size:21px;font-weight:800;color:#fff}
.bb-val small{font-size:11px;font-weight:400;opacity:.5;margin-left:3px}
.bb-note{font-size:10px;margin-top:4px}
.bb-note.can-wd{color:#6ee7a0;font-weight:600}
.bb-note.locked{color:rgba(255,255,255,.38)}

/* Withdraw rule strip */
.rule-strip{margin:8px 14px 0;background:rgba(229,57,53,.08);
  border:1px solid rgba(229,57,53,.25);border-radius:var(--r-sm);
  padding:11px 14px;display:flex;align-items:flex-start;gap:10px}
.rule-strip svg{width:18px;height:18px;fill:var(--red);flex-shrink:0;margin-top:1px}
.rule-strip p{font-size:12px;color:#6b1a1a;line-height:1.65;font-weight:500}
.rule-strip strong{color:#4a0000}

/* Fee preview */
.fee-preview{background:#f8fdf8;border:1px solid #d0e8d0;border-radius:var(--r-sm);
  padding:12px 14px;margin-bottom:14px;display:none}
.fee-preview.show{display:block}
.fee-row{display:flex;justify-content:space-between;align-items:center;padding:4px 0;font-size:13px}
.fee-row:not(:last-child){border-bottom:1px solid #e8f0e8}
.fee-row .fl{color:var(--muted);font-weight:500}
.fee-row .fv{font-weight:700;color:var(--text)}
.fee-row.net .fv{color:var(--green);font-size:16px}

/* Card */
.card{margin:8px 14px 0;background:#fff;border-radius:var(--r);padding:18px 16px;box-shadow:var(--shadow)}
.card-title{font-size:14px;font-weight:700;color:var(--text);margin-bottom:16px;
  display:flex;align-items:center;gap:8px}
.card-title .dot{width:8px;height:8px;border-radius:50%;
  background:linear-gradient(135deg,var(--green-lt),var(--green));flex-shrink:0}

/* Payment methods */
.method-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-bottom:14px}
.method-option{position:relative}
.method-option input[type=radio]{position:absolute;opacity:0;width:0;height:0}
.method-label{display:flex;flex-direction:column;align-items:center;gap:5px;
  padding:10px 4px;border:2px solid var(--border);border-radius:var(--r-sm);
  cursor:pointer;text-align:center;transition:all .2s;min-height:70px;justify-content:center}
.method-label img{width:30px;height:30px;object-fit:contain}
.method-label .m-name{font-size:11px;font-weight:700;color:var(--text);line-height:1.2}
.method-option input:checked + .method-label{border-color:var(--green-lt);background:rgba(62,170,187,.08)}

/* Field */
.field{margin-bottom:14px}
.field label{display:block;font-size:11px;font-weight:700;color:var(--muted);
  margin-bottom:6px;text-transform:uppercase;letter-spacing:.5px}
.field input{width:100%;padding:13px 14px;border:2px solid var(--border);
  border-radius:var(--r-sm);font-family:'Outfit',sans-serif;font-size:14px;
  color:var(--text);background:#fff;outline:none;transition:border-color .2s}
.field input:focus{border-color:var(--green-lt)}
.field .hint{font-size:11px;color:var(--muted);margin-top:5px}

/* Max button */
.amt-wrap{position:relative}
.amt-wrap input{padding-right:70px}
.max-btn{position:absolute;right:10px;top:50%;transform:translateY(-50%);
  padding:4px 12px;border-radius:20px;background:var(--green);color:#fff;
  font-size:11px;font-weight:700;border:none;cursor:pointer;font-family:'Outfit',sans-serif}

/* Quick amounts */
.qa-row{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:10px}
.qa{padding:5px 14px;border-radius:20px;background:#f0f5ee;border:1.5px solid #d0e0c8;
  font-size:12px;font-weight:700;color:var(--green);cursor:pointer;transition:all .18s;white-space:nowrap}
.qa.sel,.qa:hover{background:var(--green);color:#fff;border-color:var(--green)}

/* Fund password field */
.fp-field{margin-bottom:14px;background:#fffbf0;border:1px solid #f0dfa0;
  border-radius:var(--r-sm);padding:12px 14px}
.fp-field label{display:block;font-size:11px;font-weight:700;color:#8a6600;
  margin-bottom:6px;text-transform:uppercase;letter-spacing:.5px}
.fp-field input{width:100%;padding:12px 14px;border:2px solid #e0cc80;
  border-radius:var(--r-sm);font-family:'Outfit',sans-serif;font-size:14px;
  color:var(--text);background:#fff;outline:none;transition:border-color .2s}
.fp-field input:focus{border-color:var(--gold2)}
.fp-field .hint{font-size:11px;color:#8a6600;margin-top:5px}

/* Submit */
.btn-submit{width:100%;padding:15px;background:linear-gradient(90deg,#b71c1c,#e53935);
  color:#fff;font-family:'Outfit',sans-serif;font-size:16px;font-weight:700;
  border:none;border-radius:var(--r);cursor:pointer;transition:opacity .2s;letter-spacing:.2px}
.btn-submit:hover{opacity:.88}
.btn-submit:active{opacity:.75;transform:scale(.98)}
.btn-submit:disabled{opacity:.45;cursor:not-allowed}

/* Alert */
.alert{margin:8px 14px 0;padding:14px 16px;border-radius:var(--r-sm);font-size:13px;line-height:1.55;font-weight:500}
.alert-ok{background:#eafaf0;border:1px solid #9de0b8;color:#14532d}
.alert-err{background:#fff0f0;border:1px solid #f0b8b8;color:#7f1d1d}
.alert svg{width:16px;height:16px;vertical-align:middle;margin-right:6px}

/* History */
.wd-list{display:flex;flex-direction:column;gap:0}
.wd-item{display:flex;align-items:center;gap:10px;padding:11px 0;border-bottom:1px solid #f0f4ee}
.wd-item:last-child{border-bottom:none}
.wd-icon{width:38px;height:38px;border-radius:50%;background:#fff0f0;
  display:flex;align-items:center;justify-content:center;flex-shrink:0}
.wd-icon svg{width:18px;height:18px;fill:var(--red)}
.wd-info{flex:1}
.wd-amount{font-size:15px;font-weight:800;color:var(--text)}
.wd-meta{font-size:11px;color:var(--muted);margin-top:2px}
.wd-net{font-size:11px;color:var(--green);font-weight:600;margin-top:2px}
.wd-badge{padding:3px 10px;border-radius:20px;font-size:10px;font-weight:700;
  text-transform:uppercase;letter-spacing:.4px;white-space:nowrap}
.wd-badge.pending{background:#fff8e0;color:#a07000}
.wd-badge.approved{background:#e6f9ef;color:#14532d}
.wd-badge.rejected{background:#fff0f0;color:#7f1d1d}
.empty-msg{text-align:center;padding:24px 0;color:var(--muted);font-size:13px}

/* Bottom Nav */
.bottom-nav{position:fixed;bottom:0;left:0;right:0;height:64px;background:#fff;
  border-top:1px solid #e0e0e0;display:flex;align-items:center;justify-content:space-around;z-index:1000}
.bn-item{display:flex;flex-direction:column;align-items:center;gap:3px;text-decoration:none;flex:1;padding:6px 0}
.bn-item .bn-icon{width:26px;height:26px;background-size:contain;background-repeat:no-repeat;background-position:center}
.bn-item span{font-size:10px;font-weight:600}
.bn-item.active span{color:#3eaabb}
.bn-item:not(.active) span{color:#aaa}
</style>
</head>
<body>

<!-- Top Bar — back arrow imeondolewa -->
<div class="top-bar">
  <h1>Withdraw</h1>
  <div class="tab-btns">
    <a href="deposit.php" class="tab-btn">Deposit</a>
    <a href="withdraw.php" class="tab-btn active">Withdraw</a>
  </div>
</div>

<!-- Balance Banner -->
<div class="bal-banner">
  <div class="bb-col">
    <div class="bb-lbl">Account Balance</div>
    <div class="bb-val"><?= number_format($balance,2) ?><small><?= $currency ?></small></div>
    <div class="bb-note can-wd">✓ Available to withdraw</div>
  </div>
  <div class="bb-col">
    <div class="bb-lbl">Security Deposit</div>
    <div class="bb-val"><?= number_format($security_deposit,2) ?><small><?= $currency ?></small></div>
    <div class="bb-note locked">🔒 Not withdrawable</div>
  </div>
</div>

<!-- Rule Strip -->
<div class="rule-strip">
  <svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/></svg>
  <p>Withdrawals are from your <strong>Account Balance only</strong> (earnings, tasks, referrals, bonuses). Your Security Deposit cannot be withdrawn — it is your investment collateral. Fee: <strong><?= $fee_pct ?>%</strong> per withdrawal.</p>
</div>

<!-- Alerts -->
<?php if ($success): ?>
<div class="alert alert-ok">
  <svg viewBox="0 0 24 24" fill="currentColor"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>
  <?= htmlspecialchars($success) ?>
</div>
<?php elseif ($error): ?>
<div class="alert alert-err">
  <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/></svg>
  <?= htmlspecialchars($error) ?>
</div>
<?php endif; ?>

<?php if ($balance <= 0): ?>
<div class="alert alert-err" style="margin-top:8px">
  <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/></svg>
  Your Account Balance is 0. Complete tasks or earn referral rewards to build your withdrawable balance.
</div>
<?php endif; ?>

<!-- Withdrawal Form -->
<div class="card">
  <div class="card-title"><span class="dot"></span> New Withdrawal Request</div>

  <form method="POST" id="wdForm">

    <!-- ① Method -->
    <div class="field">
      <label>① Select Receiving Method</label>
      <div class="method-grid">
        <?php foreach ($methods as $pm): ?>
        <div class="method-option">
          <input type="radio" name="method_id" id="wm<?= $pm['id'] ?>"
                 value="<?= $pm['id'] ?>"
                 data-name="<?= htmlspecialchars($pm['name']) ?>">
          <label class="method-label" for="wm<?= $pm['id'] ?>">
            <?php if (!empty($pm['icon_url'])): ?>
            <img src="<?= htmlspecialchars($pm['icon_url']) ?>"
                 alt="<?= htmlspecialchars($pm['name']) ?>"
                 onerror="this.style.display='none'">
            <?php else: ?>
            <svg viewBox="0 0 24 24" width="30" height="30" fill="#a0b8a0"><path d="M20 4H4c-1.11 0-2 .89-2 2v12c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zm0 14H4v-6h16v6zm0-10H4V6h16v2z"/></svg>
            <?php endif; ?>
            <span class="m-name"><?= htmlspecialchars($pm['name']) ?></span>
          </label>
        </div>
        <?php endforeach; ?>
        <?php if (empty($methods)): ?>
        <p style="font-size:13px;color:var(--muted);grid-column:1/-1;padding:8px 0">No payment methods configured. Contact support.</p>
        <?php endif; ?>
      </div>
    </div>

    <!-- ② Amount -->
    <div class="field">
      <label>② Amount to Withdraw (<?= $currency ?>)</label>
      <div class="qa-row">
        <?php
        foreach ([500,1000,2000,5000,10000,20000] as $p):
          if ($p > $balance) continue;
        ?>
        <span class="qa" onclick="setWdAmt(<?= $p ?>,this)"><?= number_format($p) ?></span>
        <?php endforeach; ?>
      </div>
      <div class="amt-wrap">
        <input type="number" name="amount" id="wdAmt"
               placeholder="Min <?= number_format($min_withdraw,0) ?>"
               min="<?= $min_withdraw ?>" max="<?= min($max_withdraw,$balance) ?>"
               step="any" required
               oninput="calcFee(this.value)"
               <?= $balance <= 0 ? 'disabled' : '' ?>>
        <button type="button" class="max-btn" onclick="setMax()">MAX</button>
      </div>
      <p class="hint">Available: <?= number_format($balance,2) ?> <?= $currency ?> · Min: <?= number_format($min_withdraw,0) ?> · Fee: <?= $fee_pct ?>%</p>
    </div>

    <!-- Fee Preview -->
    <div class="fee-preview" id="feePreview">
      <div class="fee-row">
        <span class="fl">Withdrawal Amount</span>
        <span class="fv" id="fvAmt">—</span>
      </div>
      <div class="fee-row">
        <span class="fl">Fee (<?= $fee_pct ?>%)</span>
        <span class="fv" id="fvFee" style="color:var(--red)">—</span>
      </div>
      <div class="fee-row net">
        <span class="fl" style="font-weight:700;color:var(--green)">You Will Receive</span>
        <span class="fv" id="fvNet">—</span>
      </div>
    </div>

    <!-- ③ Account -->
    <div class="field">
      <label>③ Receiving Phone / Wallet Address</label>
      <input type="text" name="account_ref"
             placeholder="e.g. 0712 345 678 or TRC20 wallet" required>
    </div>

    <!-- ④ Account Name -->
    <div class="field">
      <label>④ Account Holder Name</label>
      <input type="text" name="account_name"
             placeholder="Name on the account"
             value="<?= htmlspecialchars($u['full_name'] ?? '') ?>">
    </div>

    <!-- ⑤ Fund Password (if set) -->
    <?php if ($has_fund_pass): ?>
    <div class="fp-field">
      <label>⑤ Fund Password <span style="color:#c00">*</span></label>
      <input type="password" name="fund_password" placeholder="Enter your fund password" required>
      <p class="hint">🔒 Required to authorise withdrawals.</p>
    </div>
    <?php else: ?>
    <div style="background:#fffbf0;border:1px solid #e8d080;border-radius:var(--r-sm);
                padding:11px 14px;margin-bottom:14px;font-size:12px;color:#7a6000;font-weight:500">
      💡 Tip: Set a <a href="info.php" style="color:var(--green);font-weight:700">Fund Password</a> in your profile to protect future withdrawals.
    </div>
    <?php endif; ?>

    <button type="submit" class="btn-submit" <?= $balance <= 0 ? 'disabled' : '' ?>>
      ⬇ Submit Withdrawal Request
    </button>
  </form>
</div>

<!-- Recent Withdrawals -->
<div class="card" style="margin-bottom:12px">
  <div class="card-title"><span class="dot"></span> Recent Withdrawals</div>
  <?php if (empty($recent_wds)): ?>
    <div class="empty-msg">No withdrawal history yet.</div>
  <?php else: ?>
  <div class="wd-list">
    <?php foreach ($recent_wds as $w): ?>
    <div class="wd-item">
      <div class="wd-icon">
        <svg viewBox="0 0 24 24"><path d="M20 12l-1.41-1.41L13 16.17V4h-2v12.17l-5.58-5.59L4 12l8 8 8-8z"/></svg>
      </div>
      <div class="wd-info">
        <div class="wd-amount">-<?= number_format($w['amount'],2) ?> <?= $currency ?></div>
        <div class="wd-meta"><?= htmlspecialchars($w['method']) ?> → <?= htmlspecialchars($w['account_ref']) ?></div>
        <div class="wd-net">You receive: <?= number_format($w['net_amount'],2) ?> <?= $currency ?>
          (fee: <?= number_format($w['fee'],2) ?>)</div>
        <div class="wd-meta" style="color:#bbb"><?= date('d M Y H:i', strtotime($w['created_at'])) ?></div>
      </div>
      <span class="wd-badge <?= htmlspecialchars($w['status']) ?>"><?= ucfirst(htmlspecialchars($w['status'])) ?></span>
    </div>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>
</div>

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

<script>
const MAX_BAL  = <?= $balance ?>;
const FEE_PCT  = <?= $fee_pct ?>;
const CURRENCY = '<?= $currency ?>';

function fmt(n) {
  return n.toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2});
}

function calcFee(val) {
  const amt     = parseFloat(val);
  const preview = document.getElementById('feePreview');
  if (!amt || amt <= 0) { preview.classList.remove('show'); return; }
  const fee = amt * FEE_PCT / 100;
  const net = amt - fee;
  document.getElementById('fvAmt').textContent = fmt(amt) + ' ' + CURRENCY;
  document.getElementById('fvFee').textContent = '-' + fmt(fee) + ' ' + CURRENCY;
  document.getElementById('fvNet').textContent = fmt(net) + ' ' + CURRENCY;
  preview.classList.add('show');
}

function setWdAmt(v, el) {
  const inp = document.getElementById('wdAmt');
  inp.value = v;
  calcFee(v);
  document.querySelectorAll('.qa').forEach(q => q.classList.remove('sel'));
  el.classList.add('sel');
}

function setMax() {
  const inp = document.getElementById('wdAmt');
  inp.value = MAX_BAL;
  calcFee(MAX_BAL);
  document.querySelectorAll('.qa').forEach(q => q.classList.remove('sel'));
}
</script>
</body>
</html>