Initial commit: Proyecto Portal ePromos completo con documentación unificada y seguridad base
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
// api/seleccionar_premio.php - DB-driven selection
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
require_once __DIR__ . '/../admin/db.php';
|
||||
|
||||
$payload = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$ruleta_id = isset($payload['ruleta_id']) ? (int)$payload['ruleta_id'] : (int)($_GET['ruleta_id'] ?? 1);
|
||||
$user_agent = $payload['user_agent'] ?? ($_SERVER['HTTP_USER_AGENT'] ?? '');
|
||||
$ip_address = $payload['ip_address'] ?? ($_SERVER['REMOTE_ADDR'] ?? '');
|
||||
|
||||
// Leer premios disponibles
|
||||
$stmt = $conn->prepare("SELECT id, nombre, cantidad, probabilidad, inicio_angulo, fin_angulo FROM premios WHERE ruleta_id=? AND cantidad > 0");
|
||||
$stmt->bind_param("i", $ruleta_id);
|
||||
$stmt->execute();
|
||||
$res = $stmt->get_result();
|
||||
$premios = [];
|
||||
$totalProb = 0.0;
|
||||
while ($row = $res->fetch_assoc()) {
|
||||
$row['probabilidad'] = (float)$row['probabilidad'];
|
||||
$totalProb += $row['probabilidad'];
|
||||
$premios[] = $row;
|
||||
}
|
||||
$stmt->close();
|
||||
|
||||
if (!$premios || $totalProb <= 0) {
|
||||
http_response_code(422);
|
||||
echo json_encode(['error'=>'No hay premios configurados o probabilidades en cero']);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Sorteo ponderado
|
||||
$pick = mt_rand() / mt_getrandmax() * $totalProb;
|
||||
$acc = 0.0;
|
||||
$ganador = null;
|
||||
foreach ($premios as $p) {
|
||||
$acc += $p['probabilidad'];
|
||||
if ($pick <= $acc) { $ganador = $p; break; }
|
||||
}
|
||||
if (!$ganador) $ganador = end($premios);
|
||||
|
||||
// Guardar jugada
|
||||
$stmt = $conn->prepare("INSERT INTO jugadas (ruleta_id, premio_id, ip_address, user_agent) VALUES (?,?,?,?)");
|
||||
$stmt->bind_param("iiss", $ruleta_id, $ganador['id'], $ip_address, $user_agent);
|
||||
$stmt->execute();
|
||||
$stmt->close();
|
||||
|
||||
// Descontar inventario
|
||||
$stmt = $conn->prepare("UPDATE premios SET cantidad = cantidad - 1 WHERE id=? AND cantidad > 0");
|
||||
$stmt->bind_param("i", $ganador['id']);
|
||||
$stmt->execute();
|
||||
$stmt->close();
|
||||
|
||||
echo json_encode([
|
||||
'ok' => true,
|
||||
'nombre' => $ganador['nombre'],
|
||||
'inicio' => (float)$ganador['inicio_angulo'],
|
||||
'fin' => (float)$ganador['fin_angulo']
|
||||
]);
|
||||
Reference in New Issue
Block a user