<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');

session_start();

$ALLOWED_GAMES = ['crackegg', 'hitjar', 'open-angpow'];
$DATA_FILE     = __DIR__ . '/../data/results.json';

// ── Validate request ──────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$game = trim($_POST['game'] ?? '');
if (!in_array($game, $ALLOWED_GAMES, true)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid game']);
    exit;
}

// ── One draw per game per session (prevents refresh cheating) ─────────────────
$session_key = 'drawn_' . $game;
if (isset($_SESSION[$session_key])) {
    echo json_encode(['prize' => $_SESSION[$session_key]]);
    exit;
}

// ── Load prize pool & results log ────────────────────────────────────────────
$prizes  = require __DIR__ . '/prizes.php';
$results = file_exists($DATA_FILE)
    ? json_decode(file_get_contents($DATA_FILE), true)
    : ['counts' => [], 'log' => []];

// ── Filter prizes that still have stock ──────────────────────────────────────
$available = array_values(array_filter($prizes, function ($p) use ($results) {
    if ($p['quantity'] === -1) return true;
    return ($results['counts'][$p['id']] ?? 0) < $p['quantity'];
}));

// Fallback: if every limited prize is exhausted, give the last entry (no_prize)
if (empty($available)) {
    $available = [end($prizes)];
}

// ── Weighted random selection ─────────────────────────────────────────────────
$total_weight = array_sum(array_column($available, 'weight'));
$rand         = mt_rand(1, $total_weight);
$cumulative   = 0;
$selected     = $available[count($available) - 1]; // safe default

foreach ($available as $prize) {
    $cumulative += $prize['weight'];
    if ($rand <= $cumulative) {
        $selected = $prize;
        break;
    }
}

// ── Persist result ────────────────────────────────────────────────────────────
$results['counts'][$selected['id']] = ($results['counts'][$selected['id']] ?? 0) + 1;
$results['log'][] = [
    'game'    => $game,
    'prize'   => $selected['id'],
    'time'    => date('c'),
    'session' => session_id(),
];

if (!is_dir(dirname($DATA_FILE))) {
    mkdir(dirname($DATA_FILE), 0755, true);
}
file_put_contents($DATA_FILE, json_encode($results, JSON_PRETTY_PRINT), LOCK_EX);

// ── Cache in session & respond ────────────────────────────────────────────────
$_SESSION[$session_key] = $selected;
echo json_encode(['prize' => $selected]);
