<?php
//Developer: CORE TECH WEB DESIGN

// Check seller status before including header
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once '../include/config.php';
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header('Location: ' . $site_data['web_url'] . '/signin'); exit();
}
$seller_check = $pdo->prepare("SELECT is_seller FROM users WHERE id = ?");
$seller_check->execute([$_SESSION['user_id']]);
$seller_row = $seller_check->fetch(PDO::FETCH_ASSOC);
if (!$seller_row || !intval($seller_row['is_seller'])) {
    header('Location: ' . $site_data['web_url'] . '/user/become-seller'); exit();
}

include('header.php');
$page_title = WEB_NAME . " | Seller Dashboard";

$listing_fee = floatval($site_data['marketplace_listing_fee'] ?? 500);
$seller_balance = floatval($user['seller_balance'] ?? 0);
$msg_success = isset($_SESSION['mp_success']) ? $_SESSION['mp_success'] : '';
$msg_error = isset($_SESSION['mp_error']) ? $_SESSION['mp_error'] : '';
unset($_SESSION['mp_success'], $_SESSION['mp_error']);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'edit_listing') {
        $edit_id = intval($_POST['edit_id']);
        $platform = trim($_POST['custom_platform'] ?? '') ?: trim($_POST['platform'] ?? '');
        $pdo->prepare("UPDATE marketplace_accounts SET platform=?, username=?, followers=?, price=?, login_email=?, login_password=?, extra_info=?, profile_url=?, approval_status='pending' WHERE id=? AND seller_id=? AND status='available'")
            ->execute([$platform, trim($_POST['username']), intval($_POST['followers']), floatval($_POST['price']), trim($_POST['login_email']), trim($_POST['login_password']), trim($_POST['extra_info'] ?? ''), trim($_POST['profile_url'] ?? ''), $edit_id, $user['id']]);
        $msg_success = "Listing updated and re-submitted for review!";
    } elseif ($_POST['action'] === 'list_account') {
        $platform = trim($_POST['custom_platform'] ?? '') ?: trim($_POST['platform'] ?? '');
        $username = trim($_POST['username'] ?? '');
        $followers = intval($_POST['followers'] ?? 0);
        $price = floatval($_POST['price'] ?? 0);
        $login_email = trim($_POST['login_email'] ?? '');
        $login_password = trim($_POST['login_password'] ?? '');
        $extra_info = trim($_POST['extra_info'] ?? '');

        if (empty($platform) || empty($username) || $price <= 0 || empty($login_email) || empty($login_password)) {
            $msg_error = "Please fill all required fields.";
        } else {
            try {
                $pdo->prepare("INSERT INTO marketplace_accounts (platform, username, followers, price, login_email, login_password, extra_info, profile_url, seller_id, approval_status, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 'available')")
                    ->execute([$platform, $username, $followers, $price, $login_email, $login_password, $extra_info, trim($_POST['profile_url'] ?? ''), $user['id']]);
                $msg_success = "Account submitted for review! Awaiting admin approval.";
            } catch (Exception $e) {
                $msg_error = "Something went wrong. Please try again.";
            }
        }
    }
}

// Fetch stats
$my_listings = $pdo->prepare("SELECT * FROM marketplace_accounts WHERE seller_id = ? ORDER BY created_at DESC");
$my_listings->execute([$user['id']]);
$listings = $my_listings->fetchAll(PDO::FETCH_ASSOC);

// Fetch withdrawals
$withdrawals_stmt = $pdo->prepare("SELECT * FROM seller_withdrawals WHERE user_id = ? ORDER BY created_at DESC LIMIT 20");
$withdrawals_stmt->execute([$user['id']]);
$my_withdrawals = $withdrawals_stmt->fetchAll(PDO::FETCH_ASSOC);

$total_sold = 0; $total_earnings = 0; $total_pending = 0; $total_approved = 0; $total_rejected = 0;
foreach ($listings as $l) {
    if ($l['status'] === 'sold') { $total_sold++; $total_earnings += $l['seller_earnings']; }
    if ($l['approval_status'] === 'pending') $total_pending++;
    if ($l['approval_status'] === 'approved' && $l['status'] === 'available') $total_approved++;
    if ($l['approval_status'] === 'rejected') $total_rejected++;
}
?>
<title><?php echo $page_title; ?></title>

<!-- Messages -->
<?php if ($msg_success): ?>
<div class="bg-green-50 border border-green-200 rounded-2xl p-4 mb-5 flex items-center gap-3">
    <div class="w-9 h-9 rounded-full bg-green-100 flex items-center justify-center flex-shrink-0"><i class="fa-solid fa-check text-green-500"></i></div>
    <p class="text-sm font-bold text-green-900"><?php echo htmlspecialchars($msg_success); ?></p>
</div>
<?php endif; ?>
<?php if ($msg_error): ?>
<div class="bg-red-50 border border-red-200 rounded-2xl p-4 mb-5 flex items-center gap-3">
    <div class="w-9 h-9 rounded-full bg-red-100 flex items-center justify-center flex-shrink-0"><i class="fa-solid fa-exclamation text-red-500"></i></div>
    <p class="text-sm font-bold text-red-900"><?php echo htmlspecialchars($msg_error); ?></p>
</div>
<?php endif; ?>

<!-- Seller Balance Card -->
<section class="mb-6">
    <div class="rounded-3xl p-6 text-white relative overflow-hidden shadow-lg" style="background: linear-gradient(135deg, #4D148C 0%, #3b0f6b 50%, #2d0a54 100%);">
        <div class="absolute -right-10 -top-10 w-40 h-40 bg-white opacity-5 rounded-full"></div>
        <div class="absolute -left-6 -bottom-6 w-24 h-24 bg-white opacity-[0.03] rounded-full"></div>
        <div class="relative z-10">
            <div class="flex items-center justify-between mb-4">
                <div class="flex items-center gap-2">
                    <div class="w-8 h-8 rounded-lg bg-white/15 flex items-center justify-center">
                        <i class="fa-solid fa-wallet text-sm"></i>
                    </div>
                    <span class="text-xs font-semibold opacity-80">Seller Balance</span>
                </div>
                <span class="bg-white/15 text-[9px] font-bold px-2.5 py-1 rounded-lg uppercase tracking-wider">Verified Seller</span>
            </div>
            <h2 class="text-3xl font-bold mb-5">₦<?php echo number_format($seller_balance, 2); ?></h2>
            <div class="flex gap-3">
                <button onclick="withdrawEarnings()" class="flex-1 bg-white text-primary font-bold text-sm py-2.5 rounded-xl hover:bg-gray-100 transition-colors flex items-center justify-center gap-2 <?php echo $seller_balance <= 0 ? 'opacity-50 cursor-not-allowed' : ''; ?>" <?php echo $seller_balance <= 0 ? 'disabled' : ''; ?>>
                    <i class="fa-solid fa-money-bill-transfer"></i> Withdraw
                </button>
                <button onclick="document.getElementById('listForm').scrollIntoView({behavior:'smooth'})" class="flex-1 bg-white/20 border border-white/30 text-white font-bold text-sm py-2.5 rounded-xl hover:bg-white/30 transition-colors flex items-center justify-center gap-2">
                    <i class="fa-solid fa-plus"></i> Add Account
                </button>
            </div>
        </div>
    </div>
</section>

<!-- Stats Grid -->
<section class="mb-6">
    <div class="grid grid-cols-2 sm:grid-cols-5 gap-3">
        <div class="bg-white rounded-2xl border border-gray-100 p-4 text-center">
            <p class="text-2xl font-bold text-primary"><?php echo count($listings); ?></p>
            <p class="text-[10px] text-gray-500 uppercase font-semibold tracking-wide mt-1">Total Listed</p>
        </div>
        <div class="bg-white rounded-2xl border border-gray-100 p-4 text-center">
            <p class="text-2xl font-bold text-green-500"><?php echo $total_sold; ?></p>
            <p class="text-[10px] text-gray-500 uppercase font-semibold tracking-wide mt-1">Sold</p>
        </div>
        <div class="bg-white rounded-2xl border border-gray-100 p-4 text-center">
            <p class="text-2xl font-bold text-yellow-500"><?php echo $total_pending; ?></p>
            <p class="text-[10px] text-gray-500 uppercase font-semibold tracking-wide mt-1">Pending</p>
        </div>
        <div class="bg-white rounded-2xl border border-gray-100 p-4 text-center">
            <p class="text-2xl font-bold text-red-500"><?php echo $total_rejected; ?></p>
            <p class="text-[10px] text-gray-500 uppercase font-semibold tracking-wide mt-1">Rejected</p>
        </div>
        <div class="bg-white rounded-2xl border border-gray-100 p-4 text-center">
            <p class="text-2xl font-bold text-accent">₦<?php echo number_format($total_earnings, 0); ?></p>
            <p class="text-[10px] text-gray-500 uppercase font-semibold tracking-wide mt-1">Total Earned</p>
        </div>
    </div>
</section>

<!-- List New Account Form -->
<section class="mb-6" id="listForm">
    <div class="bg-white rounded-2xl border border-gray-100 p-5">
        <div class="flex items-center justify-between mb-4">
            <h3 class="font-bold text-sm flex items-center gap-2">
                <i class="fa-solid fa-plus-circle text-accent"></i> List New Account
            </h3>
            <span class="text-[10px] text-gray-400 bg-gray-50 px-2 py-1 rounded-lg">Fee: ₦<?php echo number_format($listing_fee, 0); ?></span>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="list_account">
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 mb-3">
                <div>
                    <label class="text-[10px] text-gray-500 uppercase font-bold tracking-wide mb-1 block">Platform *</label>
                    <select name="platform" class="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm focus:border-accent outline-none" onchange="if(this.value==='__custom__'){this.nextElementSibling.style.display='block';this.style.display='none';}">
                        <option value="Instagram">Instagram</option>
                        <option value="TikTok">TikTok</option>
                        <option value="Facebook">Facebook</option>
                        <option value="Twitter/X">Twitter/X</option>
                        <option value="YouTube">YouTube</option>
                        <option value="Snapchat">Snapchat</option>
                        <option value="Telegram">Telegram</option>
                        <option value="WhatsApp">WhatsApp</option>
                        <option value="__custom__">➕ Other...</option>
                    </select>
                    <input type="text" name="custom_platform" class="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm mt-1 focus:border-accent outline-none" placeholder="Platform name" style="display:none;">
                </div>
                <div>
                    <label class="text-[10px] text-gray-500 uppercase font-bold tracking-wide mb-1 block">Username *</label>
                    <input type="text" name="username" required class="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm focus:border-accent outline-none" placeholder="@username">
                </div>
            </div>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 mb-3">
                <div>
                    <label class="text-[10px] text-gray-500 uppercase font-bold tracking-wide mb-1 block">Followers</label>
                    <input type="number" name="followers" min="0" class="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm focus:border-accent outline-none" placeholder="0">
                </div>
                <div>
                    <label class="text-[10px] text-gray-500 uppercase font-bold tracking-wide mb-1 block">Price (₦) *</label>
                    <input type="number" name="price" min="100" step="0.01" required class="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm focus:border-accent outline-none" placeholder="5000">
                </div>
            </div>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 mb-3">
                <div>
                    <label class="text-[10px] text-gray-500 uppercase font-bold tracking-wide mb-1 block">Login Email/Phone *</label>
                    <input type="text" name="login_email" required class="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm focus:border-accent outline-none" placeholder="Login credentials">
                </div>
                <div>
                    <label class="text-[10px] text-gray-500 uppercase font-bold tracking-wide mb-1 block">Password *</label>
                    <input type="text" name="login_password" required class="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm focus:border-accent outline-none" placeholder="Account password">
                </div>
            </div>
            <div class="mb-3">
                <label class="text-[10px] text-gray-500 uppercase font-bold tracking-wide mb-1 block">Profile URL <span class="text-gray-300">(optional - for preview)</span></label>
                <input type="url" name="profile_url" class="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm focus:border-accent outline-none" placeholder="https://instagram.com/username">
            </div>
            <div class="mb-4">
                <label class="text-[10px] text-gray-500 uppercase font-bold tracking-wide mb-1 block">Extra Info <span class="text-gray-300">(optional)</span></label>
                <input type="text" name="extra_info" class="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm focus:border-accent outline-none" placeholder="2FA codes, recovery email, etc.">
            </div>
            <button type="submit" class="w-full bg-accent hover:bg-orange-700 text-white font-bold text-sm py-3 rounded-xl transition-colors flex items-center justify-center gap-2 shadow-sm">
                <i class="fa-solid fa-paper-plane"></i> Submit Account for Review
            </button>
        </form>
    </div>
</section>

<!-- My Listings -->
<?php if (!empty($listings)): ?>
<section class="mb-6">
    <!-- Tabs -->
    <div class="flex gap-2 mb-4 border-b border-gray-100 pb-2">
        <button onclick="showTab('listings')" id="tab-listings" class="seller-tab active px-4 py-2 rounded-xl text-xs font-bold transition-all">
            <i class="fa-solid fa-list"></i> My Listings (<?php echo count($listings); ?>)
        </button>
        <button onclick="showTab('withdrawals')" id="tab-withdrawals" class="seller-tab px-4 py-2 rounded-xl text-xs font-bold transition-all">
            <i class="fa-solid fa-money-bill-transfer"></i> Withdrawals (<?php echo count($my_withdrawals); ?>)
        </button>
    </div>

    <style>
    .seller-tab{background:#fff;border:1px solid rgba(0,0,0,.08);color:#64748b;}
    .seller-tab.active{background:#4D148C;border-color:#4D148C;color:#fff;}
    .seller-tab:hover:not(.active){border-color:#4D148C;color:#4D148C;}
    </style>

    <!-- Listings Tab -->
    <div id="panel-listings">
    <div class="flex items-center justify-between mb-3">
        <h3 class="font-bold text-sm text-gray-600">📋 All Listings</h3>
    </div>
    <div class="space-y-3">
        <?php foreach ($listings as $l): 
            $status_styles = [
                'pending' => 'bg-yellow-50 text-yellow-700 border-yellow-200',
                'approved' => 'bg-green-50 text-green-700 border-green-200',
                'rejected' => 'bg-red-50 text-red-700 border-red-200'
            ];
            $status_class = $status_styles[$l['approval_status']] ?? 'bg-gray-50 text-gray-700 border-gray-200';
        ?>
        <div class="bg-white rounded-2xl border border-gray-100 p-4">
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-full bg-slate-50 flex items-center justify-center">
                        <i class="fa-solid fa-user text-gray-400"></i>
                    </div>
                    <div>
                        <p class="text-sm font-bold"><?php echo htmlspecialchars($l['username']); ?></p>
                        <p class="text-[10px] text-gray-500"><?php echo htmlspecialchars($l['platform']); ?> · <?php echo number_format($l['followers']); ?> followers · ₦<?php echo number_format($l['price'], 0); ?></p>
                    </div>
                </div>
                <div class="text-right flex items-center gap-2">
                    <?php if ($l['status'] !== 'sold'): ?>
                    <button onclick='editListing(<?php echo json_encode($l); ?>)' class="text-[10px] font-bold text-primary bg-purple-50 border border-purple-200 px-2 py-1 rounded-lg hover:bg-purple-100 transition-colors">
                        <i class="fa-solid fa-pen"></i>
                    </button>
                    <?php endif; ?>
                    <span class="text-[9px] font-bold px-2 py-1 rounded-lg border <?php echo $status_class; ?> uppercase"><?php echo $l['approval_status']; ?></span>
                    <?php if ($l['status'] === 'sold'): ?>
                    <p class="text-[10px] text-green-600 font-bold ml-1"><i class="fa-solid fa-check-circle"></i></p>
                    <?php endif; ?>
                </div>
            </div>
            <?php if ($l['approval_status'] === 'rejected' && !empty($l['rejection_reason'])): ?>
            <div class="mt-2 bg-red-50 rounded-lg p-2">
                <p class="text-[10px] text-red-700"><i class="fa-solid fa-info-circle"></i> <strong>Reason:</strong> <?php echo htmlspecialchars($l['rejection_reason']); ?></p>
            </div>
            <div class="mt-2 flex gap-2">
                <a href="<?php echo $site_data['web_url']; ?>/user/ajax/marketplace-buy.php?resubmit=<?php echo $l['id']; ?>" class="text-[10px] font-bold text-primary bg-purple-50 border border-purple-200 px-3 py-1.5 rounded-lg hover:bg-purple-100 transition-colors" onclick="return confirm('Re-submit this account for review?')">
                    <i class="fa-solid fa-rotate-right"></i> Re-submit
                </a>
                <a href="<?php echo $site_data['web_url']; ?>/user/ajax/marketplace-buy.php?delete_listing=<?php echo $l['id']; ?>" class="text-[10px] font-bold text-red-500 bg-red-50 border border-red-200 px-3 py-1.5 rounded-lg hover:bg-red-100 transition-colors" onclick="return confirm('Delete this listing permanently?')">
                    <i class="fa-solid fa-trash"></i> Delete
                </a>
            </div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>

<!-- Withdrawal History -->
</div><!-- /panel-listings -->

<!-- Withdrawals Tab -->
<div id="panel-withdrawals" style="display:none;">
    <div class="flex items-center justify-between mb-3">
        <h3 class="font-bold text-sm text-gray-600">💸 Withdrawal History</h3>
    </div>
<?php if (!empty($my_withdrawals)): ?>
    <div class="space-y-3">
        <?php foreach ($my_withdrawals as $w):
            $w_colors = ['pending'=>'bg-yellow-50 text-yellow-700 border-yellow-200','completed'=>'bg-green-50 text-green-700 border-green-200','rejected'=>'bg-red-50 text-red-700 border-red-200'];
            $w_class = $w_colors[$w['status']] ?? 'bg-gray-50 text-gray-700 border-gray-200';
        ?>
        <div class="bg-white rounded-2xl border border-gray-100 p-4">
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-full bg-orange-50 flex items-center justify-center">
                        <i class="fa-solid fa-money-bill-transfer text-accent"></i>
                    </div>
                    <div>
                        <p class="text-sm font-bold">₦<?php echo number_format($w['amount'], 2); ?></p>
                        <p class="text-[10px] text-gray-500"><?php echo htmlspecialchars($w['bank_name']); ?> · <?php echo htmlspecialchars($w['account_number']); ?> · <?php echo date('M d, Y', strtotime($w['created_at'])); ?></p>
                    </div>
                </div>
                <div class="text-right">
                    <span class="text-[9px] font-bold px-2 py-1 rounded-lg border <?php echo $w_class; ?> uppercase"><?php echo $w['status']; ?></span>
                    <p class="text-[9px] text-gray-400 mt-1">Fee: ₦<?php echo number_format($w['fee'], 0); ?></p>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
<?php else: ?>
    <div class="bg-white rounded-2xl border border-gray-100 p-8 text-center">
        <i class="fa-solid fa-receipt text-2xl text-gray-300 mb-2"></i>
        <p class="text-sm text-gray-500">No withdrawals yet</p>
    </div>
<?php endif; ?>
</div><!-- /panel-withdrawals -->

</section>
<?php endif; ?>

<script>
function showTab(tab) {
    document.getElementById('panel-listings').style.display = tab === 'listings' ? '' : 'none';
    document.getElementById('panel-withdrawals').style.display = tab === 'withdrawals' ? '' : 'none';
    document.querySelectorAll('.seller-tab').forEach(function(t) { t.classList.remove('active'); });
    document.getElementById('tab-' + tab).classList.add('active');
}

function editListing(acc) {
    Swal.fire({
        title: '<span style="font-size:16px;font-weight:700;">Edit Listing</span>',
        html: '<form id="editListingForm" method="POST" style="text-align:left;font-size:13px;">' +
              '<input type="hidden" name="action" value="edit_listing">' +
              '<input type="hidden" name="edit_id" value="' + acc.id + '">' +
              '<div style="margin-bottom:8px;"><label style="font-size:10px;font-weight:700;text-transform:uppercase;color:#64748b;">Platform</label><input name="platform" value="' + (acc.platform||'') + '" class="swal2-input" style="font-size:13px;margin:4px 0;"></div>' +
              '<div style="margin-bottom:8px;"><label style="font-size:10px;font-weight:700;text-transform:uppercase;color:#64748b;">Username</label><input name="username" value="' + (acc.username||'') + '" class="swal2-input" style="font-size:13px;margin:4px 0;"></div>' +
              '<div style="margin-bottom:8px;"><label style="font-size:10px;font-weight:700;text-transform:uppercase;color:#64748b;">Followers</label><input name="followers" type="number" value="' + (acc.followers||0) + '" class="swal2-input" style="font-size:13px;margin:4px 0;"></div>' +
              '<div style="margin-bottom:8px;"><label style="font-size:10px;font-weight:700;text-transform:uppercase;color:#64748b;">Price (₦)</label><input name="price" type="number" step="0.01" value="' + (acc.price||0) + '" class="swal2-input" style="font-size:13px;margin:4px 0;"></div>' +
              '<div style="margin-bottom:8px;"><label style="font-size:10px;font-weight:700;text-transform:uppercase;color:#64748b;">Login Email/Phone</label><input name="login_email" value="' + (acc.login_email||'') + '" class="swal2-input" style="font-size:13px;margin:4px 0;"></div>' +
              '<div style="margin-bottom:8px;"><label style="font-size:10px;font-weight:700;text-transform:uppercase;color:#64748b;">Password</label><input name="login_password" value="' + (acc.login_password||'') + '" class="swal2-input" style="font-size:13px;margin:4px 0;"></div>' +
              '<div style="margin-bottom:8px;"><label style="font-size:10px;font-weight:700;text-transform:uppercase;color:#64748b;">Profile URL</label><input name="profile_url" value="' + (acc.profile_url||'') + '" class="swal2-input" style="font-size:13px;margin:4px 0;"></div>' +
              '<div style="margin-bottom:8px;"><label style="font-size:10px;font-weight:700;text-transform:uppercase;color:#64748b;">Extra Info</label><input name="extra_info" value="' + (acc.extra_info||'') + '" class="swal2-input" style="font-size:13px;margin:4px 0;"></div>' +
              '<p style="font-size:10px;color:#64748b;margin-top:8px;"><i class="fa-solid fa-info-circle"></i> Editing will re-submit for admin review.</p>' +
              '</form>',
        showCancelButton: true,
        confirmButtonColor: '#4D148C',
        confirmButtonText: '<i class="fa-solid fa-save"></i> Save Changes',
        cancelButtonText: 'Cancel',
        preConfirm: function() {
            document.getElementById('editListingForm').submit();
            return false;
        }
    });
}

function withdrawEarnings() {
    <?php if ($seller_balance <= 0): ?>
    Swal.fire({icon:'info',title:'No Balance',text:'You have no seller earnings to withdraw yet.',confirmButtonColor:'#4D148C'});
    return;
    <?php endif; ?>
    <?php
    $bank_stmt = $pdo->prepare("SELECT bank_name, account_number, account_name FROM seller_applications WHERE user_id = ? AND status = 'approved' ORDER BY id DESC LIMIT 1");
    $bank_stmt->execute([$user['id']]);
    $bank_info = $bank_stmt->fetch(PDO::FETCH_ASSOC);
    $withdrawal_fee = floatval($site_data['marketplace_listing_fee'] ?? 500);
    $max_withdraw = $seller_balance - $withdrawal_fee;
    ?>
    Swal.fire({
        title: '',
        html: '<div style="text-align:left;">' +
              '<div style="text-align:center;margin-bottom:16px;">' +
              '<div style="width:48px;height:48px;border-radius:14px;background:linear-gradient(135deg,#4D148C,#6b23c2);display:inline-flex;align-items:center;justify-content:center;margin-bottom:10px;">' +
              '<i class="fa-solid fa-money-bill-transfer" style="color:white;font-size:18px;"></i></div>' +
              '<h3 style="font-size:16px;font-weight:800;color:#1e293b;margin:0;">Withdraw Earnings</h3>' +
              '<p style="font-size:11px;color:#64748b;margin-top:4px;">Transfer your seller balance</p>' +
              '</div>' +
              '<div style="background:linear-gradient(135deg,#4D148C,#3b0f6b);border-radius:14px;padding:16px;margin-bottom:16px;text-align:center;">' +
              '<p style="font-size:10px;color:rgba(255,255,255,.6);text-transform:uppercase;letter-spacing:1px;font-weight:600;margin-bottom:4px;">Available Balance</p>' +
              '<p style="font-size:28px;font-weight:800;color:white;margin:0;">₦<?php echo number_format($seller_balance, 2); ?></p>' +
              '<div style="display:flex;justify-content:center;gap:12px;margin-top:8px;">' +
              '<span style="font-size:10px;color:rgba(255,255,255,.5);"><i class="fa-solid fa-receipt"></i> Fee: ₦<?php echo number_format($withdrawal_fee, 2); ?></span>' +
              '<span style="font-size:10px;color:rgba(255,255,255,.5);"><i class="fa-solid fa-arrow-up"></i> Max: ₦<?php echo number_format(max(0, $max_withdraw), 2); ?></span>' +
              '</div></div>' +
              '<div style="margin-bottom:12px;">' +
              '<label style="font-size:11px;font-weight:700;color:#374151;display:block;margin-bottom:4px;">Amount (₦)</label>' +
              '<input type="number" id="withdraw_amount" min="100" max="<?php echo max(0, $max_withdraw); ?>" step="0.01" value="<?php echo max(0, $max_withdraw); ?>" style="width:100%;padding:10px 14px;border:1.5px solid #e2e8f0;border-radius:10px;font-size:15px;font-weight:700;outline:none;transition:border .2s;" onfocus="this.style.borderColor=\'#4D148C\'" onblur="this.style.borderColor=\'#e2e8f0\'">' +
              '</div>' +
              '<div style="margin-bottom:10px;">' +
              '<label style="font-size:11px;font-weight:700;color:#374151;display:block;margin-bottom:4px;">Bank Name</label>' +
              '<input type="text" id="withdraw_bank" value="<?php echo htmlspecialchars($bank_info['bank_name'] ?? ''); ?>" style="width:100%;padding:10px 14px;border:1.5px solid #e2e8f0;border-radius:10px;font-size:13px;outline:none;transition:border .2s;" onfocus="this.style.borderColor=\'#4D148C\'" onblur="this.style.borderColor=\'#e2e8f0\'" placeholder="e.g. GTBank">' +
              '</div>' +
              '<div style="margin-bottom:10px;">' +
              '<label style="font-size:11px;font-weight:700;color:#374151;display:block;margin-bottom:4px;">Account Number</label>' +
              '<input type="text" id="withdraw_acct" value="<?php echo htmlspecialchars($bank_info['account_number'] ?? ''); ?>" style="width:100%;padding:10px 14px;border:1.5px solid #e2e8f0;border-radius:10px;font-size:13px;outline:none;transition:border .2s;" onfocus="this.style.borderColor=\'#4D148C\'" onblur="this.style.borderColor=\'#e2e8f0\'" placeholder="0123456789">' +
              '</div>' +
              '<div style="margin-bottom:14px;">' +
              '<label style="font-size:11px;font-weight:700;color:#374151;display:block;margin-bottom:4px;">Account Name</label>' +
              '<input type="text" id="withdraw_name" value="<?php echo htmlspecialchars($bank_info['account_name'] ?? ''); ?>" style="width:100%;padding:10px 14px;border:1.5px solid #e2e8f0;border-radius:10px;font-size:13px;outline:none;transition:border .2s;" onfocus="this.style.borderColor=\'#4D148C\'" onblur="this.style.borderColor=\'#e2e8f0\'" placeholder="John Doe">' +
              '</div>' +
              '<div style="display:flex;gap:10px;">' +
              '<button onclick="submitWithdraw(\'bank\')" style="flex:1;padding:12px;border:none;border-radius:12px;background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;font-size:12px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:6px;transition:opacity .2s;" onmouseover="this.style.opacity=\'0.9\'" onmouseout="this.style.opacity=\'1\'">' +
              '<i class="fa-solid fa-building-columns"></i> To Bank</button>' +
              '<button onclick="submitWithdraw(\'wallet\')" style="flex:1;padding:12px;border:2px solid #4D148C;border-radius:12px;background:white;color:#4D148C;font-size:12px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:6px;transition:background .2s;" onmouseover="this.style.background=\'#f5f3ff\'" onmouseout="this.style.background=\'white\'">' +
              '<i class="fa-solid fa-wallet"></i> To Wallet</button>' +
              '</div>' +
              '</div>',
        showConfirmButton: false,
        showCancelButton: true,
        cancelButtonText: '<i class="fa-solid fa-xmark"></i> Close',
        cancelButtonColor: '#94a3b8',
        customClass: { popup: 'rounded-2xl' }
    });
}

function submitWithdraw(type) {
    var amt = document.getElementById('withdraw_amount').value;
    if (!amt || amt <= 0) { Swal.showValidationMessage('Enter a valid amount'); return; }
    
    if (type === 'bank') {
        var bank = document.getElementById('withdraw_bank').value;
        var acct = document.getElementById('withdraw_acct').value;
        var name = document.getElementById('withdraw_name').value;
        if (!bank || !acct || !name) { 
            Swal.fire({icon:'error',title:'Missing Info',text:'Please fill all bank details.',confirmButtonColor:'#4D148C'}); 
            return; 
        }
        window.location.href = '<?php echo $site_data['web_url']; ?>/user/ajax/marketplace-buy.php?withdraw=bank&amount=' + amt + '&bank=' + encodeURIComponent(bank) + '&acct=' + encodeURIComponent(acct) + '&name=' + encodeURIComponent(name);
    } else {
        window.location.href = '<?php echo $site_data['web_url']; ?>/user/ajax/marketplace-buy.php?withdraw=wallet&amount=' + amt;
    }
}
</script>

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