<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
$pageTitle = 'Request Withdrawal';
include 'side.php';

$conn = getConnection();

// ============================================================================
// 1. GET USER'S COUNTRY SETTINGS
// ============================================================================
$userCountry = $userData['country'] ?? 'Kenya';
$stmt = $conn->prepare("SELECT * FROM countries WHERE name = ? AND status = 'active'");
$stmt->bind_param("s", $userCountry);
$stmt->execute();
$countrySettings = $stmt->get_result()->fetch_assoc();

if (!$countrySettings) {
    $stmt = $conn->prepare("SELECT * FROM countries WHERE name = 'Kenya'");
    $stmt->execute();
    $countrySettings = $stmt->get_result()->fetch_assoc();
    if (!$countrySettings) {
        $countrySettings = [
            'currency_symbol' => 'Ksh',
            'exchange_rate' => 1,
            'min_withdrawal' => 100,
            'withdrawal_fee' => 10,
            'id' => 0
        ];
    }
}

$currencySymbol = $countrySettings['currency_symbol'] ?? 'Ksh';
$minWithdrawal = $countrySettings['min_withdrawal'] ?? 100;
$flatWithdrawalFee = $countrySettings['withdrawal_fee'] ?? 10;

// ============================================================================
// 2. GET TIERED WITHDRAWAL FEES
// ============================================================================
$tieredFees = [];
if (isset($countrySettings['id']) && $countrySettings['id'] > 0) {
    $stmt = $conn->prepare("SELECT * FROM withdrawal_fee_tiers WHERE country_id = ? ORDER BY min_amount ASC");
    $stmt->bind_param("i", $countrySettings['id']);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($tier = $result->fetch_assoc()) {
        $tieredFees[] = $tier;
    }
}

// ============================================================================
// 3. GET ENABLED WALLET TYPES
// ============================================================================
$walletSettingsQuery = $conn->query("SELECT wallet_type FROM wallet_withdrawal_settings WHERE status = 'enabled'");
$enabledWalletTypes = [];
if ($walletSettingsQuery && $walletSettingsQuery->num_rows > 0) {
    while ($setting = $walletSettingsQuery->fetch_assoc()) {
        $enabledWalletTypes[] = $setting['wallet_type'];
    }
} else {
    // Default fallback
    $enabledWalletTypes = [
        'referral_wallet', 'bonus_wallet', 'video_wallet', 'trivia_wallet', 
        'survey_wallet', 'ads_wallet', 'spin_wallet', 'blog_wallet', 
        'meme_wallet', 'chat_wallet', 'transcription_wallet'
    ];
}

// Wallet Mapping & Info
$walletTypeMapping = [
    'referral_wallet' => 'referral', 'bonus_wallet' => 'bonus', 'video_wallet' => 'video',
    'trivia_wallet' => 'trivia', 'survey_wallet' => 'task', 'ads_wallet' => 'ads',
    'spin_wallet' => 'task', 'blog_wallet' => 'blog', 'meme_wallet' => 'task',
    'chat_wallet' => 'task', 'transcription_wallet' => 'task', 'main_wallet' => 'referral'
];

$walletInfo = [
    'referral_wallet' => ['name' => 'Main Wallet', 'icon' => 'fa-share-alt', 'color' => '#5B77F5'],
    'bonus_wallet' => ['name' => 'Bonus Wallet', 'icon' => 'fa-gift', 'color' => '#10b981'],
    'video_wallet' => ['name' => 'Video Wallet', 'icon' => 'fa-video', 'color' => '#f59e0b'],
    'trivia_wallet' => ['name' => 'Trivia Wallet', 'icon' => 'fa-question-circle', 'color' => '#ec4899'],
    'survey_wallet' => ['name' => 'Survey Wallet', 'icon' => 'fa-poll', 'color' => '#06b6d4'],
    'ads_wallet' => ['name' => 'Ads Wallet', 'icon' => 'fa-ad', 'color' => '#8b5cf6'],
    'spin_wallet' => ['name' => 'Spin Wallet', 'icon' => 'fa-spinner', 'color' => '#f59e0b'],
    'blog_wallet' => ['name' => 'Blog Wallet', 'icon' => 'fa-blog', 'color' => '#f97316'],
    'meme_wallet' => ['name' => 'Meme Wallet', 'icon' => 'fa-images', 'color' => '#e11d48'],
    'chat_wallet' => ['name' => 'Chat Wallet', 'icon' => 'fa-comments', 'color' => '#8b5cf6'],
    'transcription_wallet' => ['name' => 'Transcription Wallet', 'icon' => 'fa-keyboard', 'color' => '#10b981']
];

// ============================================================================
// 4. GET BALANCES & BUILD LIST
// ============================================================================
$stmt = $conn->prepare("SELECT * FROM wallets WHERE user_id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$walletResult = $stmt->get_result();
$userWallet = $walletResult->fetch_assoc();

$availableWallets = [];
$referralWalletIndex = -1;

if ($userWallet) {
    $index = 0;
    foreach ($enabledWalletTypes as $walletType) {
        if (isset($userWallet[$walletType]) && isset($walletInfo[$walletType])) {
            $balance = floatval($userWallet[$walletType]);
            if ($balance >= $minWithdrawal) {
                $availableWallets[] = [
                    'type' => $walletType,
                    'name' => $walletInfo[$walletType]['name'],
                    'icon' => $walletInfo[$walletType]['icon'],
                    'color' => $walletInfo[$walletType]['color'],
                    'balance' => $balance
                ];
                if ($walletType === 'referral_wallet') {
                    $referralWalletIndex = $index;
                }
                $index++;
            }
        }
    }
}

// ============================================================================
// 5. PROCESS WITHDRAWAL REQUEST
// ============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $walletColumn = sanitize($_POST['wallet_type']);
    $amount = floatval($_POST['amount']);
    $phoneNumber = sanitize($_POST['phone_number']);
    
    // Validations
    if (!in_array($walletColumn, $enabledWalletTypes)) { setFlash('error', 'Wallet disabled.'); header('Location: ' . $_SERVER['PHP_SELF']); exit; }
    if (!isset($walletTypeMapping[$walletColumn])) { setFlash('error', 'Invalid wallet type.'); header('Location: ' . $_SERVER['PHP_SELF']); exit; }
    $walletTypeEnum = $walletTypeMapping[$walletColumn];
    
    if ($amount < $minWithdrawal) { setFlash('error', 'Minimum withdrawal is ' . $currencySymbol . ' ' . number_format($minWithdrawal, 2)); header('Location: ' . $_SERVER['PHP_SELF']); exit; }
    
    $currentBalance = floatval($userWallet[$walletColumn] ?? 0);
    if ($currentBalance < $amount) { setFlash('error', 'Insufficient balance.'); header('Location: ' . $_SERVER['PHP_SELF']); exit; }
    
    // Fee Calculation
    $fee = $flatWithdrawalFee;
    foreach ($tieredFees as $tier) {
        if ($amount >= $tier['min_amount'] && $amount <= $tier['max_amount']) {
            $fee = $tier['fee'];
            break;
        }
    }
    
    $netAmount = $amount - $fee;
    if ($netAmount <= 0) { setFlash('error', 'Amount too low after fees.'); header('Location: ' . $_SERVER['PHP_SELF']); exit; }
    
    // Transaction
    $conn->begin_transaction();
    try {
        // Update Wallet Balance
        $stmt = $conn->prepare("UPDATE wallets SET $walletColumn = ?, balance = balance - ? WHERE user_id = ?");
        $newBalance = $currentBalance - $amount;
        $stmt->bind_param("ddi", $newBalance, $amount, $userId);
        if (!$stmt->execute()) throw new Exception('Failed to update wallet balance');
        
        // Insert Withdrawal Record
        $stmt = $conn->prepare("INSERT INTO withdrawals (user_id, wallet_type, amount, fee, net_amount, phone_number, status, country, requested_at) VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, NOW())");
        $stmt->bind_param("isdddss", $userId, $walletTypeEnum, $amount, $fee, $netAmount, $phoneNumber, $userCountry);
        if (!$stmt->execute()) throw new Exception('Failed to create withdrawal request');
        $withdrawalId = $conn->insert_id;
        
        // Log Transaction History
        $walletName = $walletInfo[$walletColumn]['name'];
        $description = "Withdrawal request from {$walletName}";
        $reference = "WD-" . $withdrawalId;
        $stmt = $conn->prepare("INSERT INTO transactions (user_id, wallet_type, amount, type, description, reference, status, created_at) VALUES (?, ?, ?, 'debit', ?, ?, 'completed', NOW())");
        $stmt->bind_param("isdss", $userId, $walletTypeEnum, $amount, $description, $reference);
        $stmt->execute();
        
        $conn->commit();
        
        // Success Message (Used by the Toast below)
        setFlash('success', "Withdrawal of $currencySymbol " . number_format($amount) . " successfully requested!");
        
    } catch (Exception $e) {
        $conn->rollback();
        setFlash('error', 'Failed to process withdrawal.');
    }
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}
?>

<style>
/* Core Variables */
:root { --withdrawal-gap: 12px; --card-padding: 20px; --card-radius: 12px; }

/* Page Layout */
.withdrawal-container { padding: 8px; max-width: 1200px; margin: 0 auto; }
.page-title { font-size: 28px; font-weight: 900; background: linear-gradient(135deg, var(--theme-color) 0%, #ec4899 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin: 0; }

/* Modern Card */
.modern-card { background: var(--card-bg); border: 1px solid var(--border-color); border-radius: var(--card-radius); padding: var(--card-padding); margin-bottom: 16px; transition: all 0.3s ease; }
.card-header { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; padding-bottom: 12px; border-bottom: 1px solid var(--border-color); }
.card-icon { width: 40px; height: 40px; background: linear-gradient(135deg, var(--theme-color) 0%, #ec4899 100%); border-radius: 10px; display: flex; align-items: center; justify-content: center; color: white; font-size: 20px; }
.card-title { font-size: 20px; font-weight: 800; color: var(--text-primary); flex: 1; }

/* Wallet Selector */
.wallet-selector { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; margin-bottom: 20px; }
.wallet-option { background: var(--darker-bg); border: 2px solid var(--border-color); border-radius: 12px; padding: 16px; cursor: pointer; transition: all 0.3s ease; position: relative; }
.wallet-option input[type="radio"] { position: absolute; opacity: 0; }
.wallet-option.selected { border-color: var(--theme-color); background: rgba(var(--theme-rgb), 0.05); }
.wallet-option:hover { transform: translateY(-2px); border-color: var(--theme-color); }
.wallet-option-icon { width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: white; font-size: 20px; margin-bottom: 12px; }
.wallet-option-name { font-size: 14px; font-weight: 700; color: var(--text-primary); margin-bottom: 4px; }
.wallet-option-balance { font-size: 18px; font-weight: 900; background: linear-gradient(135deg, var(--theme-color), #ec4899); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }

/* Form Elements */
.form-group { margin-bottom: 16px; }
.form-label { display: block; font-size: 13px; font-weight: 600; color: var(--text-primary); margin-bottom: 8px; }
.form-control { width: 100%; padding: 12px; background: var(--darker-bg); border: 1px solid var(--border-color); border-radius: 8px; color: var(--text-primary); font-size: 14px; transition: all 0.3s ease; }
.form-control:focus { outline: none; border-color: var(--theme-color); }

/* Fee Calculator */
.fee-calculator { background: var(--darker-bg); border: 1px solid var(--border-color); border-radius: 8px; padding: 12px; margin-top: 8px; display: none; }
.fee-calculator.active { display: block; }
.fee-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid var(--border-color); }
.fee-row:last-child { border-bottom: none; font-weight: 800; color: var(--theme-color); font-size: 16px; }

/* Buttons */
.btn { display: inline-flex; align-items: center; gap: 8px; padding: 12px 24px; background: linear-gradient(135deg, var(--theme-color) 0%, #ec4899 100%); color: white; border: none; border-radius: 8px; font-size: 14px; font-weight: 700; cursor: pointer; transition: all 0.3s ease; text-decoration: none; }
.btn:hover { transform: translateY(-2px); box-shadow: 0 8px 24px rgba(var(--theme-rgb), 0.4); }
.btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }

/* Empty State */
.empty-state { text-align: center; padding: 40px 20px; color: var(--text-secondary); }
.empty-state i { font-size: 48px; margin-bottom: 16px; opacity: 0.5; }

@media (max-width: 768px) {
    .withdrawal-container { padding: 6px; }
    .modern-card { padding: 16px; }
    .wallet-selector { grid-template-columns: 1fr; }
}
</style>



    <div class="modern-card">
        <div class="card-header">
            <div class="card-icon"><i class="fas fa-paper-plane"></i></div>
            <h2 class="card-title">Withdrawal Details</h2>
        </div>
        
        <?php if (count($availableWallets) === 0): ?>
            <div class="empty-state">
                <i class="fas fa-wallet"></i>
                <p><strong>No wallets available for withdrawal</strong></p>
                <p>Minimum balance required: <?php echo $currencySymbol . ' ' . number_format($minWithdrawal, 2); ?></p>
            </div>
        <?php else: ?>
            <form method="POST" id="withdrawalForm">
                <div class="form-group">
                    <label class="form-label"><i class="fas fa-wallet"></i> Select Wallet</label>
                    <div class="wallet-selector" id="walletSelector">
                        <?php foreach ($availableWallets as $wallet): ?>
                            <div class="wallet-option" onclick="selectWallet('<?php echo $wallet['type']; ?>', <?php echo $wallet['balance']; ?>)">
                                <input type="radio" name="wallet_type" value="<?php echo $wallet['type']; ?>" id="wallet_<?php echo $wallet['type']; ?>" required>
                                <div class="wallet-option-content">
                                    <div class="wallet-option-icon" style="background: <?php echo $wallet['color']; ?>;"><i class="fas <?php echo $wallet['icon']; ?>"></i></div>
                                    <div class="wallet-option-name"><?php echo $wallet['name']; ?></div>
                                    <div class="wallet-option-balance"><?php echo $currencySymbol . ' ' . number_format($wallet['balance'], 2); ?></div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label"><i class="fas fa-coins"></i> Amount (Min: <?php echo $currencySymbol . ' ' . number_format($minWithdrawal, 2); ?>)</label>
                    <input type="number" name="amount" id="amountInput" class="form-control" min="<?php echo $minWithdrawal; ?>" step="0.01" placeholder="Enter amount" required oninput="updateFeeCalculator()">
                    
                    <div class="fee-calculator" id="feeCalculator">
                        <div class="fee-row"><span>Amount:</span><strong id="feeAmount">-</strong></div>
                        <div class="fee-row"><span>Fee:</span><strong id="feeCharge">-</strong></div>
                        <div class="fee-row"><span>You Receive:</span><strong id="feeNet">-</strong></div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label"><i class="fas fa-phone"></i> M-Pesa Number</label>
                    <input type="tel" name="phone_number" class="form-control" 
                           value="<?php echo htmlspecialchars($userData['phone'] ?? ''); ?>" 
                           placeholder="254XXXXXXXXX" required>
                </div>
                
                <button type="submit" class="btn" id="submitBtn" style="width: 100%; justify-content: center;">
                    <i class="fas fa-paper-plane"></i> Submit Request
                </button>
            </form>
        <?php endif; ?>
    </div>
</div>

<script>
const currencySymbol = '<?php echo $currencySymbol; ?>';
const tieredFees = <?php echo json_encode($tieredFees); ?>;
const flatFee = <?php echo $flatWithdrawalFee; ?>;
const minWithdrawal = <?php echo $minWithdrawal; ?>;
const referralWalletIndex = <?php echo $referralWalletIndex; ?>;
let selectedWalletBalance = 0;

window.addEventListener('DOMContentLoaded', function() {
    if (referralWalletIndex >= 0) {
        const walletOptions = document.querySelectorAll('.wallet-option');
        if (walletOptions[referralWalletIndex]) { walletOptions[referralWalletIndex].click(); }
    }
});

function selectWallet(type, balance) {
    document.querySelectorAll('.wallet-option').forEach(opt => { opt.classList.remove('selected'); });
    event.currentTarget.classList.add('selected');
    document.getElementById('wallet_' + type).checked = true;
    selectedWalletBalance = balance;
    document.getElementById('amountInput').max = balance;
    updateFeeCalculator();
}

function calculateFee(amount) {
    if (tieredFees && tieredFees.length > 0) {
        for (let tier of tieredFees) {
            if (amount >= parseFloat(tier.min_amount) && amount <= parseFloat(tier.max_amount)) { return parseFloat(tier.fee); }
        }
    }
    return flatFee;
}

function updateFeeCalculator() {
    const amountInput = document.getElementById('amountInput');
    const calculator = document.getElementById('feeCalculator');
    const submitBtn = document.getElementById('submitBtn');
    const amount = parseFloat(amountInput.value) || 0;
    
    if (amount > 0) {
        const fee = calculateFee(amount);
        const net = amount - fee;
        document.getElementById('feeAmount').textContent = currencySymbol + ' ' + amount.toFixed(2);
        document.getElementById('feeCharge').textContent = currencySymbol + ' ' + fee.toFixed(2);
        document.getElementById('feeNet').textContent = currencySymbol + ' ' + net.toFixed(2);
        calculator.classList.add('active');
        
        if (amount < minWithdrawal) { submitBtn.disabled = true; submitBtn.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Amount below minimum'; }
        else if (selectedWalletBalance > 0 && amount > selectedWalletBalance) { submitBtn.disabled = true; submitBtn.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Exceeds wallet balance'; }
        else if (net <= 0) { submitBtn.disabled = true; submitBtn.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Amount too low'; }
        else { submitBtn.disabled = false; submitBtn.innerHTML = '<i class="fas fa-paper-plane"></i> Submit Request'; }
    } else {
        calculator.classList.remove('active');
        submitBtn.disabled = false;
    }
}
</script>

<?php
// Catch success messages from session (covers common variations)
$successMessage = '';
if (isset($_SESSION['flash_success'])) {
    $successMessage = $_SESSION['flash_success'];
    unset($_SESSION['flash_success']);
} elseif (isset($_SESSION['flash']['success'])) {
    $successMessage = $_SESSION['flash']['success'];
    unset($_SESSION['flash']['success']);
} elseif (isset($_SESSION['success'])) {
    $successMessage = $_SESSION['success'];
    unset($_SESSION['success']);
}
?>

<?php if (!empty($successMessage)): ?>
<style>
    .success-overlay {
        position: fixed;
        top: 0; left: 0;
        width: 100%; height: 100%;
        background: rgba(0,0,0,0.7); /* Slightly darker overlay */
        z-index: 9999;
        display: flex;
        align-items: center;
        justify-content: center;
        backdrop-filter: blur(5px);
        animation: fadeIn 0.3s ease-out;
    }

    .toast-16-9 {
        width: 90%;
        max-width: 600px; /* Increased Size for bigger impact */
        aspect-ratio: 16/9;
        /* Dark Green Gradient: Deep Forest Green to Very Dark Emerald */
        background: linear-gradient(135deg, #065f46 0%, #022c22 100%);
        border: 2px solid #047857;
        border-radius: 24px;
        box-shadow: 0 25px 80px rgba(0, 50, 20, 0.6);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        text-align: center;
        padding: 40px;
        position: relative;
        color: white;
        animation: scaleIn 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
    }

    .toast-icon {
        font-size: 56px;
        margin-bottom: 20px;
        background: rgba(255,255,255,0.1);
        width: 100px;
        height: 100px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        border: 2px solid rgba(255,255,255,0.1);
    }

    .toast-title {
        font-size: 32px;
        font-weight: 900;
        margin-bottom: 12px;
        text-transform: uppercase;
        letter-spacing: 2px;
        text-shadow: 0 2px 4px rgba(0,0,0,0.3);
    }

    .toast-message {
        font-size: 18px;
        opacity: 0.9;
        line-height: 1.6;
        max-width: 80%;
    }

    .toast-close {
        position: absolute;
        top: 20px;
        right: 20px;
        background: rgba(255,255,255,0.1);
        border: none;
        color: white;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.2s;
        font-size: 18px;
    }

    .toast-close:hover {
        background: rgba(255,255,255,0.3);
        transform: rotate(90deg);
    }

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

<div class="success-overlay" id="successToast">
    <div class="toast-16-9">
        <button class="toast-close" onclick="closeToast()"><i class="fas fa-times"></i></button>
        
        <div class="toast-icon">
            <i class="fas fa-check"></i>
        </div>
        
        <div class="toast-title">Success!</div>
        
        <div class="toast-message">
            <?php echo htmlspecialchars($successMessage); ?>
        </div>
    </div>
</div>

<script>
    function closeToast() {
        const toast = document.getElementById('successToast');
        toast.style.opacity = '0';
        setTimeout(() => { toast.remove(); }, 300);
    }
    setTimeout(closeToast, 6000); // Auto close after 6s
</script>
<?php endif; ?>

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