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

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

global $pdo;
$message = '';

// 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 = 'chicken_win_percent'")->fetchColumn();
    
    if ($check > 0) {
        $stmt = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = 'chicken_win_percent'");
        $stmt->execute([$new_rtp]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES ('chicken_win_percent', ?)");
        $stmt->execute([$new_rtp]);
    }
    $message = "Chicken Road Win Percentage Updated to {$new_rtp}%";
}

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

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

$pageTitle = "Manage Chicken Road";
require_once 'includes/header.php';
?>

<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-drumstick-bite text-danger me-2"></i> Manage Chicken Road</h4>
    </div>

    <?php if($message): ?>
        <div class="alert alert-success fw-bold"><i class="fas fa-check-circle"></i> <?= $message ?></div>
    <?php endif; ?>

    <div class="row">
        <div class="col-md-4">
            <div class="card border-0 shadow-sm rounded-4 mb-4">
                <div class="card-header bg-dark text-white fw-bold py-3 rounded-top-4">
                    <i class="fas fa-cogs text-warning"></i> Game Settings (Win Control)
                </div>
                <div class="card-body p-4">
                    <form method="POST">
                        <div class="mb-3">
                            <label class="form-label fw-bold text-muted text-uppercase small">User Win Percentage (%)</label>
                            <div class="input-group">
                                <input type="number" name="win_percent" class="form-control fw-bold fs-4 text-center text-success" value="<?= $current_rtp ?>" min="0" max="100" required>
                                <span class="input-group-text bg-light fw-bold">%</span>
                            </div>
                            <small class="text-muted mt-2 d-block">
                                <i class="fas fa-info-circle text-danger"></i> If set to <b>40%</b>, user has a 40% chance to reach the Golden Egg. 60% chance to crash in the middle.
                            </small>
                        </div>
                        <button type="submit" name="update_rtp" class="btn btn-success w-100 fw-bold py-2 fs-5 rounded-3 shadow-sm">
                            <i class="fas fa-save"></i> Update Win %
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-md-8">
            <div class="card border-0 shadow-sm rounded-4">
                <div class="card-header bg-white border-bottom fw-bold py-3 d-flex justify-content-between align-items-center">
                    <span><i class="fas fa-history text-primary"></i> Recent 100 Bets</span>
                    <span class="badge bg-primary rounded-pill"><?= count($history) ?> Records</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">
                                <tr>
                                    <th class="ps-4">User ID</th>
                                    <th>Bet Amount</th>
                                    <th>Multiplier</th>
                                    <th>Win Amount</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">#<?= htmlspecialchars($h['user_id']) ?></td>
                                    <td class="fw-bold">₹<?= number_format($h['bet_amount'], 2) ?></td>
                                    <td><span class="badge bg-secondary"><?= number_format($h['multiplier'], 2) ?>x</span></td>
                                    <td class="fw-bold <?= $h['status']=='win' ? 'text-success' : 'text-muted' ?>">
                                        ₹<?= number_format($h['win_amount'], 2) ?>
                                    </td>
                                    <td>
                                        <?php if($h['status'] == 'win'): ?>
                                            <span class="badge bg-success"><i class="fas fa-check"></i> WIN</span>
                                        <?php else: ?>
                                            <span class="badge bg-danger"><i class="fas fa-times"></i> CRASH</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-muted small"><?= date('d M Y, h:i A', strtotime($h['created_at'])) ?></td>
                                </tr>
                                <?php endforeach; else: ?>
                                <tr><td colspan="6" class="text-center py-4 text-muted">No bet history found.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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