<?php
session_start();
require_once '../config.php';

// Admin Auth Check
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}

global $pdo;
$message = '';
$msg_type = 'success';

// =========================================================
// 1. UPDATE WIN PERCENTAGE (RTP)
// =========================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_rtp'])) {
    $new_rtp = (int)$_POST['win_percent'];
    if ($new_rtp < 0) $new_rtp = 0;
    if ($new_rtp > 100) $new_rtp = 100;
    
    // Check if setting exists
    $check = $pdo->query("SELECT COUNT(*) FROM settings WHERE setting_key = 'mines_win_percent'")->fetchColumn();
    
    if ($check > 0) {
        $stmt = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = 'mines_win_percent'");
        $stmt->execute([$new_rtp]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES ('mines_win_percent', ?)");
        $stmt->execute([$new_rtp]);
    }
    $message = "Mines Pro Win Percentage Updated to {$new_rtp}% successfully!";
}

// =========================================================
// 2. FETCH CURRENT WIN PERCENTAGE
// =========================================================
$current_rtp = 40; // Default
try {
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'mines_win_percent'");
    $stmt->execute();
    $res = $stmt->fetchColumn();
    if ($res !== false) $current_rtp = (int)$res;
} catch(Exception $e) {}

// =========================================================
// 3. FETCH GAME STATISTICS (Total Volume, Payout, Profit)
// =========================================================
$stats = ['total_bets' => 0, 'volume' => 0, 'payout' => 0, 'profit' => 0];
try {
    $stmt = $pdo->query("SELECT COUNT(*) as total_bets, SUM(bet_amount) as volume, SUM(win_amount) as payout FROM game_history WHERE game_name = 'Mines Pro'");
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if($row) {
        $stats['total_bets'] = $row['total_bets'] ?? 0;
        $stats['volume'] = $row['volume'] ?? 0;
        $stats['payout'] = $row['payout'] ?? 0;
        $stats['profit'] = $stats['volume'] - $stats['payout'];
    }
} catch(Exception $e) {}

// =========================================================
// 4. FETCH ALL BET HISTORY
// =========================================================
$history = [];
try {
    $history = $pdo->query("SELECT * FROM game_history WHERE game_name = 'Mines Pro' ORDER BY id DESC LIMIT 150")->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {}

$pageTitle = "Manage Boom Mines";
require_once 'includes/header.php';
?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
    body { background-color: #f4f7f6; }
    
    /* Modern Dashboard Cards */
    .stat-card { border: none; border-radius: 16px; color: white; overflow: hidden; position: relative;}
    .stat-card i { position: absolute; right: -10px; bottom: -10px; font-size: 80px; opacity: 0.2; transform: rotate(-15deg);}
    .bg-gradient-blue { background: linear-gradient(135deg, #005bcc 0%, #002b6b 100%); }
    .bg-gradient-green { background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%); }
    .bg-gradient-red { background: linear-gradient(135deg, #ff3b30 0%, #b31b14 100%); }
    
    /* Panel Cards */
    .card-modern { border: none; border-radius: 16px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); background: #fff;}
    .card-modern-header { background: #fff; border-bottom: 1px solid #f1f5f9; padding: 18px 20px; border-top-left-radius: 16px; border-top-right-radius: 16px;}
    
    /* Responsive Table */
    .table-hover tbody tr:hover { background-color: #f8fafc; transform: scale(1.001); transition: 0.2s;}
    .table td, .table th { padding: 16px; vertical-align: middle; border-bottom: 1px solid #f1f5f9;}
    .table thead th { text-transform: uppercase; font-size: 12px; font-weight: 700; color: #64748b; letter-spacing: 0.5px;}
    
    /* Badges */
    .badge-win { background-color: rgba(40, 167, 69, 0.1); color: #28a745; border: 1px solid #28a745; padding: 6px 12px; border-radius: 6px; font-weight: 800;}
    .badge-loss { background-color: rgba(255, 59, 48, 0.1); color: #ff3b30; border: 1px solid #ff3b30; padding: 6px 12px; border-radius: 6px; font-weight: 800;}
    .badge-mult { background-color: #f1f5f9; color: #334155; border-radius: 6px; padding: 5px 10px; font-weight: 800;}
</style>

<?php if($message): ?>
<script>
    document.addEventListener("DOMContentLoaded", function() {
        Swal.fire({
            toast: true, position: 'top-end', icon: '<?= $msg_type ?>', 
            title: '<?= addslashes($message) ?>', showConfirmButton: false, timer: 3000
        });
    });
</script>
<?php endif; ?>

<div class="container-fluid px-4 py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="fw-bold text-dark mb-0"><i class="fas fa-bomb text-danger me-2"></i> Manage Boom Mines</h4>
        <a href="../games/mines.php?id=8" target="_blank" class="btn btn-primary fw-bold rounded-pill px-4"><i class="fas fa-play me-1"></i> Play Game</a>
    </div>

    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-3">
            <div class="card stat-card bg-gradient-blue shadow-sm p-4">
                <i class="fas fa-chart-line"></i>
                <p class="text-uppercase fw-bold mb-1 opacity-75 small">Total Bets</p>
                <h3 class="fw-bold mb-0"><?= number_format($stats['total_bets']) ?></h3>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <div class="card stat-card bg-gradient-blue shadow-sm p-4">
                <i class="fas fa-coins"></i>
                <p class="text-uppercase fw-bold mb-1 opacity-75 small">Total Bet Volume</p>
                <h3 class="fw-bold mb-0">₹<?= number_format($stats['volume'], 2) ?></h3>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <div class="card stat-card bg-gradient-red shadow-sm p-4">
                <i class="fas fa-hand-holding-usd"></i>
                <p class="text-uppercase fw-bold mb-1 opacity-75 small">Total User Payout</p>
                <h3 class="fw-bold mb-0">₹<?= number_format($stats['payout'], 2) ?></h3>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <div class="card stat-card bg-gradient-green shadow-sm p-4">
                <i class="fas fa-wallet"></i>
                <p class="text-uppercase fw-bold mb-1 opacity-75 small">Admin Profit (Edge)</p>
                <h3 class="fw-bold mb-0">₹<?= number_format($stats['profit'], 2) ?></h3>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-4 mb-4">
            <div class="card card-modern">
                <div class="card-modern-header d-flex align-items-center">
                    <h6 class="m-0 fw-bold text-dark"><i class="fas fa-sliders-h text-primary me-2"></i> Game Rigging Control</h6>
                </div>
                <div class="card-body p-4">
                    <form method="POST">
                        <div class="mb-4">
                            <label class="form-label fw-bold text-muted small text-uppercase">Target Win Percentage (%)</label>
                            <div class="input-group input-group-lg shadow-sm rounded-3 overflow-hidden">
                                <input type="number" name="win_percent" class="form-control fw-bold text-center border-0 bg-light" value="<?= $current_rtp ?>" min="0" max="100" required>
                                <span class="input-group-text border-0 bg-primary text-white fw-bold">%</span>
                            </div>
                            <div class="mt-3 p-3 bg-light rounded-3 border">
                                <small class="text-muted d-block">
                                    <i class="fas fa-shield-alt text-success me-1"></i> <b>Currently set to <?= $current_rtp ?>%</b>.<br><br>
                                    This means the server will allow the user to win naturally <b><?= $current_rtp ?>%</b> of the time. The remaining <b><?= 100 - $current_rtp ?>%</b> of the time, the server will intentionally spawn a bomb on the user's click to force a crash.
                                </small>
                            </div>
                        </div>
                        <button type="submit" name="update_rtp" class="btn btn-primary w-100 fw-bold py-3 fs-6 rounded-pill shadow-sm">
                            <i class="fas fa-save me-1"></i> Save Changes
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-lg-8">
            <div class="card card-modern">
                <div class="card-modern-header d-flex justify-content-between align-items-center">
                    <h6 class="m-0 fw-bold text-dark"><i class="fas fa-history text-primary me-2"></i> Live Bet History (Last 150)</h6>
                    <span class="badge bg-light text-dark border"><i class="fas fa-sync fa-spin text-primary me-1"></i> Live</span>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive" style="max-height: 500px; overflow-y: auto;">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="table-light sticky-top" style="z-index: 10;">
                                <tr>
                                    <th class="ps-4">User ID</th>
                                    <th>Bet Amount</th>
                                    <th>Multiplier</th>
                                    <th>Payout</th>
                                    <th>Status</th>
                                    <th>Date/Time</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(!empty($history)): foreach($history as $h): ?>
                                <tr>
                                    <td class="ps-4 fw-bold text-primary">#<?= htmlspecialchars($h['user_id']) ?></td>
                                    <td class="fw-bold text-dark">₹<?= number_format($h['bet_amount'], 2) ?></td>
                                    <td><span class="badge-mult"><i class="fas fa-times text-muted" style="font-size:10px;"></i> <?= number_format($h['multiplier'], 2) ?></span></td>
                                    <td class="fw-bold <?= $h['status']=='win' ? 'text-success' : 'text-muted opacity-50' ?>">
                                        ₹<?= number_format($h['win_amount'], 2) ?>
                                    </td>
                                    <td>
                                        <?php if($h['status'] == 'win'): ?>
                                            <span class="badge-win"><i class="fas fa-star text-warning"></i> CASHOUT</span>
                                        <?php else: ?>
                                            <span class="badge-loss"><i class="fas fa-bomb"></i> CRASHED</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-muted small fw-bold"><?= date('d M, h:i A', strtotime($h['created_at'])) ?></td>
                                </tr>
                                <?php endforeach; else: ?>
                                <tr><td colspan="6" class="text-center py-5 text-muted"><i class="fas fa-ghost fs-1 mb-3 opacity-25 d-block"></i> No bet history found for Mines.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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