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

requireLogin();
$user   = getConnectedUser($pdo);
$userId = (int)$user['id'];

// Bloquer les mineurs
$isMinorW = (bool)($user['is_minor'] ?? false);
if (!$isMinorW && !empty($user['birthdate'])) {
    $age = (new DateTime())->diff(new DateTime($user['birthdate']))->y;
    $isMinorW = $age < 18;
}
if ($isMinorW) {
    include 'header.php';
    echo '<div class="container mt-5 text-center">
        <div class="card bg-dark border-warning p-4 mx-auto" style="max-width:420px;">
            <div class="text-warning fw-bold mb-2" style="font-size:1.1rem;">🔒 Accès restreint</div>
            <div class="text-muted small">Le portefeuille de jetons n\'est pas disponible pour les membres de moins de 18 ans.</div>
            <a href="index.php" class="btn btn-outline-secondary btn-sm mt-3">← Retour</a>
        </div>
    </div>';
    include 'footer.php';
    exit;
}

// Helper config
function walletCfg($pdo, $key, $default = 0) {
    try {
        $s = $pdo->prepare("SELECT config_value FROM admin_config WHERE config_key=?");
        $s->execute([$key]);
        $v = $s->fetchColumn();
        return $v !== false ? $v : $default;
    } catch (Exception $e) { return $default; }
}

// Vérifier que les colonnes existent
try {
    $pdo->exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS wallet_points INT(11) DEFAULT 0");
    $pdo->exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS last_daily_bonus DATE DEFAULT NULL");
    $pdo->exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS last_daily_roll DATE DEFAULT NULL");
    $pdo->exec("CREATE TABLE IF NOT EXISTS wallet_transactions (
        id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
        user_id INT(11) NOT NULL,
        amount INT(11) NOT NULL,
        type ENUM('daily_bonus','daily_roll','bet_win','bet_lose','purchase','admin_grant','bet_stake') NOT NULL,
        description VARCHAR(255) DEFAULT NULL,
        ref_id INT(11) DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
} catch (Exception $e) {}

// Recharger user avec wallet_points
$uStmt = $pdo->prepare("SELECT * FROM users WHERE id=?");
$uStmt->execute([$userId]);
$user = $uStmt->fetch();

$walletEnabled = (int)walletCfg($pdo, 'wallet_enabled', 1);
if (!$walletEnabled) {
    include 'header.php';
    echo '<div class="container mt-4"><div class="alert alert-warning">Le portefeuille est désactivé.</div></div>';
    include 'footer.php';
    exit;
}

$tier = $user['tier'] ?? 'free';
$isAdminU = (int)($user['admin'] ?? 0) === 1;

// Bonus journalier selon forfait
$dailyBonus = match(true) {
    $isAdminU || $tier === 'premium_plus' => (int)walletCfg($pdo, 'wallet_daily_premplus', 200),
    $tier === 'premium'                   => (int)walletCfg($pdo, 'wallet_daily_premium', 150),
    default                               => (int)walletCfg($pdo, 'wallet_daily_free', 100),
};

$msg = ''; $error = ''; $rollResult = null;

// Roulette
if (isset($_POST['spin_roulette'])) {
    $today = date('Y-m-d');
    $lastRoll = $user['last_daily_roll'] ?? '';
    if ($lastRoll === $today) {
        $error = "Tu as déjà tourné la roulette aujourd'hui !";
    } else {
        $rollMin = (int)walletCfg($pdo, 'wallet_roll_min', 10);
        $rollMax = (int)walletCfg($pdo, 'wallet_roll_max', 500);
        // Pondération : petits gains plus fréquents
        $ranges = [
            [$rollMin, (int)($rollMax*0.1), 40],   // 40% chance : petit gain
            [(int)($rollMax*0.1), (int)($rollMax*0.3), 35],  // 35% : moyen
            [(int)($rollMax*0.3), (int)($rollMax*0.6), 20],  // 20% : bon
            [(int)($rollMax*0.6), $rollMax, 5],               // 5% : jackpot
        ];
        $rand = rand(1, 100);
        $cumul = 0;
        $rollResult = $rollMin;
        foreach ($ranges as [$min, $max, $pct]) {
            $cumul += $pct;
            if ($rand <= $cumul) { $rollResult = rand($min, $max); break; }
        }
        $pdo->prepare("UPDATE users SET wallet_points=wallet_points+?, last_daily_roll=? WHERE id=?")
            ->execute([$rollResult, $today, $userId]);
        $pdo->prepare("INSERT INTO wallet_transactions (user_id,amount,type,description) VALUES (?,?,?,?)")
            ->execute([$userId, $rollResult, 'daily_roll', "Roulette du {$today}"]);
        $msg = "La roulette donne : +{$rollResult} jetons !";
        $user['wallet_points'] = ($user['wallet_points'] ?? 0) + $rollResult;
        $user['last_daily_roll'] = $today;
    }
}

// Historique
try {
    $histStmt = $pdo->prepare("SELECT * FROM wallet_transactions WHERE user_id=? ORDER BY id DESC LIMIT 20");
    $histStmt->execute([$userId]);
    $history = $histStmt->fetchAll();
} catch (Exception $e) { $history = []; }

// Classement wallet
try {
    $rankStmt = $pdo->query("SELECT id, username, wallet_points FROM users WHERE wallet_points > 0 ORDER BY wallet_points DESC LIMIT 10");
    $walletRank = $rankStmt->fetchAll();
} catch (Exception $e) { $walletRank = []; }

$today = date('Y-m-d');
$canBonus = ($user['last_daily_bonus'] ?? '') !== $today;
$canRoll  = ($user['last_daily_roll']  ?? '') !== $today;
$walletPts = (int)($user['wallet_points'] ?? 0);

include 'header.php';
?>

<div class="container mt-4 px-4">
    <div class="d-flex align-items-center gap-3 mb-4">
        <a href="index.php" class="btn btn-outline-secondary btn-sm">&larr; Retour</a>
        <h5 class="text-warning fw-bold mb-0">Portefeuille de Jetons</h5>
        <a href="wallet_shop.php" class="btn btn-warning btn-sm fw-bold ms-auto">Acheter des jetons</a>
    </div>

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

    <div class="row g-3">
        <!-- SOLDE + ACTIONS -->
        <div class="col-md-4">
            <!-- Solde -->
            <div class="card bg-dark border-warning shadow text-center p-3 mb-3">
                <div class="text-muted small mb-1">Ton solde</div>
                <div class="text-warning fw-bold" style="font-size:2.2rem;"><?= number_format($walletPts) ?></div>
                <div class="text-muted small">jetons</div>
                <hr class="border-secondary my-2">
                <div class="text-muted" style="font-size:0.65rem;">
                    Bonus journalier : <span class="text-warning"><?= $dailyBonus ?> jetons</span>
                    <span class="text-muted">(forfait <?= strtoupper($tier) ?>)</span>
                </div>
            </div>

            <!-- Bonus journalier -->
            <div class="card bg-dark border-success shadow p-3 mb-3">
                <div class="text-white fw-bold small mb-2">Bonus de connexion</div>
                <div class="text-muted small mb-2">Automatiquement crédité à ta première connexion de la journée.</div>
                <div class="d-flex align-items-center justify-content-between">
                    <span style="color:#aaa;font-size:0.75rem;">+<?= $dailyBonus ?> jetons/jour</span>
                    <?php if (!$canBonus): ?>
                    <span class="badge bg-success" style="font-size:0.62rem;">Recu aujourd'hui !</span>
                    <?php else: ?>
                    <span class="badge bg-secondary" style="font-size:0.62rem;">Pas encore connecte</span>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Roulette -->
            <div class="card bg-dark border-info shadow p-3">
                <div class="text-white fw-bold small mb-2">Roulette quotidienne</div>
                <div style="color:#aaa;font-size:0.72rem;margin-bottom:8px;">
                    Entre <?= walletCfg($pdo,'wallet_roll_min',10) ?> et <?= walletCfg($pdo,'wallet_roll_max',500) ?> jetons
                </div>

                <!-- Roue visuelle -->
                <div style="position:relative;height:52px;overflow:hidden;background:#0a0a0a;border-radius:6px;border:1px solid #0dcaf0;margin-bottom:8px;display:flex;align-items:center;justify-content:center;">
                    <div id="rouletteNumbers" style="display:flex;gap:18px;font-size:1.3rem;font-weight:bold;color:#0dcaf0;"></div>
                    <div style="position:absolute;top:0;bottom:0;left:50%;transform:translateX(-50%);width:2px;background:#ffc107;pointer-events:none;"></div>
                </div>

                <div id="rollResult" style="display:none;" class="alert alert-warning py-1 text-center fw-bold mb-2" style="font-size:1.1rem;"></div>

                <?php if ($rollResult !== null): ?>
                <div class="alert alert-warning py-1 text-center fw-bold mb-2">+<?= $rollResult ?> jetons !</div>
                <?php endif; ?>

                <form method="POST" id="rollForm">
                    <input type="hidden" name="spin_roulette" value="1" id="spinInput" disabled>
                    <button type="button" id="spinBtn"
                            class="btn btn-info fw-bold w-100 <?= !$canRoll ? 'disabled' : '' ?>"
                            <?= !$canRoll ? 'disabled' : '' ?>
                            onclick="<?= $canRoll ? 'spinRoulette()' : '' ?>">
                        <?= $canRoll ? 'TOURNER LA ROULETTE' : 'Deja tourne aujourd\'hui' ?>
                    </button>
                </form>
                <?php if (!$canRoll): ?>
                <small style="color:#aaa;font-size:0.62rem;">Revient demain a minuit</small>
                <?php endif; ?>
            </div>
        </div>

        <!-- HISTORIQUE -->
        <div class="col-md-4">
            <div class="card bg-dark border-secondary shadow h-100">
                <div class="card-header text-info fw-bold small py-2">Historique des transactions</div>
                <div class="card-body p-0" style="overflow-y:auto;max-height:400px;">
                    <?php if (empty($history)): ?>
                    <div class="text-muted text-center py-3 small">Aucune transaction.</div>
                    <?php else: ?>
                    <?php foreach ($history as $h):
                        $typeIcon = match($h['type']) {
                            'daily_bonus' => '+',
                            'daily_roll'  => '*',
                            'bet_win'     => 'W',
                            'bet_lose'    => 'L',
                            'purchase'    => '$',
                            'admin_grant' => 'A',
                            'bet_stake'   => 'S',
                            default       => '?'
                        };
                        $isPos = $h['amount'] > 0;
                    ?>
                    <div class="d-flex align-items-center gap-2 px-2 py-1 border-bottom border-secondary">
                        <span class="badge bg-secondary" style="font-size:0.55rem;min-width:18px;"><?= $typeIcon ?></span>
                        <div class="flex-grow-1">
                            <div style="font-size:0.68rem;color:#ddd;"><?= htmlspecialchars($h['description'] ?? $h['type']) ?></div>
                            <div style="font-size:0.58rem;color:#666;"><?= date('d M H:i', strtotime($h['created_at'])) ?></div>
                        </div>
                        <span class="fw-bold <?= $isPos ? 'text-success' : 'text-danger' ?>" style="font-size:0.8rem;">
                            <?= $isPos ? '+' : '' ?><?= number_format($h['amount']) ?>
                        </span>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- CLASSEMENT -->
        <div class="col-md-4">
            <div class="card bg-dark border-warning shadow">
                <div class="card-header text-warning fw-bold small py-2">Classement Jetons</div>
                <table class="table table-dark table-sm small mb-0">
                    <thead><tr><th>#</th><th>Membre</th><th class="text-end">Jetons</th></tr></thead>
                    <tbody>
                    <?php foreach ($walletRank as $i => $wr):
                        $medals = ['&#127881;','&#129352;','&#129353;'];
                        $icon = $medals[$i] ?? ($i+1).'.';
                    ?>
                    <tr class="<?= $wr['id']==$userId ? 'table-warning' : '' ?>">
                        <td><?= $icon ?></td>
                        <td class="text-white"><?= htmlspecialchars($wr['username']) ?></td>
                        <td class="text-end text-warning fw-bold"><?= number_format($wr['wallet_points']) ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($walletRank)): ?>
                    <tr><td colspan="3" class="text-center text-muted py-2">Aucun joueur</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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

<script>
// Roulette animation
const rollMin = <?= (int)walletCfg($pdo,'wallet_roll_min',10) ?>;
const rollMax = <?= (int)walletCfg($pdo,'wallet_roll_max',500) ?>;

function randomNum() { return Math.floor(Math.random() * (rollMax - rollMin + 1)) + rollMin; }

function initWheel() {
    const el = document.getElementById('rouletteNumbers');
    if (!el) return;
    let html = '';
    for (let i = 0; i < 7; i++) html += '<span>' + randomNum() + '</span>';
    el.innerHTML = html;
}

function spinRoulette() {
    const btn = document.getElementById('spinBtn');
    if (btn) btn.disabled = true;

    let speed = 50, count = 0, maxCount = 40;
    const el = document.getElementById('rouletteNumbers');

    function tick() {
        if (!el) return;
        let html = '';
        for (let i = 0; i < 7; i++) html += '<span>' + randomNum() + '</span>';
        el.innerHTML = html;
        count++;
        if (count < maxCount) {
            speed = count < 20 ? 50 : 50 + (count - 20) * 15;
            setTimeout(tick, speed);
        } else {
            // Soumettre le formulaire
            const input = document.getElementById('spinInput');
            if (input) input.disabled = false;
            document.getElementById('rollForm').submit();
        }
    }
    tick();
}

initWheel();
</script>
