<?php
include('header.php');
$page_title  = WEB_NAME . " | Withdraw";
$page_title2 = "Withdraw";
$current_page = 'withdraw';

$min_withdraw = floatval($site_data['withdraw_minimum'] ?? 500);
$withdraw_fee = floatval($site_data['withdraw_fee'] ?? 50);
$user_balance = (float)$user['main_balance'];

// Check KYC status
$kyc_status = $user['kyc_status'] ?? 'none';
if ($kyc_status !== 'approved') {
    // Redirect to KYC page
    echo '<title>' . htmlspecialchars($page_title) . '</title>';
    echo '<div class="max-w-lg mx-auto" style="padding-top:20px;">';
    echo '<div style="background:rgba(245,158,11,.06);border:1px solid rgba(245,158,11,.2);border-radius:16px;padding:30px;text-align:center;">';
    echo '<div style="width:56px;height:56px;border-radius:50%;background:rgba(245,158,11,.12);display:flex;align-items:center;justify-content:center;margin:0 auto 14px;"><i class="fas fa-shield-halved" style="font-size:1.6rem;color:#d97706;"></i></div>';
    echo '<h3 style="font-weight:700;font-size:1rem;color:#d97706;margin-bottom:8px;">KYC Required</h3>';
    echo '<p style="font-size:.82rem;color:var(--text-muted);margin-bottom:16px;">You need to complete identity verification before you can withdraw funds.</p>';
    echo '<a href="kyc" style="display:inline-flex;align-items:center;gap:8px;padding:11px 22px;background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;font-weight:700;font-size:.82rem;border-radius:10px;text-decoration:none;"><i class="fas fa-id-card"></i>Complete KYC</a>';
    echo '</div></div>';
    include('footer.php');
    exit();
}
?>
<title><?php echo htmlspecialchars($page_title); ?></title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<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}
.wd-hero{background:linear-gradient(145deg,#2d0a5e 0%,#3b0f6b 40%,#4D148C 80%,#4D148C 100%);border:1px solid rgba(245,158,11,.15);border-radius:20px;padding:20px;position:relative;overflow:hidden;margin-bottom:14px}
.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}
.wd-input{width:100%;padding:12px 14px;background:var(--btn-bg);color:var(--hd-title);border-radius:10px;border:1.5px solid var(--card-border);outline:none;font-size:.85rem;transition:border-color .2s}
.wd-input:focus{border-color:#6b23c2}
.wd-btn{width:100%;background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;font-weight:700;padding:13px;border-radius:10px;border:none;cursor:pointer;font-size:.88rem;display:flex;align-items:center;justify-content:center;gap:8px;box-shadow:0 4px 14px rgba(77,20,140,.28);transition:all .2s}
.wd-btn:disabled{opacity:.5;cursor:not-allowed}
.verified-badge{background:rgba(16,185,129,.08);border:1px solid rgba(16,185,129,.2);border-radius:10px;padding:12px;display:flex;align-items:center;gap:10px}
</style>

<div class="max-w-lg mx-auto">

<!-- Hero -->
<div class="wd-hero anim anim-1">
    <div style="position:absolute;width:140px;height:140px;border-radius:50%;filter:blur(50px);background:radial-gradient(circle,rgba(77,20,140,.2),transparent);top:-30px;right:-30px;pointer-events:none;"></div>
    <div style="position:relative;z-index:1;display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:14px;">
        <div>
            <h2 style="font-size:1.1rem;font-weight:800;color:white;margin-bottom:4px;display:flex;align-items:center;gap:8px;">
                <i class="fas fa-money-bill-transfer text-emerald-300 text-base"></i>Withdraw Funds
            </h2>
            <p style="color:rgba(255,255,255,.55);font-size:.78rem;">Transfer money from your wallet to any Nigerian bank account.</p>
        </div>
        <div style="background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.15);border-radius:10px;padding:10px 16px;text-align:center;">
            <p style="font-size:.6rem;color:rgba(255,255,255,.55);font-weight:700;text-transform:uppercase;letter-spacing:.06em;">Balance</p>
            <p id="wdBalance" style="font-weight:800;color:white;font-size:.95rem;font-family:monospace;">&#8358;<?php echo number_format($user_balance, 2); ?></p>
        </div>
    </div>
</div>

<!-- Info -->
<div class="anim anim-2" style="background:rgba(59,130,246,.06);border:1px solid rgba(59,130,246,.15);border-radius:12px;padding:12px 14px;margin-bottom:14px;display:flex;align-items:center;gap:10px;">
    <i class="fas fa-info-circle" style="color:#2563eb;"></i>
    <p style="font-size:.75rem;color:var(--text-muted);">Minimum: <strong>&#8358;<?php echo number_format($min_withdraw, 2); ?></strong> &bull; Fee: <strong>&#8358;<?php echo number_format($withdraw_fee, 2); ?></strong> per withdrawal</p>
</div>

<!-- Withdrawal Form -->
<div class="wd-card anim anim-3">
    <div style="display:flex;flex-direction:column;gap:16px;">

        <!-- Bank Select -->
        <div>
            <label style="display:block;font-size:.8rem;font-weight:600;color:var(--text-primary);margin-bottom:6px;">Select Bank</label>
            <select id="bankSelect" class="wd-input" onchange="resetVerification()">
                <option value="">Loading banks...</option>
            </select>
        </div>

        <!-- Account Number -->
        <div>
            <label style="display:block;font-size:.8rem;font-weight:600;color:var(--text-primary);margin-bottom:6px;">Account Number</label>
            <div style="display:flex;gap:8px;">
                <input type="text" id="accountNumber" class="wd-input" placeholder="0123456789" maxlength="10" oninput="resetVerification()">
                <button id="verifyBtn" onclick="verifyAccount()" style="padding:12px 18px;background:rgba(77,20,140,.08);border:1.5px solid rgba(77,20,140,.2);border-radius:10px;color:#4D148C;font-weight:700;font-size:.78rem;cursor:pointer;white-space:nowrap;">
                    Verify
                </button>
            </div>
        </div>

        <!-- Verified Account Name -->
        <div id="verifiedSection" style="display:none;">
            <div class="verified-badge">
                <i class="fas fa-circle-check" style="color:#059669;font-size:1.2rem;"></i>
                <div>
                    <p style="font-size:.68rem;color:#059669;font-weight:600;">Account Verified</p>
                    <p id="verifiedName" style="font-weight:700;font-size:.88rem;color:var(--text-primary);"></p>
                </div>
            </div>
        </div>

        <!-- Amount -->
        <div>
            <label style="display:block;font-size:.8rem;font-weight:600;color:var(--text-primary);margin-bottom:6px;">Amount (&#8358;)</label>
            <input type="number" id="withdrawAmount" class="wd-input" placeholder="Enter amount" min="<?php echo $min_withdraw; ?>" step="1">
            <p style="font-size:.72rem;color:var(--text-muted);margin-top:4px;">You'll receive: <strong id="receiveAmount">&#8358;0.00</strong> (after &#8358;<?php echo number_format($withdraw_fee, 2); ?> fee)</p>
        </div>

        <!-- Submit -->
        <button id="withdrawBtn" class="wd-btn" onclick="processWithdraw()" disabled>
            <i class="fas fa-paper-plane"></i> Withdraw Now
        </button>
    </div>
</div>

</div>

<script>
const MIN_WITHDRAW = <?php echo $min_withdraw; ?>;
const WITHDRAW_FEE = <?php echo $withdraw_fee; ?>;
let verifiedAccountName = '';
let banksList = [];

// Load banks on page load
$(document).ready(function() {
    $.ajax({
        url: 'ajax/withdraw.php',
        type: 'POST',
        data: { action: 'get_banks' },
        dataType: 'json',
        success: function(res) {
            if (res.status === '1' && res.banks) {
                banksList = res.banks;
                let html = '<option value="">Choose your bank</option>';
                res.banks.forEach(function(b) {
                    html += '<option value="' + b.code + '">' + b.name + '</option>';
                });
                $('#bankSelect').html(html);
            } else {
                $('#bankSelect').html('<option value="">Failed to load banks</option>');
            }
        },
        error: function() {
            $('#bankSelect').html('<option value="">Failed to load banks</option>');
        }
    });
});

// Amount input
$('#withdrawAmount').on('input', function() {
    const amt = parseFloat($(this).val()) || 0;
    const receive = Math.max(0, amt);
    $('#receiveAmount').text('\u20A6' + receive.toLocaleString('en-NG', {minimumFractionDigits:2}));
    checkReady();
});

function resetVerification() {
    verifiedAccountName = '';
    $('#verifiedSection').hide();
    $('#withdrawBtn').prop('disabled', true);
}

function verifyAccount() {
    const acct = $('#accountNumber').val().trim();
    const bank = $('#bankSelect').val();

    if (!acct || acct.length < 10) { alert('Enter a valid 10-digit account number.'); return; }
    if (!bank) { alert('Please select a bank.'); return; }

    const btn = $('#verifyBtn');
    btn.prop('disabled', true).text('Verifying...');

    $.ajax({
        url: 'ajax/withdraw.php',
        type: 'POST',
        data: { action: 'verify_account', account_number: acct, bank_code: bank },
        dataType: 'json',
        success: function(res) {
            btn.prop('disabled', false).text('Verify');
            if (res.status === '1' && res.account_name) {
                verifiedAccountName = res.account_name;
                $('#verifiedName').text(res.account_name);
                $('#verifiedSection').slideDown(200);
                checkReady();
            } else {
                alert(res.msg || 'Could not verify account.');
            }
        },
        error: function() {
            btn.prop('disabled', false).text('Verify');
            alert('Verification failed. Please try again.');
        }
    });
}

function checkReady() {
    const amt = parseFloat($('#withdrawAmount').val()) || 0;
    const ready = verifiedAccountName && amt >= MIN_WITHDRAW;
    $('#withdrawBtn').prop('disabled', !ready);
}

function processWithdraw() {
    const amount = parseFloat($('#withdrawAmount').val()) || 0;
    const bank   = $('#bankSelect').val();
    const acct   = $('#accountNumber').val().trim();

    if (!verifiedAccountName || amount < MIN_WITHDRAW || !bank || !acct) return;

    if (!confirm('Withdraw \u20A6' + amount.toLocaleString() + ' to ' + verifiedAccountName + '?\n\nFee: \u20A6' + WITHDRAW_FEE.toLocaleString() + '\nTotal deducted: \u20A6' + (amount + WITHDRAW_FEE).toLocaleString())) return;

    const btn = $('#withdrawBtn');
    btn.prop('disabled', true).html('<span style="display:inline-block;width:14px;height:14px;border:2px solid white;border-top-color:transparent;border-radius:50%;animation:spin 1s linear infinite;"></span> Processing...');

    $.ajax({
        url: 'ajax/withdraw.php',
        type: 'POST',
        data: { action: 'withdraw', amount: amount, account_number: acct, bank_code: bank, account_name: verifiedAccountName },
        dataType: 'json',
        success: function(res) {
            btn.prop('disabled', false).html('<i class="fas fa-paper-plane"></i> Withdraw Now');
            if (res.status === '1') {
                if (res.new_balance) {
                    $('#wdBalance').text('\u20A6' + parseFloat(res.new_balance.replace(/,/g,'')).toLocaleString('en-NG',{minimumFractionDigits:2}));
                }
                // Reset form
                $('#withdrawAmount').val('');
                resetVerification();
                // Show success popup
                showWithdrawSuccess(amount);
            } else {
                alert(res.msg.replace(/&#8358;/g, '\u20A6') || 'Withdrawal failed.');
            }
        },
        error: function() {
            btn.prop('disabled', false).html('<i class="fas fa-paper-plane"></i> Withdraw Now');
            alert('An error occurred. Please try again.');
        }
    });
}

function showWithdrawSuccess(amount) {
    var overlay = document.createElement('div');
    overlay.id = 'withdrawSuccessOverlay';
    overlay.style.cssText = 'position:fixed;inset:0;z-index:9999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.6);backdrop-filter:blur(6px);padding:20px;animation:fadeIn .3s ease;';
    overlay.innerHTML = `
        <div style="background:white;border-radius:24px;padding:32px 24px;max-width:340px;width:100%;text-align:center;box-shadow:0 24px 60px rgba(0,0,0,.25);animation:popIn .4s ease;">
            <div style="width:72px;height:72px;border-radius:50%;background:linear-gradient(135deg,#059669,#10b981);display:flex;align-items:center;justify-content:center;margin:0 auto 18px;box-shadow:0 8px 24px rgba(16,185,129,.3);">
                <i class="fas fa-check" style="color:white;font-size:2rem;"></i>
            </div>
            <h3 style="font-weight:800;font-size:1.2rem;color:#1e293b;margin-bottom:8px;">Withdrawal Successful!</h3>
            <p style="font-size:.88rem;color:#64748b;margin-bottom:6px;">Your withdrawal of</p>
            <p style="font-size:1.6rem;font-weight:800;color:#059669;font-family:monospace;margin-bottom:12px;">\u20A6${amount.toLocaleString('en-NG',{minimumFractionDigits:2})}</p>
            <p style="font-size:.78rem;color:#94a3b8;margin-bottom:20px;line-height:1.5;">has been initiated and will arrive in your bank account shortly.</p>
            <div style="display:flex;gap:10px;">
                <a href="withdrawal-history" style="flex:1;padding:12px;background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;font-weight:700;font-size:.8rem;border-radius:10px;text-decoration:none;display:flex;align-items:center;justify-content:center;gap:6px;">
                    <i class="fas fa-receipt"></i> View History
                </a>
                <button onclick="document.getElementById('withdrawSuccessOverlay').remove()" style="flex:1;padding:12px;background:#f1f5f9;color:#475569;font-weight:700;font-size:.8rem;border-radius:10px;border:none;cursor:pointer;">
                    Done
                </button>
            </div>
        </div>
    `;
    document.body.appendChild(overlay);
    overlay.addEventListener('click', function(e) { if (e.target === overlay) overlay.remove(); });
}
</script>

<style>
@keyframes fadeIn{from{opacity:0}to{opacity:1}}
@keyframes popIn{from{opacity:0;transform:scale(.85)}to{opacity:1;transform:scale(1)}}
</style>

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