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

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

// Bloquer les mineurs
$isMinor = (bool)($user['is_minor'] ?? false);
if (!$isMinor && !empty($user['birthdate'])) {
    $age = (new DateTime())->diff(new DateTime($user['birthdate']))->y;
    $isMinor = $age < 18;
}
if ($isMinor) {
    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">La boutique 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;
}

// Vérifier que la boutique est active
$shopEnabled = (int)getWalletConfig($pdo, 'wallet_shop_enabled', 1);

$msg = ''; $error = '';

// Packages disponibles — configurables via admin_wallet
// Format: [jetons, prix_affiche, prix_cents]
$packages = [
    ['id' => 1, 'jetons' => 100,  'price' => '1.99$',  'label' => 'Starter',  'color' => 'secondary'],
    ['id' => 2, 'jetons' => 300,  'price' => '4.99$',  'label' => 'Standard', 'color' => 'info'],
    ['id' => 3, 'jetons' => 700,  'price' => '9.99$',  'label' => 'Premium',  'color' => 'warning'],
    ['id' => 4, 'jetons' => 1500, 'price' => '19.99$', 'label' => 'Mega',     'color' => 'danger'],
];

// Simuler un achat (sans vrai paiement)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['buy_package'])) {
    $pkgId = (int)$_POST['package_id'];
    $pkg   = null;
    foreach ($packages as $p) {
        if ($p['id'] === $pkgId) { $pkg = $p; break; }
    }

    if ($pkg && $shopEnabled) {
        try {
            // Ajouter les jetons
            $pdo->prepare("UPDATE users SET wallet_points=wallet_points+? WHERE id=?")->execute([$pkg['jetons'], $userId]);
            $pdo->prepare("INSERT INTO wallet_transactions (user_id,amount,type,description) VALUES (?,?,?,?)")
                ->execute([$userId, $pkg['jetons'], 'purchase', "Achat package {$pkg['label']} ({$pkg['price']})"]);

            // Recharger user
            $user = getConnectedUser($pdo);
            $msg  = "Achat simule ! +{$pkg['jetons']} jetons cредités. (Aucun montant reel preleve)";
        } catch (Exception $e) { $error = $e->getMessage(); }
    }
}

// Recharger wallet
$walletPts = (int)($user['wallet_points'] ?? 0);

// Historique achats
try {
    $hist = $pdo->prepare("SELECT * FROM wallet_transactions WHERE user_id=? AND type='purchase' ORDER BY id DESC LIMIT 10");
    $hist->execute([$userId]);
    $purchases = $hist->fetchAll();
} catch (Exception $e) { $purchases = []; }

// Message si redirigé depuis bet_accept (manque de jetons)
$needJetons = (int)($_GET['need'] ?? 0);
$betIdRef   = (int)($_GET['bet'] ?? 0);
$walletError = $_SESSION['wallet_error'] ?? '';
unset($_SESSION['wallet_error']);

include 'header.php';
?>
<?php if ($needJetons > 0 || $walletError): ?>
<div class="alert alert-warning alert-dismissible fade show mx-3 mt-3" style="background:rgba(255,193,7,0.1);border:1px solid #ffc107;">
    <i class="fa-solid fa-coins me-2 text-warning"></i>
    <?php if ($walletError): ?>
        <?= htmlspecialchars($walletError) ?>
    <?php else: ?>
        Il vous faut <strong><?= $needJetons ?> jetons</strong> pour accepter ce gage.
        <?php if ($betIdRef): ?> <a href="bet_accept.php?id=<?=$betIdRef?>&action=refuse" class="btn btn-sm btn-outline-secondary ms-2" style="font-size:0.7rem;">Refuser le gage</a><?php endif; ?>
    <?php endif; ?>
    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="container mt-4 px-4">
    <div class="d-flex align-items-center gap-3 mb-4">
        <a href="wallet.php" class="btn btn-outline-secondary btn-sm">&larr; Portefeuille</a>
        <h5 class="text-warning fw-bold mb-0">Boutique de Jetons</h5>
        <span class="badge bg-warning text-dark"><?= number_format($walletPts) ?> jetons</span>
    </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; ?>

    <?php if (!$shopEnabled): ?>
    <div class="alert alert-warning">La boutique est temporairement fermee.</div>
    <?php else: ?>

    <div class="alert alert-info small py-2 mb-4">
        Achat simule — aucun montant reel preleve pour l'instant. Les jetons sont credites immediatement.
    </div>

    <div class="row g-3 mb-4">
        <?php foreach ($packages as $pkg): ?>
        <div class="col-6 col-md-3">
            <div class="card bg-dark border-<?= $pkg['color'] ?> shadow h-100 text-center">
                <?php if ($pkg['id'] === 3): ?>
                <div class="py-1 fw-bold text-dark bg-<?= $pkg['color'] ?>" style="font-size:0.65rem;border-radius:4px 4px 0 0;">POPULAIRE</div>
                <?php endif; ?>
                <div class="card-body py-3">
                    <div class="text-<?= $pkg['color'] ?> fw-bold mb-1" style="font-size:0.8rem;"><?= $pkg['label'] ?></div>
                    <div class="text-warning fw-bold" style="font-size:2rem;line-height:1;"><?= number_format($pkg['jetons']) ?></div>
                    <div class="text-muted small mb-3">jetons</div>
                    <div class="text-white fw-bold" style="font-size:1.1rem;"><?= $pkg['price'] ?></div>
                    <div class="text-muted" style="font-size:0.6rem;">
                        <?= round($pkg['jetons'] / (float)$pkg['price']) ?> jetons/$
                    </div>
                </div>
                <div class="card-footer border-secondary bg-transparent pb-3">
                    <form method="POST">
                        <input type="hidden" name="package_id" value="<?= $pkg['id'] ?>">
                        <button type="submit" name="buy_package"
                                class="btn btn-<?= $pkg['color'] ?> fw-bold w-100 btn-sm"
                                onclick="return confirm('Acheter <?= $pkg['jetons'] ?> jetons pour <?= $pkg['price'] ?> ? (Simulation)')">
                            ACHETER
                        </button>
                    </form>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- Historique achats -->
    <?php if (!empty($purchases)): ?>
    <div class="card bg-dark border-secondary shadow">
        <div class="card-header text-muted fw-bold small py-2">Historique des achats</div>
        <div class="table-responsive">
            <table class="table table-dark table-sm small mb-0">
                <thead><tr><th>Date</th><th>Package</th><th class="text-end">Jetons</th></tr></thead>
                <tbody>
                <?php foreach ($purchases as $p): ?>
                <tr>
                    <td class="text-muted" style="font-size:0.65rem;"><?= date('d M Y H:i', strtotime($p['created_at'])) ?></td>
                    <td><?= htmlspecialchars($p['description']) ?></td>
                    <td class="text-end text-success fw-bold">+<?= number_format($p['amount']) ?></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <?php endif; ?>
</div>

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