<?php
/**
 * Admin Risk Management
 * Global Win Rate: 0-100% (applies ONLY to LIVE accounts)
 * Demo accounts are ALWAYS risk-free (natural market results)
 */
require_once 'includes/header.php';

// Get risk stats (LIVE trades only)
$stats = [
    'total_trades_today' => dbFetch("SELECT COUNT(*) as c FROM trades WHERE DATE(created_at) = CURDATE() AND is_demo = 0")['c'] ?? 0,
    'total_volume_today' => dbFetch("SELECT COALESCE(SUM(amount),0) as s FROM trades WHERE DATE(created_at) = CURDATE() AND is_demo = 0")['s'] ?? 0,
    'pending_withdrawals' => dbFetch("SELECT COALESCE(SUM(amount),0) as s FROM withdrawals WHERE status = 'pending'")['s'] ?? 0,
    'platform_profit' => dbFetch("SELECT COALESCE(SUM(CASE WHEN result = 'lost' THEN amount ELSE 0 END) - SUM(CASE WHEN result = 'won' THEN actual_profit ELSE 0 END), 0) as p FROM trades WHERE result IN ('won','lost') AND is_demo = 0")['p'] ?? 0,
    'demo_trades_today' => dbFetch("SELECT COUNT(*) as c FROM trades WHERE DATE(created_at) = CURDATE() AND is_demo = 1")['c'] ?? 0,
    'live_win_count' => dbFetch("SELECT COUNT(*) as c FROM trades WHERE result = 'won' AND is_demo = 0")['c'] ?? 0,
    'live_loss_count' => dbFetch("SELECT COUNT(*) as c FROM trades WHERE result = 'lost' AND is_demo = 0")['c'] ?? 0
];

// Calculate actual win rate
$totalLiveTrades = $stats['live_win_count'] + $stats['live_loss_count'];
$actualWinRate = $totalLiveTrades > 0 ? round(($stats['live_win_count'] / $totalLiveTrades) * 100, 1) : 0;

// Handle settings update
$successMsg = '';
$errorMsg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate Global Win Rate (0-100)
    $globalWinRate = (int)$_POST['global_win_rate'];
    if ($globalWinRate < 0) $globalWinRate = 0;
    if ($globalWinRate > 100) $globalWinRate = 100;
    
    $settings = [
        'global_win_rate' => $globalWinRate,
        'max_daily_payout' => (float)$_POST['max_daily_payout'],
        'max_single_trade' => (float)$_POST['max_single_trade'],
        'risk_mode' => $_POST['risk_mode'],
        'win_rate_min' => 0,
        'win_rate_max' => 100
    ];
    
    foreach ($settings as $key => $value) {
        $exists = dbFetch("SELECT id FROM settings WHERE setting_key = ?", [$key]);
        if ($exists) {
            dbUpdate('settings', ['setting_value' => $value], 'setting_key = ?', [$key]);
        } else {
            dbInsert('settings', ['setting_key' => $key, 'setting_value' => $value]);
        }
    }
    
    // Log activity
    logActivity('admin', $_SESSION['admin_id'] ?? 0, 'risk_settings', "Updated global win rate to {$globalWinRate}%");
    
    $successMsg = 'Risk settings updated successfully! Global Win Rate set to ' . $globalWinRate . '%';
}

// Get current settings
$globalWinRate = (int)(dbFetch("SELECT setting_value FROM settings WHERE setting_key = 'global_win_rate'")['setting_value'] ?? 45);
$maxDailyPayout = dbFetch("SELECT setting_value FROM settings WHERE setting_key = 'max_daily_payout'")['setting_value'] ?? 1000000;
$maxSingleTrade = dbFetch("SELECT setting_value FROM settings WHERE setting_key = 'max_single_trade'")['setting_value'] ?? 50000;
$riskMode = dbFetch("SELECT setting_value FROM settings WHERE setting_key = 'risk_mode'")['setting_value'] ?? 'balanced';

// Ensure win rate is within bounds
if ($globalWinRate < 0) $globalWinRate = 0;
if ($globalWinRate > 100) $globalWinRate = 100;
?>

<div class="page-header">
    <h1 class="page-title">
        <i class="fas fa-shield-alt"></i> Risk Management
    </h1>
    <p class="text-muted">Control platform risk settings for LIVE accounts only</p>
</div>

<?php if ($successMsg): ?>
<div class="alert alert-success alert-dismissible fade show">
    <i class="fas fa-check-circle"></i> <?= $successMsg ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Important Notice -->
<div class="alert alert-info mb-4">
    <h5><i class="fas fa-info-circle"></i> How Risk Control Works</h5>
    <ul class="mb-0">
        <li><strong>LIVE Account:</strong> Global Win Rate (<?= $globalWinRate ?>%) controls the probability of winning trades</li>
        <li><strong>Demo Account:</strong> Always RISK-FREE - uses natural market results (no manipulation)</li>
        <li><strong>Win Rate Range:</strong> 0% (all trades lose) to 100% (all trades win)</li>
    </ul>
</div>

<div class="row">
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon blue"><i class="fas fa-chart-line"></i></div>
            <div class="stat-value"><?= number_format($stats['total_trades_today']) ?></div>
            <div class="stat-label">Live Trades Today</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon yellow"><i class="fas fa-rupee-sign"></i></div>
            <div class="stat-value"><?= CURRENCY_SYMBOL ?><?= number_format($stats['total_volume_today']) ?></div>
            <div class="stat-label">Live Volume Today</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon <?= $stats['platform_profit'] >= 0 ? 'green' : 'red' ?>"><i class="fas fa-wallet"></i></div>
            <div class="stat-value"><?= CURRENCY_SYMBOL ?><?= number_format($stats['platform_profit']) ?></div>
            <div class="stat-label">Platform Profit</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon purple"><i class="fas fa-percentage"></i></div>
            <div class="stat-value"><?= $actualWinRate ?>%</div>
            <div class="stat-label">Actual Win Rate (Live)</div>
        </div>
    </div>
</div>

<div class="row mt-4">
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon green"><i class="fas fa-trophy"></i></div>
            <div class="stat-value"><?= number_format($stats['live_win_count']) ?></div>
            <div class="stat-label">Total Live Wins</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon red"><i class="fas fa-times-circle"></i></div>
            <div class="stat-value"><?= number_format($stats['live_loss_count']) ?></div>
            <div class="stat-label">Total Live Losses</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon orange"><i class="fas fa-clock"></i></div>
            <div class="stat-value"><?= CURRENCY_SYMBOL ?><?= number_format($stats['pending_withdrawals']) ?></div>
            <div class="stat-label">Pending Withdrawals</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon cyan"><i class="fas fa-flask"></i></div>
            <div class="stat-value"><?= number_format($stats['demo_trades_today']) ?></div>
            <div class="stat-label">Demo Trades Today</div>
        </div>
    </div>
</div>

<div class="card mt-4">
    <div class="card-header bg-danger text-white">
        <h3 class="card-title mb-0">
            <i class="fas fa-cog"></i> Global Risk Settings (LIVE Account Only)
        </h3>
    </div>
    <div class="card-body">
        <form method="POST" id="riskForm">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label class="form-label fw-bold">
                            <i class="fas fa-percentage text-danger"></i> Global Win Rate (%)
                            <span class="badge bg-danger">LIVE ONLY</span>
                        </label>
                        <div class="input-group">
                            <input type="range" class="form-range" id="winRateSlider" min="0" max="100" value="<?= $globalWinRate ?>" oninput="updateWinRate(this.value)">
                        </div>
                        <div class="input-group mt-2">
                            <span class="input-group-text">Win Rate</span>
                            <input type="number" name="global_win_rate" id="winRateInput" class="form-control form-control-lg text-center fw-bold" value="<?= $globalWinRate ?>" min="0" max="100" oninput="updateSlider(this.value)">
                            <span class="input-group-text">%</span>
                        </div>
                        <div class="mt-2">
                            <small class="text-muted">
                                <i class="fas fa-info-circle"></i> Controls probability of LIVE trades winning
                            </small>
                            <div class="progress mt-2" style="height: 25px;">
                                <div class="progress-bar bg-success" id="winRateBar" style="width: <?= $globalWinRate ?>%">
                                    <?= $globalWinRate ?>% Win
                                </div>
                                <div class="progress-bar bg-danger" id="loseRateBar" style="width: <?= 100 - $globalWinRate ?>%">
                                    <?= 100 - $globalWinRate ?>% Lose
                                </div>
                            </div>
                        </div>
                        <div class="alert alert-warning mt-3 mb-0">
                            <small>
                                <strong>0%:</strong> All LIVE trades will lose<br>
                                <strong>50%:</strong> 50/50 chance (fair)<br>
                                <strong>100%:</strong> All LIVE trades will win
                            </small>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label class="form-label fw-bold">
                            <i class="fas fa-sliders-h"></i> Risk Mode
                        </label>
                        <select name="risk_mode" class="form-control form-control-lg">
                            <option value="conservative" <?= $riskMode === 'conservative' ? 'selected' : '' ?>>🛡️ Conservative (Lower payouts, safer for platform)</option>
                            <option value="balanced" <?= $riskMode === 'balanced' ? 'selected' : '' ?>>⚖️ Balanced (Default)</option>
                            <option value="aggressive" <?= $riskMode === 'aggressive' ? 'selected' : '' ?>>🔥 Aggressive (Higher payouts, riskier for platform)</option>
                        </select>
                        <small class="text-muted">Affects payout calculations and risk exposure</small>
                    </div>
                    
                    <div class="alert alert-success mt-3">
                        <h6><i class="fas fa-flask"></i> Demo Account Settings</h6>
                        <p class="mb-0">Demo accounts are <strong>ALWAYS RISK-FREE</strong> and use natural market results. No manipulation applied.</p>
                    </div>
                </div>
            </div>
            
            <hr>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label class="form-label fw-bold">
                            <i class="fas fa-rupee-sign"></i> Max Daily Payout
                        </label>
                        <div class="input-group">
                            <span class="input-group-text"><?= CURRENCY_SYMBOL ?></span>
                            <input type="number" name="max_daily_payout" class="form-control" value="<?= $maxDailyPayout ?>">
                        </div>
                        <small class="text-muted">Maximum total payout per day (LIVE only)</small>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label class="form-label fw-bold">
                            <i class="fas fa-hand-holding-usd"></i> Max Single Trade
                        </label>
                        <div class="input-group">
                            <span class="input-group-text"><?= CURRENCY_SYMBOL ?></span>
                            <input type="number" name="max_single_trade" class="form-control" value="<?= $maxSingleTrade ?>">
                        </div>
                        <small class="text-muted">Maximum amount for single trade</small>
                    </div>
                </div>
            </div>
            
            <div class="mt-4">
                <button type="submit" class="btn btn-danger btn-lg">
                    <i class="fas fa-save"></i> Save Risk Settings
                </button>
                <button type="button" class="btn btn-outline-secondary btn-lg ms-2" onclick="resetToDefault()">
                    <i class="fas fa-undo"></i> Reset to Default (45%)
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Quick Win Rate Presets -->
<div class="card mt-4">
    <div class="card-header">
        <h3 class="card-title mb-0"><i class="fas fa-magic"></i> Quick Win Rate Presets</h3>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-2">
                <button class="btn btn-danger w-100 mb-2" onclick="setWinRate(0)">
                    <strong>0%</strong><br><small>All Lose</small>
                </button>
            </div>
            <div class="col-md-2">
                <button class="btn btn-warning w-100 mb-2" onclick="setWinRate(25)">
                    <strong>25%</strong><br><small>Platform Wins</small>
                </button>
            </div>
            <div class="col-md-2">
                <button class="btn btn-secondary w-100 mb-2" onclick="setWinRate(45)">
                    <strong>45%</strong><br><small>Recommended</small>
                </button>
            </div>
            <div class="col-md-2">
                <button class="btn btn-info w-100 mb-2" onclick="setWinRate(50)">
                    <strong>50%</strong><br><small>Fair (50/50)</small>
                </button>
            </div>
            <div class="col-md-2">
                <button class="btn btn-primary w-100 mb-2" onclick="setWinRate(75)">
                    <strong>75%</strong><br><small>User Friendly</small>
                </button>
            </div>
            <div class="col-md-2">
                <button class="btn btn-success w-100 mb-2" onclick="setWinRate(100)">
                    <strong>100%</strong><br><small>All Win</small>
                </button>
            </div>
        </div>
    </div>
</div>

<script>
function updateWinRate(val) {
    val = Math.max(0, Math.min(100, parseInt(val) || 0));
    document.getElementById('winRateInput').value = val;
    document.getElementById('winRateSlider').value = val;
    document.getElementById('winRateBar').style.width = val + '%';
    document.getElementById('winRateBar').textContent = val + '% Win';
    document.getElementById('loseRateBar').style.width = (100 - val) + '%';
    document.getElementById('loseRateBar').textContent = (100 - val) + '% Lose';
}

function updateSlider(val) {
    val = Math.max(0, Math.min(100, parseInt(val) || 0));
    document.getElementById('winRateSlider').value = val;
    updateWinRate(val);
}

function setWinRate(val) {
    updateWinRate(val);
}

function resetToDefault() {
    setWinRate(45);
}

// Validate on form submit
document.getElementById('riskForm').addEventListener('submit', function(e) {
    var winRate = parseInt(document.getElementById('winRateInput').value) || 0;
    if (winRate < 0 || winRate > 100) {
        alert('Win Rate must be between 0 and 100');
        e.preventDefault();
        return false;
    }
});
</script>

<style>
.stat-card .stat-icon.purple { background: linear-gradient(135deg, #9c27b0, #7b1fa2); }
.stat-card .stat-icon.orange { background: linear-gradient(135deg, #ff9800, #f57c00); }
.stat-card .stat-icon.cyan { background: linear-gradient(135deg, #00bcd4, #0097a7); }
.form-range { width: 100%; height: 30px; }
</style>

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