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

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

$itemId     = (int)($_GET['item'] ?? $_POST['item_id'] ?? 0);
$payMethod  = $_POST['pay_method'] ?? 'money'; // 'money' ou 'jetons'

// Charger l'article
$item = null;
if ($itemId) {
    try { $pdo->exec("ALTER TABLE store_items ADD COLUMN IF NOT EXISTS price_jetons INT DEFAULT 0"); } catch(Exception $e){}
    $stmt = $pdo->prepare("SELECT * FROM store_items WHERE id=? AND is_active=1 LIMIT 1");
    $stmt->execute([$itemId]);
    $item = $stmt->fetch();
}
if (!$item) { header("Location: store.php"); exit; }

$priceJetons = (int)($item['price_jetons'] ?? 0);
$priceMoney  = (float)($item['is_on_sale'] && $item['sale_price'] > 0 ? $item['sale_price'] : $item['price']);
$myWallet    = (int)$pdo->query("SELECT wallet_points FROM users WHERE id=$userId")->fetchColumn();

// Traitement achat en jetons
if ($_SERVER['REQUEST_METHOD']==='POST' && $payMethod === 'jetons') {
    if ($priceJetons <= 0) {
        $error = "Cet article n'est pas disponible en jetons.";
    } elseif ($myWallet < $priceJetons) {
        $error = "Solde insuffisant. Vous avez $myWallet jetons, il en faut $priceJetons.";
    } else {
        // Débiter les jetons
        $pdo->prepare("UPDATE users SET wallet_points=wallet_points-? WHERE id=?")->execute([$priceJetons, $userId]);
        try {
            $pdo->prepare("INSERT INTO wallet_transactions (user_id,amount,type,description,ref_id) VALUES (?,?,?,?,?)")
                ->execute([$userId, -$priceJetons, 'purchase', "Achat: ".htmlspecialchars($item['name']), $itemId]);
        } catch(Exception $e){}
        // Enregistrer la vente
        $pdo->prepare("INSERT INTO store_sales (user_id, items_json, total_price, status) VALUES (?,?,?,?)")
            ->execute([$userId, json_encode([['id'=>$itemId,'qty'=>1]]), 0, 'paid']);
        addNotification($pdo, $userId, "✅ Achat confirmé : ".htmlspecialchars($item['name'])." (".$priceJetons." jetons)", "store.php");
        header("Location: store.php?bought=ok"); exit;
    }
}

include 'header.php';
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<div class="container" style="max-width:500px;margin:40px auto;">
    <div class="d-flex align-items-center gap-3 mb-4">
        <a href="store.php" class="btn btn-outline-secondary btn-sm"><i class="fa-solid fa-arrow-left fa-xs me-1"></i>Boutique</a>
        <h5 class="mb-0 text-info" style="letter-spacing:1px;"><i class="fa-solid fa-cart-shopping me-2"></i>CONFIRMATION D'ACHAT</h5>
    </div>

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

    <!-- Article -->
    <div class="card bg-dark border-secondary shadow mb-3">
        <div class="card-body d-flex gap-3 align-items-center">
            <?php if (!empty($item['image_url'])): ?>
            <img src="<?= htmlspecialchars($item['image_url']) ?>" style="width:60px;height:60px;object-fit:cover;border-radius:6px;">
            <?php endif; ?>
            <div>
                <div class="fw-bold text-white"><?= htmlspecialchars($item['name']) ?></div>
                <div class="text-muted small"><?= htmlspecialchars(substr($item['description']??'',0,80)) ?></div>
            </div>
        </div>
    </div>

    <!-- Options de paiement -->
    <div class="card bg-dark border-secondary shadow mb-4">
        <div class="card-header py-2" style="background:#050520;border-bottom:1px solid #1a1a2a;">
            <span class="fw-bold text-info" style="font-size:0.72rem;letter-spacing:1px;">CHOISIR LE MODE DE PAIEMENT</span>
        </div>
        <div class="card-body">

            <?php if ($priceMoney > 0): ?>
            <div style="background:#080810;border:1px solid #1a1a2a;border-radius:6px;padding:12px;margin-bottom:8px;">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <div class="fw-bold text-white" style="font-size:0.85rem;">Paiement en argent</div>
                        <div class="text-muted" style="font-size:0.7rem;">Carte de crédit / PayPal</div>
                    </div>
                    <div class="fw-bold text-success" style="font-size:1.1rem;"><?= number_format($priceMoney, 2) ?>$</div>
                </div>
                <form method="POST" class="mt-2">
                    <input type="hidden" name="item_id" value="<?= $itemId ?>">
                    <input type="hidden" name="pay_method" value="money">
                    <button type="submit" class="btn btn-success btn-sm w-100 fw-bold">
                        <i class="fa-solid fa-credit-card me-1"></i>Payer <?= number_format($priceMoney, 2) ?>$
                    </button>
                </form>
            </div>
            <?php endif; ?>

            <?php if ($priceJetons > 0): ?>
            <div style="background:#080810;border:1px solid <?= $myWallet>=$priceJetons?'#1a3a1a':'#3a1a1a' ?>;border-radius:6px;padding:12px;">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <div class="fw-bold text-white" style="font-size:0.85rem;">Paiement en jetons</div>
                        <div style="font-size:0.7rem;color:#999;">Votre solde : <span style="color:<?= $myWallet>=$priceJetons?'#ffc107':'#dc3545' ?>;"><?= $myWallet ?> jetons</span></div>
                    </div>
                    <div class="fw-bold text-warning" style="font-size:1.1rem;">&#9670; <?= $priceJetons ?></div>
                </div>
                <?php if ($myWallet >= $priceJetons): ?>
                <form method="POST" class="mt-2">
                    <input type="hidden" name="item_id" value="<?= $itemId ?>">
                    <input type="hidden" name="pay_method" value="jetons">
                    <button type="submit" class="btn btn-warning btn-sm w-100 fw-bold text-dark">
                        <i class="fa-solid fa-coins me-1"></i>Payer <?= $priceJetons ?> jetons
                    </button>
                </form>
                <?php else: ?>
                <div class="mt-2">
                    <div class="text-danger small mb-2">Il vous manque <?= $priceJetons - $myWallet ?> jetons.</div>
                    <a href="wallet_shop.php" class="btn btn-outline-warning btn-sm w-100">
                        <i class="fa-solid fa-plus me-1"></i>Obtenir des jetons
                    </a>
                </div>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <?php if ($priceJetons <= 0 && $priceMoney <= 0): ?>
            <div class="text-muted text-center py-3 small">Aucun mode de paiement disponible.</div>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php include 'footer.php'; ?>
