<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once '../include/config.php';

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header('Location: ../signin.php');
    exit();
}

// ── Fetch fresh user data ─────────────────────────────────────────────────
try {
    $stmt = $pdo->prepare("SELECT id, username, email, full_name, phone, main_balance, referral_balance, total_earnings FROM users WHERE id = :uid");
    $stmt->execute([':uid' => $_SESSION['user_id']]);
    if ($stmt->rowCount() == 1) {
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
    } else {
        session_destroy();
        header('Location: ../signin.php');
        exit();
    }
} catch (PDOException $e) {
    die("Error: " . $e->getMessage());
}

// ── Settings ──────────────────────────────────────────────────────────────
$min_redeem = floatval($site_data['min_redeem'] ?? 10000);

// ── Fetch active withdrawal methods ───────────────────────────────────────
try {
    $wm_stmt = $pdo->prepare("SELECT * FROM withdrawal_methods WHERE status = 'active' ORDER BY method_name ASC");
    $wm_stmt->execute();
    $withdrawal_methods = $wm_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $withdrawal_methods = [];
}

// ── Fetch user's withdrawal history ───────────────────────────────────────
try {
    $wh_stmt = $pdo->prepare("SELECT * FROM withdrawals WHERE user_id = :uid ORDER BY created_at DESC LIMIT 20");
    $wh_stmt->execute([':uid' => $user['id']]);
    $withdrawal_history = $wh_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $withdrawal_history = [];
}

$error_message   = '';
$success_message = '';
if (!empty($_SESSION['withdraw_success'])) { $success_message = $_SESSION['withdraw_success']; unset($_SESSION['withdraw_success']); }
if (!empty($_SESSION['withdraw_error']))   { $error_message   = $_SESSION['withdraw_error'];   unset($_SESSION['withdraw_error']);   }

$referral_balance = floatval($user['referral_balance']);
$can_withdraw     = $referral_balance >= $min_redeem;

$page_title = $site_data['web_name'] . " | Withdraw Referral Earnings";
include ('header.php');
?>
<title><?php echo $page_title; ?></title>

<style>
@keyframes fadeUp{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)}}
.anim{opacity:0;animation:fadeUp .45s ease-out forwards}
.anim-1{animation-delay:.05s}.anim-2{animation-delay:.12s}.anim-3{animation-delay:.19s}.anim-4{animation-delay:.26s}

/* ── Hero: green gradient copied from referral.php ── */
.wd-hero{background:linear-gradient(145deg,#011a14 0%,#022c22 40%,#064e3b 80%,#047857 100%);border:1px solid rgba(245,158,11,.15);border-radius:20px;padding:20px;position:relative;overflow:hidden;margin-bottom:16px}
.wd-hero::before{content:'';position:absolute;inset:0;background:repeating-linear-gradient(-45deg,transparent,transparent 35px,rgba(245,158,11,.012) 35px,rgba(245,158,11,.012) 36px);pointer-events:none}

.wd-card{background:var(--card-bg);border:1px solid var(--card-border);box-shadow:var(--card-shadow);border-radius:16px;padding:20px;margin-bottom:14px}
.method-card{border:1.5px solid var(--card-border);border-radius:13px;padding:14px;cursor:pointer;transition:all .2s ease;position:relative;background:var(--card-bg)}
.method-card:has(input:checked){border-color:#16a354;background:rgba(34,184,100,.04)}
.dark .method-card:has(input:checked){background:rgba(34,184,100,.08)}
.txn-item{border:1px solid var(--card-border);border-radius:11px;padding:12px;transition:border-color .2s}
.txn-item:hover{border-color:rgba(34,184,100,.25)}
.locked-overlay{position:relative;pointer-events:none;opacity:0.55;user-select:none}

/* ── Mobile-first card fit ── */
@media(max-width:640px){
    .wd-card{padding:14px;border-radius:13px}
    .wd-hero{padding:16px;border-radius:16px}
    #methodsContainer .method-card{padding:12px}
    .wd-hero .hero-grid{grid-template-columns:1fr!important}
}
</style>

<div class="max-w-2xl mx-auto">

<?php if ($error_message): ?>
<div class="anim anim-1 mb-4" style="background:rgba(239,68,68,.06);border:1px solid rgba(239,68,68,.18);border-radius:12px;padding:12px 16px;display:flex;align-items:center;gap:10px;">
    <i class="fas fa-circle-exclamation text-red-500 text-base flex-shrink-0"></i>
    <p style="font-size:.82rem;color:#dc2626;"><?php echo htmlspecialchars($error_message); ?></p>
</div>
<?php endif; ?>
<?php if ($success_message): ?>
<div class="anim anim-1 mb-4" style="background:rgba(34,184,100,.06);border:1px solid rgba(34,184,100,.18);border-radius:12px;padding:12px 16px;display:flex;align-items:center;gap:10px;">
    <i class="fas fa-circle-check" style="color:#16a354;" class="text-base flex-shrink-0"></i>
    <p style="font-size:.82rem;color:#15803d;"><?php echo htmlspecialchars($success_message); ?></p>
</div>
<?php endif; ?>

<!-- Hero -->
<div class="wd-hero anim anim-1">
    <div style="position:absolute;width:160px;height:160px;border-radius:50%;filter:blur(50px);background:radial-gradient(circle,rgba(245,158,11,.15),transparent);top:-40px;right:-40px;pointer-events:none;"></div>
    <div style="position:relative;z-index:1;">
        <div style="display:flex;align-items:center;gap:10px;margin-bottom:14px;">
            <div style="width:36px;height:36px;border-radius:9px;background:rgba(255,255,255,.1);display:flex;align-items:center;justify-content:center;">
                <i class="fas fa-money-bill-transfer text-white text-sm"></i>
            </div>
            <div>
                <p style="font-size:.62rem;color:rgba(255,255,255,.55);font-weight:700;text-transform:uppercase;letter-spacing:.08em;">Referral Withdrawal</p>
                <p style="font-size:.9rem;font-weight:700;color:white;">Withdraw Your Earnings</p>
            </div>
        </div>
        <div class="hero-grid" style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
            <div style="background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);border-radius:12px;padding:12px 16px;">
                <p style="font-size:.62rem;color:rgba(255,255,255,.5);font-weight:600;text-transform:uppercase;letter-spacing:.06em;">Referral Balance</p>
                <p style="font-size:1.2rem;font-weight:800;color:#fbbf24;font-family:monospace;letter-spacing:-.02em;">₦<?php echo number_format($referral_balance, 2); ?></p>
            </div>
            <div style="background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);border-radius:12px;padding:12px 16px;">
                <p style="font-size:.62rem;color:rgba(255,255,255,.5);font-weight:600;text-transform:uppercase;letter-spacing:.06em;">Min. Withdrawal</p>
                <p style="font-size:1.2rem;font-weight:800;color:white;font-family:monospace;letter-spacing:-.02em;">₦<?php echo number_format($min_redeem, 2); ?></p>
            </div>
        </div>
    </div>
</div>

<?php if (!$can_withdraw): ?>
<!-- Locked State -->
<div class="wd-card anim anim-2">
    <div style="text-align:center;padding:24px 0;">
        <div style="width:60px;height:60px;border-radius:50%;background:rgba(239,68,68,.08);border:2px solid rgba(239,68,68,.15);display:flex;align-items:center;justify-content:center;margin:0 auto 16px;">
            <i class="fas fa-lock" style="font-size:1.4rem;color:#dc2626;"></i>
        </div>
        <p style="font-weight:800;font-size:.95rem;color:var(--text-primary);margin-bottom:6px;">Withdrawal Locked</p>
        <p style="font-size:.8rem;color:var(--text-muted);line-height:1.6;max-width:300px;margin:0 auto 16px;">
            You need at least <strong style="color:#16a354;">₦<?php echo number_format($min_redeem, 2); ?></strong> in referral balance to withdraw.
            You currently have <strong style="color:#dc2626;">₦<?php echo number_format($referral_balance, 2); ?></strong>.
        </p>
        <?php $remaining = $min_redeem - $referral_balance; ?>
        <div style="background:rgba(34,184,100,.06);border:1px solid rgba(34,184,100,.15);border-radius:10px;padding:10px 16px;display:inline-block;">
            <p style="font-size:.78rem;color:#16a354;font-weight:700;">
                <i class="fas fa-chart-line mr-1"></i>
                ₦<?php echo number_format($remaining, 2); ?> more needed
            </p>
        </div>
        <!-- Progress bar -->
        <?php $pct = min(100, ($referral_balance / $min_redeem) * 100); ?>
        <div style="margin-top:16px;background:var(--card-border);border-radius:99px;height:8px;overflow:hidden;">
            <div style="width:<?php echo $pct; ?>%;height:100%;background:linear-gradient(90deg,#16a354,#22b864);border-radius:99px;transition:width .5s;"></div>
        </div>
        <p style="font-size:.68rem;color:var(--text-muted);margin-top:6px;"><?php echo round($pct, 1); ?>% towards withdrawal threshold</p>
    </div>
</div>
<?php else: ?>
<!-- Withdrawal Form -->
<div class="wd-card anim anim-2">
    <p style="font-weight:700;font-size:.88rem;color:var(--text-primary);margin-bottom:16px;display:flex;align-items:center;gap:8px;">
        <span style="width:28px;height:28px;border-radius:8px;background:rgba(34,184,100,.1);display:inline-flex;align-items:center;justify-content:center;">
            <i class="fas fa-hand-holding-dollar" style="font-size:.72rem;color:#16a354;"></i>
        </span>
        Withdrawal Request
    </p>

    <?php if (empty($withdrawal_methods)): ?>
    <div style="text-align:center;padding:20px;background:rgba(245,158,11,.05);border:1px solid rgba(245,158,11,.2);border-radius:12px;">
        <i class="fas fa-exclamation-triangle" style="color:#d97706;font-size:1.5rem;margin-bottom:8px;display:block;"></i>
        <p style="font-size:.82rem;color:var(--text-muted);">No withdrawal methods available at the moment. Please contact support.</p>
    </div>
    <?php else: ?>

    <form id="withdrawalForm">
        <!-- Amount -->
        <div style="margin-bottom:16px;">
            <label style="display:block;font-size:.8rem;font-weight:600;color:var(--text-primary);margin-bottom:6px;">
                Amount to Withdraw (NGN) <span style="color:#ef4444;">*</span>
            </label>
            <div style="position:relative;">
                <span style="position:absolute;left:14px;top:50%;transform:translateY(-50%);color:var(--text-muted);font-weight:600;">₦</span>
                <input type="number" id="wd_amount" name="amount"
                       min="<?php echo $min_redeem; ?>"
                       max="<?php echo $referral_balance; ?>"
                       step="0.01"
                       placeholder="<?php echo number_format($min_redeem, 2); ?>"
                       required
                       style="width:100%;padding:12px 14px 12px 32px;border-radius:10px;border:1.5px solid var(--card-border);background:var(--btn-bg);color:var(--hd-title);font-size:.88rem;outline:none;transition:border-color .2s;box-sizing:border-box;"
                       onfocus="this.style.borderColor='#16a354'" onblur="this.style.borderColor=''">
            </div>
            <p style="font-size:.7rem;color:var(--text-muted);margin-top:4px;">
                Min: ₦<?php echo number_format($min_redeem, 2); ?> | Available: ₦<?php echo number_format($referral_balance, 2); ?>
            </p>
        </div>

        <!-- Quick amounts -->
        <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px;">
            <button type="button" onclick="document.getElementById('wd_amount').value='<?php echo $referral_balance; ?>'"
                    style="padding:6px 12px;border-radius:8px;font-size:.72rem;font-weight:700;background:rgba(34,184,100,.07);border:1px solid rgba(34,184,100,.2);color:#16a354;cursor:pointer;transition:all .2s;">
                Withdraw All (₦<?php echo number_format($referral_balance, 2); ?>)
            </button>
        </div>

        <!-- Withdrawal Method -->
        <div style="margin-bottom:16px;">
            <label style="display:block;font-size:.8rem;font-weight:600;color:var(--text-primary);margin-bottom:10px;">
                Select Withdrawal Method <span style="color:#ef4444;">*</span>
            </label>
            <div id="methodsContainer" style="display:grid;gap:10px;">
                <?php foreach ($withdrawal_methods as $idx => $method): ?>
                <label class="method-card" style="display:block;cursor:pointer;">
                    <input type="radio" name="method_id" value="<?php echo $method['id']; ?>"
                           data-fee="<?php echo $method['fee_percentage']; ?>"
                           data-min="<?php echo $method['minimum_amount']; ?>"
                           data-max="<?php echo $method['maximum_amount'] ?? 0; ?>"
                           data-name="<?php echo htmlspecialchars($method['method_name']); ?>"
                           data-type="<?php echo $method['method_type']; ?>"
                           class="sr-only method-radio" <?php echo $idx === 0 ? 'checked' : ''; ?>>
                    <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:10px;">
                        <div style="display:flex;align-items:flex-start;gap:10px;">
                            <div style="width:38px;height:38px;border-radius:9px;<?php echo $method['method_type']==='bank'?'background:rgba(34,184,100,.1);':'background:rgba(245,158,11,.1);'; ?>display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                                <i class="fas <?php echo $method['method_type']==='bank'?'fa-building-columns text-emerald-600':'fa-coins text-amber-500'; ?> text-base"></i>
                            </div>
                            <div>
                                <p style="font-weight:700;font-size:.82rem;color:var(--text-primary);"><?php echo htmlspecialchars($method['method_name']); ?></p>
                                <p style="font-size:.68rem;color:var(--text-muted);margin-top:2px;line-height:1.4;">
                                    Fee: <?php echo $method['fee_percentage']; ?>% &bull;
                                    Min: ₦<?php echo number_format($method['minimum_amount'], 2); ?>
                                    <?php if ($method['maximum_amount']): ?> &bull; Max: ₦<?php echo number_format($method['maximum_amount'], 2); ?><?php endif; ?>
                                </p>
                                <p style="font-size:.65rem;color:var(--text-muted);margin-top:1px;">
                                    <i class="fas fa-clock mr-1"></i><?php echo htmlspecialchars($method['processing_time']); ?>
                                </p>
                            </div>
                        </div>
                        <div style="flex-shrink:0;width:18px;height:18px;border-radius:50%;border:2px solid var(--card-border);background:var(--btn-bg);display:flex;align-items:center;justify-content:center;" class="radio-indicator">
                        </div>
                    </div>
                    <?php if (!empty($method['instructions'])): ?>
                    <p style="font-size:.7rem;color:var(--text-muted);margin-top:8px;padding-top:8px;border-top:1px solid var(--card-border);line-height:1.5;">
                        <i class="fas fa-info-circle mr-1" style="color:#16a354;"></i>
                        <?php echo htmlspecialchars($method['instructions']); ?>
                    </p>
                    <?php endif; ?>
                </label>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Account/Wallet Details -->
        <div style="margin-bottom:16px;">
            <label style="display:block;font-size:.8rem;font-weight:600;color:var(--text-primary);margin-bottom:6px;" id="accountLabel">
                Bank Account Details <span style="color:#ef4444;">*</span>
            </label>
            <textarea id="wd_account" name="wallet_or_account" rows="4" required
                      placeholder="Account Number: 0123456789&#10;Account Name: John Doe&#10;Bank Name: First Bank"
                      style="width:100%;padding:12px 14px;border-radius:10px;border:1.5px solid var(--card-border);background:var(--btn-bg);color:var(--hd-title);font-size:.82rem;outline:none;transition:border-color .2s;resize:vertical;font-family:monospace;box-sizing:border-box;"
                      onfocus="this.style.borderColor='#16a354'" onblur="this.style.borderColor=''"></textarea>
            <p style="font-size:.7rem;color:var(--text-muted);margin-top:4px;" id="accountHint">
                Provide your account number, account name, and bank name.
            </p>
        </div>

        <!-- Fee & Summary -->
        <div id="feeSummary" style="background:rgba(34,184,100,.05);border:1px solid rgba(34,184,100,.15);border-radius:12px;padding:14px;margin-bottom:16px;display:none;">
            <p style="font-weight:700;font-size:.8rem;color:var(--text-primary);margin-bottom:10px;display:flex;align-items:center;gap:6px;">
                <i class="fas fa-calculator" style="color:#16a354;"></i> Withdrawal Summary
            </p>
            <div style="display:flex;flex-direction:column;gap:6px;">
                <div style="display:flex;justify-content:space-between;font-size:.78rem;">
                    <span style="color:var(--text-muted);">Amount Requested</span>
                    <span style="font-weight:700;color:var(--text-primary);" id="summaryAmount">₦0.00</span>
                </div>
                <div style="display:flex;justify-content:space-between;font-size:.78rem;">
                    <span style="color:var(--text-muted);">Processing Fee (<span id="summaryFeeRate">0</span>%)</span>
                    <span style="font-weight:700;color:#dc2626;" id="summaryFee">-₦0.00</span>
                </div>
                <div style="border-top:1px dashed var(--card-border);padding-top:6px;display:flex;justify-content:space-between;font-size:.82rem;">
                    <span style="font-weight:700;color:var(--text-primary);">You Receive</span>
                    <span style="font-weight:800;color:#16a354;font-family:monospace;" id="summaryFinal">₦0.00</span>
                </div>
            </div>
        </div>

        <button type="button" id="submitWithdrawal"
                style="width:100%;background:linear-gradient(135deg,#16a354,#22b864);color:white;font-weight:700;padding:14px;border-radius:12px;border:none;cursor:pointer;font-size:.88rem;display:flex;align-items:center;justify-content:center;gap:8px;box-shadow:0 4px 16px rgba(34,184,100,.28);transition:all .2s;">
            <i class="fas fa-paper-plane text-sm"></i>
            <span id="withdrawBtnText">Submit Withdrawal Request</span>
        </button>
    </form>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- Withdrawal History -->
<div class="wd-card anim anim-3">
    <p style="font-weight:700;font-size:.88rem;color:var(--text-primary);margin-bottom:14px;display:flex;align-items:center;gap:8px;">
        <span style="width:28px;height:28px;border-radius:8px;background:rgba(34,184,100,.1);display:inline-flex;align-items:center;justify-content:center;">
            <i class="fas fa-clock-rotate-left" style="font-size:.72rem;color:#16a354;"></i>
        </span>
        Withdrawal History
    </p>
    <?php if (empty($withdrawal_history)): ?>
    <div style="text-align:center;padding:32px 0;">
        <div style="width:52px;height:52px;border-radius:50%;background:rgba(34,184,100,.07);display:flex;align-items:center;justify-content:center;margin:0 auto 12px;">
            <i class="fas fa-receipt" style="font-size:1.2rem;color:var(--text-muted);"></i>
        </div>
        <p style="color:var(--text-muted);font-size:.82rem;">No withdrawal requests yet.</p>
    </div>
    <?php else: ?>
    <div style="display:flex;flex-direction:column;gap:8px;">
        <?php foreach ($withdrawal_history as $wd):
            if ($wd['status'] === 'completed')    { $sc='rgba(5,150,105,.08)';    $si='fa-check-circle';   $sic='#059669'; $badge='rgba(5,150,105,.1)';    $bc='#047857'; }
            elseif ($wd['status'] === 'rejected') { $sc='rgba(239,68,68,.06)';    $si='fa-times-circle';   $sic='#dc2626'; $badge='rgba(239,68,68,.08)';    $bc='#b91c1c'; }
            elseif ($wd['status'] === 'processing'){ $sc='rgba(59,130,246,.06)';  $si='fa-spinner fa-spin';$sic='#2563eb'; $badge='rgba(59,130,246,.08)';   $bc='#1d4ed8'; }
            elseif ($wd['status'] === 'cancelled'){ $sc='rgba(107,114,128,.06)';  $si='fa-ban';            $sic='#6b7280'; $badge='rgba(107,114,128,.08)';  $bc='#4b5563'; }
            else                                  { $sc='rgba(245,158,11,.06)';   $si='fa-clock';          $sic='#d97706'; $badge='rgba(245,158,11,.1)';    $bc='#b45309'; }
        ?>
        <div class="txn-item">
            <div style="display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;">
                <div style="display:flex;align-items:center;gap:10px;min-width:0;">
                    <div style="width:38px;height:38px;border-radius:9px;background:<?php echo $sc; ?>;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                        <i class="fas <?php echo $si; ?>" style="color:<?php echo $sic; ?>;"></i>
                    </div>
                    <div style="min-width:0;">
                        <p style="font-weight:600;font-size:.8rem;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"><?php echo htmlspecialchars($wd['method_name']); ?></p>
                        <p style="font-size:.68rem;color:var(--text-muted);margin-top:1px;"><?php echo date('M d, Y — h:i A', strtotime($wd['created_at'])); ?></p>
                    </div>
                </div>
                <div style="text-align:right;flex-shrink:0;">
                    <p style="font-weight:700;font-size:.85rem;color:var(--text-primary);">₦<?php echo number_format($wd['amount'], 2); ?></p>
                    <span style="font-size:.65rem;font-weight:600;padding:2px 8px;border-radius:99px;background:<?php echo $badge; ?>;color:<?php echo $bc; ?>;">
                        <?php echo ucfirst($wd['status']); ?>
                    </span>
                </div>
            </div>
            <div style="border-top:1px solid var(--card-border);padding-top:7px;margin-top:8px;">
                <p style="font-size:.65rem;color:var(--text-muted);">
                    Fee: ₦<?php echo number_format($wd['fee_amount'], 2); ?> |
                    You receive: <strong>₦<?php echo number_format($wd['final_amount'], 2); ?></strong>
                </p>
                <?php if (!empty($wd['admin_note'])): ?>
                <p style="font-size:.65rem;color:#d97706;margin-top:2px;">
                    <i class="fas fa-comment-alt mr-1"></i><?php echo htmlspecialchars($wd['admin_note']); ?>
                </p>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<div style="text-align:center;margin-bottom:20px;">
    <a href="referral.php" style="font-size:.8rem;color:#16a354;font-weight:600;display:inline-flex;align-items:center;gap:6px;text-decoration:none;">
        <i class="fas fa-arrow-left text-xs"></i> Back to Referral Dashboard
    </a>
</div>

</div><!-- /max-w -->

<script>
(function() {
    var methodRadios  = document.querySelectorAll('.method-radio');
    var amountInput   = document.getElementById('wd_amount');
    var feeSummary    = document.getElementById('feeSummary');
    var accountLabel  = document.getElementById('accountLabel');
    var accountHint   = document.getElementById('accountHint');
    var accountField  = document.getElementById('wd_account');

    var cryptoPlaceholders = {
        'crypto'      : 'Wallet Address: T9xABCD...\nNetwork: TRC20\nCoin: USDT',
        'bank'        : 'Account Number: 0123456789\nAccount Name: John Doe\nBank Name: First Bank',
        'mobile_money': 'Phone Number: 0800000000\nNetwork: MTN Mobile Money',
        'paypal'      : 'PayPal Email: your@email.com',
        'other'       : 'Provide your payment details clearly...'
    };
    var cryptoLabels = {
        'crypto'      : 'Crypto Wallet Address',
        'bank'        : 'Bank Account Details',
        'mobile_money': 'Mobile Money Details',
        'paypal'      : 'PayPal Email',
        'other'       : 'Payment Details'
    };

    function getCurrentMethod() {
        var checked = document.querySelector('.method-radio:checked');
        if (!checked) return null;
        return {
            id  : checked.value,
            fee : parseFloat(checked.dataset.fee)  || 0,
            min : parseFloat(checked.dataset.min)  || 0,
            max : parseFloat(checked.dataset.max)  || 0,
            name: checked.dataset.name,
            type: checked.dataset.type
        };
    }

    function updateSummary() {
        var m   = getCurrentMethod();
        var amt = parseFloat(amountInput ? amountInput.value : 0) || 0;
        if (!m || amt <= 0) { feeSummary.style.display = 'none'; return; }
        var fee   = Math.round((amt * m.fee / 100) * 100) / 100;
        var final = Math.round((amt - fee) * 100) / 100;
        document.getElementById('summaryAmount').textContent  = '₦' + amt.toLocaleString('en-NG', {minimumFractionDigits:2});
        document.getElementById('summaryFeeRate').textContent = m.fee;
        document.getElementById('summaryFee').textContent     = '-₦' + fee.toLocaleString('en-NG', {minimumFractionDigits:2});
        document.getElementById('summaryFinal').textContent   = '₦' + final.toLocaleString('en-NG', {minimumFractionDigits:2});
        feeSummary.style.display = 'block';
    }

    function updateMethodUI() {
        var m = getCurrentMethod();
        if (!m) return;
        var lbl = cryptoLabels[m.type]       || 'Payment Details';
        var ph  = cryptoPlaceholders[m.type] || 'Provide your payment details...';
        if (accountLabel) accountLabel.innerHTML = lbl + ' <span style="color:#ef4444;">*</span>';
        if (accountField) accountField.placeholder = ph;
        if (accountHint)  accountHint.textContent  = 'Enter your ' + lbl.toLowerCase() + ' for this withdrawal.';
        updateSummary();
    }

    methodRadios.forEach(function(r) {
        r.addEventListener('change', updateMethodUI);
    });

    if (amountInput) {
        amountInput.addEventListener('input', updateSummary);
    }

    updateMethodUI();

    // Submit
    var submitBtn = document.getElementById('submitWithdrawal');
    if (submitBtn) {
        submitBtn.addEventListener('click', function() {
            var m       = getCurrentMethod();
            var amt     = parseFloat(amountInput ? amountInput.value : 0) || 0;
            var account = accountField ? accountField.value.trim() : '';
            var maxBal  = <?php echo $referral_balance; ?>;
            var minWd   = <?php echo $min_redeem; ?>;

            if (!m)                               { showAlert('Please select a withdrawal method.'); return; }
            if (amt < minWd)                      { showAlert('Minimum withdrawal is ₦' + minWd.toLocaleString('en-NG', {minimumFractionDigits:2})); return; }
            if (amt > maxBal)                     { showAlert('Amount exceeds your referral balance of ₦' + maxBal.toLocaleString('en-NG', {minimumFractionDigits:2})); return; }
            if (m.min > 0 && amt < m.min)         { showAlert('Minimum for ' + m.name + ' is ₦' + m.min.toLocaleString('en-NG', {minimumFractionDigits:2})); return; }
            if (m.max > 0 && amt > m.max)         { showAlert('Maximum for ' + m.name + ' is ₦' + m.max.toLocaleString('en-NG', {minimumFractionDigits:2})); return; }
            if (!account)                         { showAlert('Please provide your account/wallet details.'); return; }

            if (!confirm('Confirm withdrawal of ₦' + amt.toLocaleString('en-NG', {minimumFractionDigits:2}) + ' via ' + m.name + '?')) return;

            submitBtn.disabled = true;
            document.getElementById('withdrawBtnText').textContent = 'Submitting...';
            submitBtn.style.opacity = '0.7';

            var formData = new FormData();
            formData.append('amount',            amt);
            formData.append('method_id',         m.id);
            formData.append('wallet_or_account', account);

            fetch('withdrawal-handler.php', {
                method: 'POST',
                body: formData
            })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                submitBtn.disabled = false;
                document.getElementById('withdrawBtnText').textContent = 'Submit Withdrawal Request';
                submitBtn.style.opacity = '1';
                if (data.status === '1') {
                    showSuccess(data.msg);
                    setTimeout(function(){ location.reload(); }, 2000);
                } else {
                    showAlert(data.msg);
                }
            })
            .catch(function() {
                submitBtn.disabled = false;
                document.getElementById('withdrawBtnText').textContent = 'Submit Withdrawal Request';
                submitBtn.style.opacity = '1';
                showAlert('A network error occurred. Please try again.');
            });
        });
    }

    function showAlert(msg) {
        var box = document.createElement('div');
        box.style.cssText = 'position:fixed;top:20px;right:20px;z-index:9999;background:#dc2626;color:white;padding:12px 18px;border-radius:10px;font-size:.82rem;font-weight:600;max-width:320px;box-shadow:0 4px 20px rgba(0,0,0,.2);';
        box.textContent = msg;
        document.body.appendChild(box);
        setTimeout(function(){ box.remove(); }, 4000);
    }

    function showSuccess(msg) {
        var box = document.createElement('div');
        box.style.cssText = 'position:fixed;top:20px;right:20px;z-index:9999;background:#16a354;color:white;padding:12px 18px;border-radius:10px;font-size:.82rem;font-weight:600;max-width:320px;box-shadow:0 4px 20px rgba(0,0,0,.2);';
        box.textContent = msg;
        document.body.appendChild(box);
        setTimeout(function(){ box.remove(); }, 4000);
    }
})();
</script>

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