<?php
/**
 * User Withdrawal Page
 */
$pageTitle = 'Withdraw';
require_once 'includes/header.php';

$withdrawalFee = (float)getSetting('withdrawal_fee_percent', 2);
$minWithdraw = (float)getSetting('min_withdrawal', 1000);
$maxWithdraw = (float)getSetting('max_withdrawal', 100000);

// Get admin settings for withdrawal requirements
$binaryTurnoverMultiplier = (float)getSetting('bonus_turnover_multiplier', 30);
$cfdBalanceMultiplier = (float)getSetting('cfd_balance_multiplier', 3);

// Binary Turnover Requirement (from stored values in users table)
$turnoverRequired = (float)($user['turnover_required'] ?? 0);
$turnoverCompleted = (float)($user['turnover_completed'] ?? 0);
$turnoverRemaining = max(0, $turnoverRequired - $turnoverCompleted);
$binaryMet = $turnoverRemaining <= 0;

// CFD Balance Requirement (stored threshold in users table)
$cfdThreshold = (float)($user['cfd_withdraw_threshold'] ?? 0);
$currentBalance = (float)(($wallet['balance'] ?? 0) + ($wallet['bonus_balance'] ?? 0));
$cfdMet = $cfdThreshold <= 0 || $currentBalance >= $cfdThreshold;

// Either condition can be met to withdraw if requirements exist
if ($turnoverRequired > 0 || $cfdThreshold > 0) {
    $canWithdraw = false;
    if ($turnoverRequired > 0 && $binaryMet) $canWithdraw = true;
    if ($cfdThreshold > 0 && $cfdMet) $canWithdraw = true;
} else {
    $canWithdraw = true;
}

$pendingWithdrawals = dbFetchAll(
    "SELECT * FROM withdrawals WHERE user_id = :id AND status = 'pending' ORDER BY created_at DESC",
    ['id' => $user['id']]
);

$recentWithdrawals = dbFetchAll(
    "SELECT * FROM withdrawals WHERE user_id = :id ORDER BY created_at DESC LIMIT 10",
    ['id' => $user['id']]
);

// Calculate available balance minus pending withdrawals
$pendingAmountData = dbFetch(
    "SELECT COALESCE(SUM(amount), 0) as total_pending FROM withdrawals WHERE user_id = :id AND status = 'pending'",
    ['id' => $user['id']]
);
$pendingAmount = (float)$pendingAmountData['total_pending'];
$availableBalance = max(0, (($wallet['balance'] ?? 0) + ($wallet['bonus_balance'] ?? 0)) - $pendingAmount);


// Handle withdrawal submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount = (float)($_POST['amount'] ?? 0);
    $method = $_POST['method'] ?? '';
    
    $fee = $amount * ($withdrawalFee / 100);
    $netAmount = $amount - $fee;
    
    // Check turnover requirement first
    if (!$canWithdraw) {
        $errorParts = [];
        if ($turnoverRequired > 0 && !$binaryMet) $errorParts[] = 'Complete Binary trading turnover of ' . formatCurrency($turnoverRemaining) . ' more.';
        if ($cfdThreshold > 0 && !$cfdMet) $errorParts[] = 'CFD Balance must reach ' . formatCurrency($cfdThreshold) . ' (current: ' . formatCurrency($currentBalance) . ').';
        $error = implode(' -OR- ', $errorParts);
    } elseif ($amount < $minWithdraw) {
        $error = 'Minimum withdrawal is ' . formatCurrency($minWithdraw);
    } elseif ($amount > $availableBalance) {
        $error = 'Insufficient balance. ' . ($pendingAmount > 0 ? 'You have ' . formatCurrency($pendingAmount) . ' in pending withdrawals.' : '');
    } elseif ($amount > $maxWithdraw) {
        $error = 'Maximum withdrawal is ' . formatCurrency($maxWithdraw);
    } else {
        $withdrawalData = [
            'withdrawal_id' => 'WDR' . strtoupper(substr(md5(uniqid()), 0, 10)),
            'user_id' => $user['id'],
            'amount' => $amount,
            'fee' => $fee,
            'net_amount' => $netAmount,
            'payment_method' => $method,
            'status' => 'pending'
        ];
        
        if ($method === 'upi') {
            $withdrawalData['upi_id'] = trim($_POST['upi_id'] ?? '');
        } elseif ($method === 'bank_transfer') {
            $withdrawalData['bank_name'] = trim($_POST['bank_name'] ?? '');
            $withdrawalData['account_number'] = trim($_POST['account_number'] ?? '');
            $withdrawalData['ifsc_code'] = trim($_POST['ifsc_code'] ?? '');
            $withdrawalData['account_holder'] = trim($_POST['account_holder'] ?? '');
        } elseif ($method === 'crypto') {
            $withdrawalData['wallet_address'] = trim($_POST['wallet_address'] ?? '');
            $withdrawalData['network'] = trim($_POST['network'] ?? 'TRC20');
        }
        
        dbInsert('withdrawals', $withdrawalData);
        
        $success = 'Withdrawal request submitted! ID: ' . $withdrawalData['withdrawal_id'];
        
        // Refresh pending withdrawals list and amount
        $pendingWithdrawals = dbFetchAll(
            "SELECT * FROM withdrawals WHERE user_id = :id AND status = 'pending' ORDER BY created_at DESC",
            ['id' => $user['id']]
        );
        $recentWithdrawals = dbFetchAll(
            "SELECT * FROM withdrawals WHERE user_id = :id ORDER BY created_at DESC LIMIT 10",
            ['id' => $user['id']]
        );
        $pendingAmountData = dbFetch(
            "SELECT COALESCE(SUM(amount), 0) as total_pending FROM withdrawals WHERE user_id = :id AND status = 'pending'",
            ['id' => $user['id']]
        );
        $pendingAmount = (float)$pendingAmountData['total_pending'];
        $availableBalance = max(0, (($wallet['balance'] ?? 0) + ($wallet['bonus_balance'] ?? 0)) - $pendingAmount);
    }
}
?>

<style>
.withdraw-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; }
@media (max-width: 992px) { .withdraw-grid { grid-template-columns: 1fr; } }
.balance-card {
    background: linear-gradient(135deg, rgba(0, 208, 156, 0.1) 0%, rgba(0, 168, 122, 0.1) 100%);
    border: 1px solid rgba(0, 208, 156, 0.2);
    border-radius: var(--radius-lg);
    padding: 1.5rem;
    text-align: center;
    margin-bottom: 1.5rem;
}
.balance-label { font-size: 0.875rem; color: var(--text-muted); }
.balance-amount { font-size: 2rem; font-weight: 700; font-family: var(--font-mono); color: var(--accent-green); }
.turnover-card {
    background: var(--bg-tertiary);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-lg);
    padding: 1.5rem;
    margin-bottom: 1.5rem;
}
.turnover-header { display: flex; justify-content: space-between; margin-bottom: 0.75rem; }
.turnover-title { font-weight: 600; }
.turnover-percent { color: var(--accent-yellow); font-weight: 600; }
.turnover-bar { height: 10px; background: var(--bg-primary); border-radius: 5px; overflow: hidden; margin-bottom: 0.75rem; }
.turnover-fill { height: 100%; background: linear-gradient(90deg, var(--accent-green), var(--accent-yellow)); border-radius: 5px; transition: width 0.3s; }
.turnover-info { display: flex; justify-content: space-between; font-size: 0.8rem; color: var(--text-muted); }
.turnover-warning { background: rgba(255, 82, 82, 0.1); border: 1px solid var(--accent-red); color: var(--accent-red); padding: 1rem; border-radius: var(--radius-md); margin-bottom: 1rem; }
.turnover-success { background: rgba(0, 208, 156, 0.1); border: 1px solid var(--accent-green); color: var(--accent-green); padding: 1rem; border-radius: var(--radius-md); margin-bottom: 1rem; }
.method-tabs { display: flex; gap: 0.5rem; margin-bottom: 1.5rem; }
.method-tab {
    flex: 1;
    padding: 1rem;
    background: var(--bg-tertiary);
    border: 2px solid var(--border-color);
    border-radius: var(--radius-md);
    text-align: center;
    cursor: pointer;
}
.method-tab:hover { border-color: var(--accent-green); }
.method-tab.active { border-color: var(--accent-green); background: rgba(0, 208, 156, 0.1); }
.method-tab i { font-size: 1.5rem; color: var(--accent-green); display: block; margin-bottom: 0.5rem; }
.method-fields { display: none; }
.method-fields.active { display: block; }
.fee-info {
    background: var(--bg-tertiary);
    border-radius: var(--radius-md);
    padding: 1rem;
    margin: 1rem 0;
}
.fee-row { display: flex; justify-content: space-between; padding: 0.5rem 0; font-size: 0.9rem; }
.fee-row.total { border-top: 1px solid var(--border-color); font-weight: 600; padding-top: 0.75rem; margin-top: 0.5rem; }

/* Modal CSS */
.modal-overlay { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); z-index: 1000; align-items: center; justify-content: center; }
.modal-overlay.active { display: flex; }
.modal-content { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: var(--radius-lg); width: 90%; max-width: 500px; max-height: 90vh; overflow-y: auto; }
.modal-header { padding: 1.5rem; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center; }
.modal-title { font-size: 1.25rem; font-weight: 600; margin: 0; }
.modal-close { background: none; border: none; color: var(--text-muted); font-size: 1.5rem; cursor: pointer; padding: 0; line-height: 1; }
.modal-body { padding: 1.5rem; }
</style>

<div class="withdraw-grid">
    <div>
        <div class="balance-card">
            <div class="balance-label">Available Balance</div>
            <div class="balance-amount"><?= formatCurrency(max(0, ($wallet['balance'] ?? 0) + ($wallet['bonus_balance'] ?? 0) - ($pendingAmount ?? 0))) ?></div>
            <?php if (($pendingAmount ?? 0) > 0): ?>
            <div class="balance-label mt-2 text-warning"><i class="fas fa-clock"></i> <?= formatCurrency($pendingAmount) ?> pending</div>
            <?php endif; ?>
        </div>
        
        <div class="card">
            <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
                <h3 class="card-title" style="margin-bottom: 0;">Request Withdrawal</h3>
            </div>
            <div class="card-body">
                <?php if (!empty($error)): ?>
                <div class="alert alert-danger"><?= $error ?></div>
                <?php endif; ?>
                <?php if (!empty($success)): ?>
                <div class="alert alert-success"><?= $success ?></div>
                <?php endif; ?>
                

                
                <form method="POST" id="withdrawForm">
                    <div class="form-group">
                        <label class="form-label">Withdrawal Method</label>
                        <div class="method-tabs">
                            <div class="method-tab active" data-method="upi" onclick="selectWithdrawMethod('upi')">
                                <i class="fas fa-mobile-alt"></i>
                                UPI
                            </div>
                            <div class="method-tab" data-method="bank_transfer" onclick="selectWithdrawMethod('bank_transfer')">
                                <i class="fas fa-university"></i>
                                Bank
                            </div>
                            <div class="method-tab" data-method="crypto" onclick="selectWithdrawMethod('crypto')">
                                <i class="fab fa-bitcoin"></i>
                                Crypto
                            </div>
                        </div>
                        <input type="hidden" name="method" id="withdrawMethod" value="upi">
                    </div>
                    
                    <!-- UPI Fields -->
                    <div class="method-fields active" id="upiFields">
                        <div class="form-group">
                            <label class="form-label">UPI ID</label>
                            <input type="text" name="upi_id" class="form-control" placeholder="yourname@upi">
                        </div>
                    </div>
                    
                    <!-- Bank Fields -->
                    <div class="method-fields" id="bank_transferFields">
                        <div class="form-group">
                            <label class="form-label">Bank Name</label>
                            <input type="text" name="bank_name" class="form-control" placeholder="State Bank of India">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Account Number</label>
                            <input type="text" name="account_number" class="form-control" placeholder="Enter account number">
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label">IFSC Code</label>
                                <input type="text" name="ifsc_code" class="form-control" placeholder="SBIN0001234">
                            </div>
                            <div class="form-group">
                                <label class="form-label">Account Holder Name</label>
                                <input type="text" name="account_holder" class="form-control" placeholder="Full name">
                            </div>
                        </div>
                    </div>
                    
                    <!-- Crypto Fields -->
                    <div class="method-fields" id="cryptoFields">
                        <div class="form-group">
                            <label class="form-label">Network</label>
                            <select name="network" class="form-control">
                                <option value="TRC20">USDT - TRC20 (Tron)</option>
                                <option value="ERC20">USDT - ERC20 (Ethereum)</option>
                                <option value="BEP20">USDT - BEP20 (BSC)</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Wallet Address</label>
                            <input type="text" name="wallet_address" class="form-control" placeholder="Enter wallet address">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Amount (<?= CURRENCY_SYMBOL ?>)</label>
                        <input type="number" name="amount" id="withdrawAmount" class="form-control" min="<?= $minWithdraw ?>" max="<?= min($maxWithdraw, max(0, ($wallet['balance'] ?? 0) + ($wallet['bonus_balance'] ?? 0) - ($pendingAmount ?? 0))) ?>" step="100" placeholder="Enter amount" required onchange="calculateFee()">
                        <div class="form-text">Min: <?= formatCurrency($minWithdraw) ?> | Max: <?= formatCurrency($maxWithdraw) ?> | Fee: <?= $withdrawalFee ?>%</div>
                    </div>
                    
                    <div class="fee-info">
                        <div class="fee-row">
                            <span>Withdrawal Amount</span>
                            <span id="feeAmount"><?= CURRENCY_SYMBOL ?>0.00</span>
                        </div>
                        <div class="fee-row">
                            <span>Fee (<?= $withdrawalFee ?>%)</span>
                            <span id="feeValue">-<?= CURRENCY_SYMBOL ?>0.00</span>
                        </div>
                        <div class="fee-row total">
                            <span>You'll Receive</span>
                            <span class="text-green" id="netAmount"><?= CURRENCY_SYMBOL ?>0.00</span>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary btn-block">
                        <i class="fas fa-paper-plane"></i> Request Withdrawal
                    </button>
                </form>
            </div>
        </div>
        
        <div class="card" style="margin-top: 1.5rem;">
            <div class="card-header">
                <h3 class="card-title">Withdrawal History</h3>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Amount</th>
                                <th>Net</th>
                                <th>Status</th>
                                <th>Date</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recentWithdrawals as $wd): ?>
                            <tr>
                                <td class="font-mono"><?= $wd['withdrawal_id'] ?></td>
                                <td><?= formatCurrency($wd['amount']) ?></td>
                                <td class="font-semibold"><?= formatCurrency($wd['net_amount']) ?></td>
                                <td>
                                    <?php
                                    $statusClasses = ['approved' => 'success', 'completed' => 'success', 'rejected' => 'danger'];
                                    $statusClass = $statusClasses[$wd['status']] ?? 'warning';
                                    ?>
                                    <span class="badge badge-<?= $statusClass ?>"><?= ucfirst($wd['status']) ?></span>
                                </td>
                                <td class="text-muted"><?= formatDateTime($wd['created_at'], 'd M Y') ?></td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if (empty($recentWithdrawals)): ?>
                            <tr><td colspan="5" class="text-center text-muted py-4">No withdrawals yet</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <div>
        <?php if (!empty($pendingWithdrawals)): ?>
        <div class="card mb-3">
            <div class="card-header">
                <h3 class="card-title">Pending Withdrawals</h3>
            </div>
            <div class="card-body p-0">
                <?php foreach ($pendingWithdrawals as $wd): ?>
                <div class="d-flex align-items-center gap-3 p-3" style="border-bottom: 1px solid var(--border-color);">
                    <div class="stat-icon yellow" style="width: 40px; height: 40px;">
                        <i class="fas fa-clock"></i>
                    </div>
                    <div class="flex-1">
                        <div class="font-semibold"><?= formatCurrency($wd['net_amount']) ?></div>
                        <div class="text-muted" style="font-size: 0.75rem;"><?= $wd['withdrawal_id'] ?> • <?= timeAgo($wd['created_at']) ?></div>
                    </div>
                    <span class="badge badge-warning">Processing</span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
        
    </div>
</div>

<script>
const withdrawalFee = <?= $withdrawalFee ?>;

function selectWithdrawMethod(method) {
    document.querySelectorAll('.method-tab').forEach(t => t.classList.remove('active'));
    document.querySelector(`[data-method="${method}"]`).classList.add('active');
    document.getElementById('withdrawMethod').value = method;
    
    document.querySelectorAll('.method-fields').forEach(f => f.classList.remove('active'));
    document.getElementById(method + 'Fields').classList.add('active');
}

function calculateFee() {
    const amount = parseFloat(document.getElementById('withdrawAmount').value) || 0;
    const fee = amount * (withdrawalFee / 100);
    const net = amount - fee;
    
    document.getElementById('feeAmount').textContent = '<?= CURRENCY_SYMBOL ?>' + amount.toFixed(2);
    document.getElementById('feeValue').textContent = '-<?= CURRENCY_SYMBOL ?>' + fee.toFixed(2);
    document.getElementById('netAmount').textContent = '<?= CURRENCY_SYMBOL ?>' + net.toFixed(2);
}

function showBonusRequirements() {
    document.getElementById('bonusRequirementsModal').classList.add('active');
}

function hideBonusRequirements() {
    document.getElementById('bonusRequirementsModal').classList.remove('active');
}

const canWithdraw = <?= $canWithdraw ? 'true' : 'false' ?>;

document.getElementById('withdrawForm').addEventListener('submit', function(e) {
    if (!canWithdraw) {
        e.preventDefault();
        showBonusRequirements();
        return false;
    }
});
</script>

<!-- Bonus Requirements Modal -->
<div class="modal-overlay" id="bonusRequirementsModal">
    <div class="modal-content">
        <div class="modal-header">
            <h4 class="modal-title">Bonus Withdrawal Requirements</h4>
            <button class="modal-close" onclick="hideBonusRequirements()">&times;</button>
        </div>
        <div class="modal-body">
            <div class="turnover-card">
                <div class="turnover-header">
                    <span class="turnover-title"><i class="fas fa-chart-bar"></i> Binary Trading Turnover</span>
                    <span class="turnover-percent"><?= $turnoverRequired > 0 ? round(($turnoverCompleted / $turnoverRequired) * 100, 1) : 0 ?>%</span>
                </div>
                <div class="turnover-bar">
                    <div class="turnover-fill" style="width: <?= $turnoverRequired > 0 ? min(100, ($turnoverCompleted / $turnoverRequired) * 100) : 0 ?>%"></div>
                </div>
                <div class="turnover-info">
                    <span>Completed: <?= formatCurrency($turnoverCompleted) ?></span>
                    <span>Required: <?= formatCurrency($turnoverRequired) ?></span>
                </div>
                <div style="font-size: 0.75rem; color: var(--text-muted); margin-top: 0.5rem;">
                    <strong>Binary Turnover Multiplier (<?= number_format($binaryTurnoverMultiplier, 0) ?>x)</strong><br>
                    (Deposit+Bonus) × <?= number_format($binaryTurnoverMultiplier, 0) ?>x = <?= number_format($binaryTurnoverMultiplier * 100, 0) ?>% turnover required
                </div>
            </div>
            
            <div class="turnover-card">
                <div class="turnover-header">
                    <span class="turnover-title"><i class="fas fa-chart-line"></i> CFD Balance Requirement</span>
                    <span class="turnover-percent"><?= $cfdThreshold > 0 ? round(($currentBalance / $cfdThreshold) * 100, 1) : 100 ?>%</span>
                </div>
                <div class="turnover-bar">
                    <div class="turnover-fill" style="width: <?= $cfdThreshold > 0 ? min(100, ($currentBalance / $cfdThreshold) * 100) : 100 ?>%; background: linear-gradient(90deg, #6366f1, #818cf8);"></div>
                </div>
                <div class="turnover-info">
                    <span>Current Balance: <?= formatCurrency($currentBalance) ?></span>
                    <span>Required: <?= formatCurrency($cfdThreshold) ?></span>
                </div>
                <div style="font-size: 0.75rem; color: var(--text-muted); margin-top: 0.5rem;">
                    <strong>CFD Balance Multiplier (<?= number_format($cfdBalanceMultiplier, 0) ?>x)</strong><br>
                    (Deposit+Bonus) × <?= number_format($cfdBalanceMultiplier, 0) ?>x balance required
                </div>
            </div>
            
            <?php if (!$canWithdraw): ?>
            <div class="turnover-warning" style="margin-bottom: 0;">
                <i class="fas fa-exclamation-triangle"></i>
                <strong>Withdrawal Locked</strong><br>
                <?php if ($turnoverRequired > 0 && !$binaryMet): ?>
                Complete Binary trading turnover of <strong><?= formatCurrency($turnoverRemaining) ?></strong> more.<br>
                <?php endif; ?>
                
                <?php if ($turnoverRequired > 0 && !$binaryMet && $cfdThreshold > 0 && !$cfdMet): ?>
                <strong>-- OR --</strong><br>
                <?php endif; ?>
                
                <?php if ($cfdThreshold > 0 && !$cfdMet): ?>
                CFD Balance must reach <strong><?= formatCurrency($cfdThreshold) ?></strong> (current: <?= formatCurrency($currentBalance) ?>).<br>
                <?php endif; ?>
                <small style="opacity: 0.8;">(Complete ANY ONE condition to unlock)</small>
            </div>
            <?php else: ?>
            <div class="turnover-success" style="margin-bottom: 0;">
                <i class="fas fa-check-circle"></i>
                <strong>Withdrawal Unlocked!</strong><br>All bonus requirements have been completed.
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php require_once 'includes/footer.php'; ?>
