<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/auth.php';

// Auto-create tables if they don't exist yet
$pdo->exec("
CREATE TABLE IF NOT EXISTS mines_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 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS mines_games (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id INT(11) NOT NULL,
    bet DECIMAL(18,2) NOT NULL,
    mine_count TINYINT UNSIGNED NOT NULL DEFAULT 3,
    rows_c TINYINT UNSIGNED NOT NULL DEFAULT 5,
    cols_c TINYINT UNSIGNED NOT NULL DEFAULT 5,
    safe_clicks TINYINT UNSIGNED NOT NULL DEFAULT 0,
    clicked_tiles JSON NOT NULL DEFAULT '[]',
    board_mines JSON NOT NULL DEFAULT '[]',
    is_over TINYINT(1) NOT NULL DEFAULT 0,
    is_win TINYINT(1) DEFAULT NULL,
    payout DECIMAL(18,2) NOT NULL DEFAULT 0.00,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    ended_at DATETIME DEFAULT NULL,
    INDEX idx_user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
");

// Fetch Mines Pool Balance
$pool_st = $pdo->query("SELECT balance FROM mines_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['update_pool'])) {
    $new_pool = (float)$_POST['pool_balance'];
    $pdo->prepare("UPDATE mines_pool SET balance = ? WHERE id = 1")->execute([$new_pool]);
    header("Location: Mines.php?success=Pool updated");
    exit;
}

// Fetch recent games
$recent_games = $pdo->query("
    SELECT m.*, u.number, u.member_name 
    FROM mines_games m 
    JOIN users u ON m.user_id = u.id 
    ORDER BY m.id DESC LIMIT 50
")->fetchAll(PDO::FETCH_ASSOC);

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Mines Admin — PakClub Admin</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{background:#0b0e18;color:#e8eaf0;font-family:'Segoe UI',sans-serif;display:flex;min-height:100vh}
.main{flex:1;overflow-x:hidden}
.topbar{background:#111827;border-bottom:1px solid rgba(255,255,255,.07);padding:16px 28px;display:flex;align-items:center;justify-content:space-between}
.topbar h2{font-size:20px;font-weight:700;color:#fff}
.content{padding:24px 28px}
.card{background:#1e2130;border:1px solid rgba(255,255,255,.07);border-radius:14px;overflow:hidden;overflow-x:auto;margin-bottom:24px}
.card-header{padding:16px 20px;border-bottom:1px solid rgba(255,255,255,.07);background:#181b28;display:flex;justify-content:space-between;align-items:center}
.card-title{font-size:16px;font-weight:600;color:#fff}
.card-body{padding:20px}

.form-group{margin-bottom:15px}
.form-group label{display:block;margin-bottom:6px;font-size:13px;color:#9ca3af;font-weight:500}
.form-control{width:100%;background:#0f1117;border:1px solid rgba(255,255,255,.1);border-radius:8px;padding:10px 14px;color:#fff;font-size:14px;outline:none;font-family:inherit}
.form-control:focus{border-color:#f26d0f}

.btn{padding:10px 18px;border-radius:10px;border:none;cursor:pointer;font-size:14px;font-weight:600;display:inline-flex;align-items:center;gap:7px;transition:opacity .2s}
.btn:hover{opacity:.85}
.btn-orange{background:#f26d0f;color:#fff}

table{width:100%;border-collapse:collapse;font-size:13px;min-width:600px;}
th{padding:11px 16px;color:#4b5563;font-size:11px;text-transform:uppercase;letter-spacing:.7px;border-bottom:1px solid rgba(255,255,255,.06);text-align:left;font-weight:600}
td{padding:12px 16px;border-bottom:1px solid rgba(255,255,255,.04);color:#c9ccd6;vertical-align:middle}
tr:last-child td{border-bottom:none}
tr:hover td{background:rgba(255,255,255,.02)}

.badge{padding:4px 8px;border-radius:4px;font-size:11px;font-weight:700;text-transform:uppercase}
.bg-danger{background:rgba(239,68,68,.15);color:#ef4444}
.bg-warning{background:rgba(245,158,11,.15);color:#f59e0b}
.bg-success{background:rgba(34,197,94,.15);color:#22c55e}
.bg-primary{background:rgba(59,130,246,.15);color:#3b82f6}

.alert{padding:15px;background:rgba(34,197,94,.15);color:#22c55e;border-radius:10px;margin-bottom:20px;border:1px solid rgba(34,197,94,.3)}
</style>
</head>
<body>
<?php include 'sidebar.php'; ?>
<div class="main">
    <div class="topbar">
        <h2><i class="fa-solid fa-bomb" style="color:#f26d0f;margin-right:10px"></i>Mines Admin</h2>
    </div>
    
    <div class="content">
        <?php if (isset($_GET['success'])): ?>
            <div class="alert"><i class="fa-solid fa-check-circle"></i> <?php echo htmlspecialchars($_GET['success']); ?></div>
        <?php endif; ?>

        <div class="card" style="max-width: 600px;">
            <div class="card-header">
                <div class="card-title">Manage Profit Pool</div>
            </div>
            <div class="card-body">
                <p style="margin-bottom:15px;font-size:15px">Current Mines Pool Balance: <strong style="color:#22c55e">Rs <?php echo number_format($pool_balance, 2); ?></strong></p>
                <form method="POST">
                    <div class="form-group">
                        <label>Set Pool Balance Manually</label>
                        <input type="number" step="any" name="pool_balance" class="form-control" value="<?= $pool_balance ?>" required>
                    </div>
                    <button type="submit" name="update_pool" class="btn btn-orange"><i class="fa-solid fa-floppy-disk"></i> Save Pool</button>
                </form>
                <hr style="border:none;border-top:1px solid rgba(255,255,255,.07);margin:20px 0">
                <div style="font-size:12px;color:#9ca3af">The dynamic logic guarantees users cannot win more than 70% of this pool. Add funds here to allow users to hit higher multipliers.</div>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <div class="card-title">Recent 50 Games</div>
            </div>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>User</th>
                        <th>Bet Amount</th>
                        <th>Clicks</th>
                        <th>Status</th>
                        <th>Payout</th>
                        <th>Date</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($recent_games as $g): ?>
                        <tr>
                            <td>#<?= $g['id'] ?></td>
                            <td><?= htmlspecialchars($g['member_name'] ?? 'Unknown') ?> <br><small style="color: #9ca3af;"><?= htmlspecialchars($g['number'] ?? '') ?></small></td>
                            <td style="font-weight:600">Rs <?= number_format($g['bet'], 2) ?></td>
                            <td><?= $g['safe_clicks'] ?></td>
                            <td>
                                <?php if($g['is_over'] == 0): ?>
                                    <span class="badge bg-warning">Playing</span>
                                <?php elseif($g['is_win'] == 1): ?>
                                    <span class="badge bg-success">Cashed Out</span>
                                <?php else: ?>
                                    <span class="badge bg-danger">Lost</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if($g['is_win'] == 1): ?>
                                    <span style="color: #4ade80;">+Rs <?= number_format($g['payout'], 2) ?></span>
                                <?php else: ?>
                                    <span style="color: #f87171;">-Rs <?= number_format($g['bet'], 2) ?></span>
                                <?php endif; ?>
                            </td>
                            <td style="font-size:12px;color:#9ca3af"><?= $g['created_at'] ?></td>
                        </tr>
                    <?php endforeach; ?>
                    <?php if(empty($recent_games)): ?>
                        <tr><td colspan="7" style="text-align: center;padding:30px;color:#9ca3af">No games played yet.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>