<?php
require_once __DIR__ . '/auth.php';

// Check if slots_pool table exists, create if not
$pdo->exec("CREATE TABLE IF NOT EXISTS `slots_pool` (
    `id` TINYINT UNSIGNED NOT NULL PRIMARY KEY DEFAULT 1,
    `balance` DECIMAL(18,2) NOT NULL DEFAULT 0.00,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

// Fetch Slots Pool Balance
$pool_st = $pdo->query("SELECT balance FROM slots_pool WHERE id=1");
$pool_balance = $pool_st ? (float)$pool_st->fetchColumn() : 0.00;

// Update Pool Balance (Admin Action)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'add_funds') {
        $amount = (float)$_POST['amount'];
        if ($amount > 0) {
            // insert ignore in case it doesn't exist
            $pdo->exec("INSERT IGNORE INTO slots_pool (id, balance) VALUES (1, 0)");
            $stmt = $pdo->prepare("UPDATE slots_pool SET balance = balance + ? WHERE id=1");
            $stmt->execute([$amount]);
            $success = "Successfully added PKR " . number_format($amount, 2) . " to the Slots Pool.";
        } else {
            $error = "Amount must be greater than zero.";
        }
    } elseif ($_POST['action'] === 'remove_funds') {
        $amount = (float)$_POST['amount'];
        if ($amount > 0 && $amount <= $pool_balance) {
            $stmt = $pdo->prepare("UPDATE slots_pool SET balance = balance - ? WHERE id=1");
            $stmt->execute([$amount]);
            $success = "Successfully removed PKR " . number_format($amount, 2) . " from the Slots Pool.";
        } else {
            $error = "Invalid amount or insufficient pool balance.";
        }
    }
    // Refresh balance
    $pool_st = $pdo->query("SELECT balance FROM slots_pool WHERE id=1");
    $pool_balance = $pool_st ? (float)$pool_st->fetchColumn() : 0.00;
}

// Fetch recent bets
$bets_st = $pdo->query("
    SELECT s.*, u.phone 
    FROM slots_games s 
    JOIN users u ON s.user_id = u.id 
    ORDER BY s.id DESC LIMIT 50
");
$recent_bets = $bets_st ? $bets_st->fetchAll() : [];

$page_title = 'Slots Game Management';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?= $page_title ?> - Admin</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
:root {
    --bg:#0f172a; --surface:#1e293b; --primary:#3b82f6; --text:#f8fafc; --text-muted:#94a3b8; --border:#334155;
    --success:#10b981; --danger:#ef4444; --warning:#f59e0b;
}
* { box-sizing:border-box; margin:0; padding:0; }
body { font-family:'Inter', sans-serif; background:var(--bg); color:var(--text); display:flex; min-height:100vh; overflow-x:hidden; }
.sidebar { width:260px; background:var(--surface); border-right:1px solid var(--border); display:flex; flex-direction:column; position:fixed; height:100vh; overflow-y:auto; z-index:10; transition:transform 0.3s ease; }
.main-content { flex:1; margin-left:260px; padding:2rem; display:flex; flex-direction:column; gap:2rem; min-width:0; }
header { display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid var(--border); padding-bottom:1rem; }
h1 { font-size:1.75rem; font-weight:700; color:#fff; }
.card { background:var(--surface); border-radius:12px; padding:1.5rem; border:1px solid var(--border); box-shadow:0 4px 6px -1px rgba(0,0,0,0.1); }
.card-header { font-size:1.25rem; font-weight:600; margin-bottom:1rem; border-bottom:1px solid var(--border); padding-bottom:0.75rem; display:flex; justify-content:space-between; align-items:center; }
.stats-grid { display:grid; grid-template-columns:repeat(auto-fit, minmax(240px, 1fr)); gap:1.5rem; }
.stat-card { background:rgba(255,255,255,0.03); border:1px solid var(--border); border-radius:12px; padding:1.5rem; display:flex; flex-direction:column; gap:0.5rem; position:relative; overflow:hidden; }
.stat-value { font-size:2rem; font-weight:700; color:#fff; }
.stat-label { font-size:0.875rem; color:var(--text-muted); text-transform:uppercase; letter-spacing:0.05em; }
.alert { padding:1rem; border-radius:8px; margin-bottom:1rem; font-weight:600; }
.alert-success { background:rgba(16,185,129,0.1); color:var(--success); border:1px solid var(--success); }
.alert-danger { background:rgba(239,68,68,0.1); color:var(--danger); border:1px solid var(--danger); }
.form-group { margin-bottom:1rem; }
.form-group label { display:block; margin-bottom:0.5rem; color:var(--text-muted); font-size:0.875rem; }
.form-control { width:100%; padding:0.75rem; background:rgba(0,0,0,0.2); border:1px solid var(--border); border-radius:6px; color:#fff; font-family:inherit; }
.btn { padding:0.75rem 1.5rem; border:none; border-radius:6px; font-weight:600; cursor:pointer; transition:all 0.2s; color:#fff; }
.btn-primary { background:var(--primary); }
.btn-primary:hover { background:#2563eb; }
.btn-danger { background:var(--danger); }
.btn-danger:hover { background:#dc2626; }
.table-responsive { overflow-x:auto; }
table { width:100%; border-collapse:collapse; margin-top:1rem; }
th, td { padding:1rem; text-align:left; border-bottom:1px solid var(--border); white-space:nowrap; }
th { color:var(--text-muted); font-size:0.75rem; text-transform:uppercase; letter-spacing:0.05em; }
tbody tr:hover { background:rgba(255,255,255,0.02); }
.badge { padding:0.25rem 0.75rem; border-radius:999px; font-size:0.75rem; font-weight:600; }
.badge-win { background:rgba(16,185,129,0.1); color:var(--success); border:1px solid var(--success); }
.badge-lose { background:rgba(239,68,68,0.1); color:var(--danger); border:1px solid var(--danger); }

@media (max-width:768px) {
    .sidebar { transform:translateX(-100%); }
    .main-content { margin-left:0; padding:1rem; }
}
</style>
</head>
<body>

<?php $cur = 'Slots.php'; include 'sidebar.php'; ?>

<main class="main-content">
    <header>
        <h1><i class="fa-solid fa-slot-machine"></i> <?= $page_title ?></h1>
    </header>

    <?php if (isset($success)): ?>
        <div class="alert alert-success"><i class="fa-solid fa-check-circle"></i> <?= $success ?></div>
    <?php endif; ?>
    <?php if (isset($error)): ?>
        <div class="alert alert-danger"><i class="fa-solid fa-triangle-exclamation"></i> <?= $error ?></div>
    <?php endif; ?>

    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-label">Current Slots Pool Balance</div>
            <div class="stat-value">PKR <?= number_format($pool_balance, 2) ?></div>
            <p style="font-size:0.8rem; color:var(--text-muted); margin-top:0.5rem;">Total funds available for user payouts in Slots (70% RTP protected).</p>
        </div>
    </div>

    <div class="stats-grid">
        <div class="card">
            <div class="card-header">Add Funds to Pool</div>
            <form method="POST">
                <input type="hidden" name="action" value="add_funds">
                <div class="form-group">
                    <label>Amount (PKR)</label>
                    <input type="number" step="0.01" name="amount" class="form-control" required>
                </div>
                <button type="submit" class="btn btn-primary"><i class="fa-solid fa-plus"></i> Add to Pool</button>
            </form>
        </div>

        <div class="card">
            <div class="card-header">Remove Funds from Pool</div>
            <form method="POST">
                <input type="hidden" name="action" value="remove_funds">
                <div class="form-group">
                    <label>Amount (PKR)</label>
                    <input type="number" step="0.01" name="amount" class="form-control" required>
                </div>
                <button type="submit" class="btn btn-danger"><i class="fa-solid fa-minus"></i> Remove from Pool</button>
            </form>
        </div>
    </div>

    <div class="card">
        <div class="card-header">Recent Slots Bets</div>
        <div class="table-responsive">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>User</th>
                        <th>Bet Amount</th>
                        <th>Result</th>
                        <th>Payout</th>
                        <th>Reels</th>
                        <th>Date</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($recent_bets) > 0): ?>
                        <?php foreach ($recent_bets as $bet): ?>
                            <tr>
                                <td>#<?= $bet['id'] ?></td>
                                <td><?= htmlspecialchars($bet['phone']) ?></td>
                                <td>PKR <?= number_format($bet['bet_amount'], 2) ?></td>
                                <td>
                                    <?php if ($bet['is_win']): ?>
                                        <span class="badge badge-win">WIN (<?= $bet['multiplier'] ?>x)</span>
                                    <?php else: ?>
                                        <span class="badge badge-lose">LOSE</span>
                                    <?php endif; ?>
                                </td>
                                <td>PKR <?= number_format($bet['payout'], 2) ?></td>
                                <td style="font-size:11px; color:#ccc;">
                                    <?= htmlspecialchars($bet['reel1']) ?><br>
                                    <?= htmlspecialchars($bet['reel2']) ?><br>
                                    <?= htmlspecialchars($bet['reel3']) ?>
                                </td>
                                <td><?= date('M d, H:i', strtotime($bet['created_at'])) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="7" style="text-align:center;">No recent bets found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

</body>
</html>
