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

requireLogin();
$user = getConnectedUser($pdo);
requireAdmin($user);

$msg = '';

$cfgKeys = [
    'wallet_enabled'        => ['Activer le système de jetons',          1],
    'wallet_daily_free'     => ['Bonus quotidien — Free (jetons)',       100],
    'wallet_daily_premium'  => ['Bonus quotidien — Premium (jetons)',    150],
    'wallet_daily_premplus' => ['Bonus quotidien — Premium+ (jetons)',   200],
    'wallet_bet_enabled'    => ['Activer gages avec jetons',             0],
    'wallet_bet_max'        => ['Mise maximum par gage (jetons)',         500],
    'wallet_roll_min'       => ['Roulette — Gain minimum',               10],
    'wallet_roll_max'       => ['Roulette — Gain maximum',               500],
    'wallet_shop_enabled'   => ['Activer boutique de jetons',            1],
];

// Packages boutique
$shopPackages = [
    ['pts' => 100,  'price' => '1.99$'],
    ['pts' => 300,  'price' => '4.99$'],
    ['pts' => 700,  'price' => '9.99$'],
    ['pts' => 1500, 'price' => '19.99$'],
];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_wallet'])) {
    foreach ($cfgKeys as $key => [$label, $default]) {
        $val = $_POST[$key] ?? $default;
        $ex = $pdo->prepare("SELECT config_key FROM admin_config WHERE config_key=?");
        $ex->execute([$key]);
        if ($ex->fetch()) $pdo->prepare("UPDATE admin_config SET config_value=? WHERE config_key=?")->execute([$val, $key]);
        else $pdo->prepare("INSERT INTO admin_config (config_key,config_value) VALUES (?,?)")->execute([$key, $val]);
    }
    $msg = "Configuration sauvegardée !";
}

// Octroyer des jetons manuellement
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['grant_points'])) {
    $grantUser = trim($_POST['grant_username'] ?? '');
    $grantAmt  = (int)$_POST['grant_amount'];
    if ($grantUser && $grantAmt) {
        $uStmt = $pdo->prepare("SELECT id, username FROM users WHERE username=?");
        $uStmt->execute([$grantUser]);
        $grantRow = $uStmt->fetch();
        if ($grantRow) {
            $pdo->prepare("UPDATE users SET wallet_points=wallet_points+? WHERE id=?")->execute([$grantAmt, $grantRow['id']]);
            $pdo->prepare("INSERT INTO wallet_transactions (user_id,amount,type,description) VALUES (?,?,?,?)")
                ->execute([$grantRow['id'], $grantAmt, 'admin_grant', "Octroyé par admin"]);
            $msg = "{$grantAmt} jetons octroyés à {$grantRow['username']} !";
        } else { $msg = "Utilisateur introuvable."; }
    }
}

// Charger config actuelle
$currentVals = [];
foreach ($cfgKeys as $key => [$label, $default]) {
    $s = $pdo->prepare("SELECT config_value FROM admin_config WHERE config_key=?");
    $s->execute([$key]);
    $row = $s->fetch();
    $currentVals[$key] = $row ? $row['config_value'] : $default;
}

// Stats
try {
    $totalWallet = $pdo->query("SELECT SUM(wallet_points) FROM users")->fetchColumn() ?? 0;
    $topWallet   = $pdo->query("SELECT username, wallet_points FROM users ORDER BY wallet_points DESC LIMIT 5")->fetchAll();
    $txToday     = $pdo->query("SELECT COUNT(*) FROM wallet_transactions WHERE DATE(created_at)=CURDATE()")->fetchColumn() ?? 0;
} catch (Exception $e) { $totalWallet = 0; $topWallet = []; $txToday = 0; }

include 'header.php';
?>

<div class="container mt-4 px-4">
    <div class="d-flex align-items-center gap-3 mb-4">
        <a href="admin.php" class="btn btn-outline-secondary btn-sm">&larr; Admin</a>
        <h5 class="text-warning fw-bold mb-0">Gestion du Portefeuille de Jetons</h5>
    </div>

    <?php if ($msg): ?><div class="alert alert-success py-2 small"><?= $msg ?></div><?php endif; ?>

    <div class="row g-3 mb-4">
        <div class="col-md-4 text-center">
            <div class="card bg-dark border-warning p-3">
                <div class="text-warning fw-bold" style="font-size:1.6rem;"><?= number_format($totalWallet) ?></div>
                <div class="text-muted small">Jetons en circulation</div>
            </div>
        </div>
        <div class="col-md-4 text-center">
            <div class="card bg-dark border-info p-3">
                <div class="text-info fw-bold" style="font-size:1.6rem;"><?= $txToday ?></div>
                <div class="text-muted small">Transactions aujourd'hui</div>
            </div>
        </div>
        <div class="col-md-4 text-center">
            <div class="card bg-dark border-success p-3">
                <div class="text-success fw-bold" style="font-size:1.6rem;"><?= (int)$currentVals['wallet_enabled'] ? 'ACTIF' : 'INACTIF' ?></div>
                <div class="text-muted small">Statut système</div>
            </div>
        </div>
    </div>

    <div class="row g-3">
        <!-- CONFIG -->
        <div class="col-md-7">
            <div class="card bg-dark border-secondary shadow">
                <div class="card-header text-warning fw-bold small py-2">Configuration</div>
                <div class="card-body">
                    <form method="POST">
                        <?php foreach ($cfgKeys as $key => [$label, $default]): ?>
                        <div class="row align-items-center mb-2">
                            <div class="col-8">
                                <label class="text-white small"><?= $label ?></label>
                            </div>
                            <div class="col-4">
                                <?php if (in_array($key, ['wallet_enabled','wallet_bet_enabled','wallet_shop_enabled'])): ?>
                                <select name="<?= $key ?>" class="form-select form-select-sm bg-dark text-white border-secondary">
                                    <option value="1" <?= $currentVals[$key]=='1'?'selected':'' ?>>Oui</option>
                                    <option value="0" <?= $currentVals[$key]=='0'?'selected':'' ?>>Non</option>
                                </select>
                                <?php else: ?>
                                <input type="number" name="<?= $key ?>" class="form-control form-control-sm bg-dark text-white border-secondary"
                                       value="<?= htmlspecialchars($currentVals[$key]) ?>" min="0">
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                        <button type="submit" name="save_wallet" class="btn btn-warning fw-bold w-100 mt-2">SAUVEGARDER</button>
                    </form>
                </div>
            </div>
        </div>

        <!-- OCTROYER + TOP -->
        <div class="col-md-5">
            <div class="card bg-dark border-success shadow mb-3">
                <div class="card-header text-success fw-bold small py-2">Octroyer des jetons</div>
                <div class="card-body">
                    <form method="POST" class="d-flex flex-column gap-2">
                        <input type="text" name="grant_username" class="form-control form-control-sm bg-dark text-white border-secondary"
                               placeholder="Nom d'utilisateur">
                        <input type="number" name="grant_amount" class="form-control form-control-sm bg-dark text-white border-secondary"
                               placeholder="Quantité" min="1" value="100">
                        <button type="submit" name="grant_points" class="btn btn-success btn-sm fw-bold">Octroyer</button>
                    </form>
                </div>
            </div>

            <div class="card bg-dark border-warning shadow">
                <div class="card-header text-warning fw-bold small py-2">Top Jetons</div>
                <table class="table table-dark table-sm small mb-0">
                    <tbody>
                    <?php foreach ($topWallet as $i => $t): ?>
                    <tr>
                        <td class="text-muted"><?= $i+1 ?>.</td>
                        <td class="text-white"><?= htmlspecialchars($t['username']) ?></td>
                        <td class="text-end text-warning"><?= number_format($t['wallet_points']) ?></td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>
