<?php
session_start(); 
include 'config.php';

$cart = json_decode($_POST['cart'] ?? '[]', true);
$username = $_SESSION['mc_username'];

// Insert fake order
$pdo->prepare("INSERT INTO orders (mc_username, total, status) VALUES (?,?,?)")
    ->execute([$username, array_sum(array_map(fn($i)=>$i['price']*$i['qty'], $cart)), 'paid']);

// Insert commands into pending_rewards
foreach($cart as $item) {
    for($i = 0; $i < $item['qty']; $i++) {
        $stmt = $pdo->prepare("SELECT commands FROM packages WHERE name = ?");
        $stmt->execute([$item['name']]);
        $cmds = json_decode($stmt->fetchColumn() ?: '[]', true);
        foreach($cmds as $cmd) {
            $cmd = str_replace('%username%', $username, $cmd);
            $pdo->prepare("INSERT INTO pending_rewards (username, command) VALUES (?,?)")
                ->execute([$username, $cmd]);
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>PAYMENT SUCCESS!</title>
    <style>
        body{background:#000;color:#0f0;font-family:courier;text-align:center;padding:5rem}
        .success{font-size:6rem;margin:2rem 0;animation:blink 1s infinite}
        @keyframes blink{0%,100%{opacity:1}50%{opacity:0.3}}
        .box{background:#111;border:4px solid #0f0;padding:4rem;border-radius:30px;max-width:700px;margin:2rem auto;box-shadow:0 0 80px #0f03}
        a{color:#0f0;font-size:2rem;text-decoration:underline}
    </style>
</head>
<body>
<div class="box">
    <div class="success">SUCCESS!</div>
    <h1>Thank you <strong><?=$username?></strong>!</h1>
    <h2>Your items are being delivered in-game!</h2>
    <p>All commands added to pending_rewards table.</p>
    <br><br>
    <a href="index.php">Back to Store</a>
</div>

<script>
localStorage.removeItem('reckon_cart');
</script>
</body>
</html>