<?php
session_start();
require_once __DIR__ . '/db.php';
if (empty($_SESSION['admin_id'])) { header('Location: ../index.php'); exit; }

function all_ruletas(mysqli $conn) {
  $res = $conn->query("SELECT id, nombre FROM ruletas ORDER BY id DESC");
  return $res->fetch_all(MYSQLI_ASSOC);
}
function find_premio(mysqli $conn, $id) {
  $stmt = $conn->prepare("SELECT id, ruleta_id, nombre, cantidad, probabilidad, inicio_angulo, fin_angulo FROM premios WHERE id=?");
  $stmt->bind_param("i", $id); $stmt->execute(); return $stmt->get_result()->fetch_assoc();
}

$ruletas = all_ruletas($conn);
$ruleta_id = (int)($_GET['ruleta_id'] ?? ($ruletas[0]['id'] ?? 0));
$msg = $err = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $id            = (int)($_POST['id'] ?? 0);
  $ruleta_id     = (int)($_POST['ruleta_id'] ?? 0);
  $nombre        = trim($_POST['nombre'] ?? '');
  $cantidad      = (int)($_POST['cantidad'] ?? 0);
  $probabilidad  = (float)($_POST['probabilidad'] ?? 0);
  $inicio        = (float)($_POST['inicio_angulo'] ?? 0);
  $fin           = (float)($_POST['fin_angulo'] ?? 0);

  if (!$ruleta_id || $nombre === '') {
    $err = "Completa ruleta y nombre.";
  } else {
    if ($id > 0) {
      $stmt = $conn->prepare("UPDATE premios SET ruleta_id=?, nombre=?, cantidad=?, probabilidad=?, inicio_angulo=?, fin_angulo=? WHERE id=?");
      $stmt->bind_param("isidddi", $ruleta_id, $nombre, $cantidad, $probabilidad, $inicio, $fin, $id);
      $stmt->execute(); $msg = "Premio actualizado.";
    } else {
      $stmt = $conn->prepare("INSERT INTO premios (ruleta_id, nombre, cantidad, probabilidad, inicio_angulo, fin_angulo) VALUES (?,?,?,?,?,?)");
      $stmt->bind_param("isiddd", $ruleta_id, $nombre, $cantidad, $probabilidad, $inicio, $fin);
      $stmt->execute(); $msg = "Premio creado.";
    }
  }
}

if (($_GET['action'] ?? '') === 'delete') {
  $id = (int)($_GET['id'] ?? 0);
  if ($id) {
    $stmt = $conn->prepare("DELETE FROM premios WHERE id=?");
    $stmt->bind_param("i", $id); $stmt->execute(); $msg = "Premio eliminado.";
  }
}

$edit = null;
if (($_GET['action'] ?? '') === 'edit') {
  $edit = find_premio($conn, (int)($_GET['id'] ?? 0));
  if ($edit) $ruleta_id = (int)$edit['ruleta_id'];
}

$stmt = $conn->prepare("SELECT p.id, p.nombre, p.cantidad, p.probabilidad, p.inicio_angulo, p.fin_angulo, r.nombre AS ruleta
  FROM premios p INNER JOIN ruletas r ON r.id=p.ruleta_id
  WHERE p.ruleta_id=? ORDER BY p.id DESC");
$stmt->bind_param("i", $ruleta_id); $stmt->execute();
$items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <title>Premios | Admin Ruletas</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-lg bg-dark navbar-dark">
  <div class="container-fluid">
    <a class="navbar-brand" href="dashboard.php">Home</a>
    <div class="d-flex gap-2">
      <a class="btn btn-outline-light btn-sm" href="ruletas.php">Ruletas</a>
      <a class="btn btn-outline-light btn-sm" href="jugadas.php">Jugadas</a>
    </div>
  </div>
</nav>

<div class="container py-4">
  <div class="d-flex align-items-center justify-content-between">
    <h3 class="mb-3">Premios</h3>
    <form class="d-flex" method="get">
      <select name="ruleta_id" class="form-select me-2" onchange="this.form.submit()">
        <?php foreach ($ruletas as $r): ?>
          <option value="<?= (int)$r['id'] ?>" <?= $ruleta_id===$r['id']?'selected':'' ?>>
            <?= htmlspecialchars($r['nombre']) ?> (ID <?= (int)$r['id'] ?>)
          </option>
        <?php endforeach; ?>
      </select>
      <noscript><button class="btn btn-primary">Cambiar</button></noscript>
    </form>
  </div>

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

  <div class="card shadow-sm mb-4"><div class="card-body">
    <h5 class="mb-3"><?= $edit ? 'Editar premio' : 'Nuevo premio' ?></h5>
    <form method="post" class="row g-3">
      <input type="hidden" name="id" value="<?= (int)($edit['id'] ?? 0) ?>">
      <div class="col-md-3">
        <label class="form-label">Ruleta</label>
        <select name="ruleta_id" class="form-select" required>
          <?php foreach ($ruletas as $r): ?>
            <option value="<?= (int)$r['id'] ?>" <?= ($ruleta_id===$r['id'])?'selected':'' ?>><?= htmlspecialchars($r['nombre']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">Nombre</label>
        <input name="nombre" class="form-control" required value="<?= htmlspecialchars($edit['nombre'] ?? '') ?>">
      </div>
      <div class="col-md-2">
        <label class="form-label">Cantidad</label>
        <input type="number" name="cantidad" class="form-control" min="0" value="<?= (int)($edit['cantidad'] ?? 0) ?>">
      </div>
      <div class="col-md-2">
        <label class="form-label">Probabilidad (%)</label>
        <input type="number" step="0.01" name="probabilidad" class="form-control" min="0" value="<?= htmlspecialchars($edit['probabilidad'] ?? '0') ?>">
      </div>
      <div class="col-md-1">
        <label class="form-label">Inicio°</label>
        <input type="number" step="0.01" name="inicio_angulo" class="form-control" value="<?= htmlspecialchars($edit['inicio_angulo'] ?? '0') ?>">
      </div>
      <div class="col-md-1">
        <label class="form-label">Fin°</label>
        <input type="number" step="0.01" name="fin_angulo" class="form-control" value="<?= htmlspecialchars($edit['fin_angulo'] ?? '0') ?>">
      </div>
      <div class="col-12">
        <button class="btn btn-primary"><?= $edit ? 'Actualizar' : 'Crear' ?></button>
        <?php if ($edit): ?><a href="premios.php?ruleta_id=<?= (int)$ruleta_id ?>" class="btn btn-secondary">Cancelar</a><?php endif; ?>
      </div>
    </form>
  </div></div>

  <div class="card shadow-sm"><div class="card-body table-responsive">
    <table class="table table-striped table-sm align-middle">
      <thead><tr><th>ID</th><th>Premio</th><th>Cantidad</th><th>Prob %</th><th>Inicio°</th><th>Fin°</th><th>Acciones</th></tr></thead>
      <tbody>
        <?php foreach ($items as $it): ?>
        <tr>
          <td><?= (int)$it['id'] ?></td>
          <td><?= htmlspecialchars($it['nombre']) ?></td>
          <td><?= (int)$it['cantidad'] ?></td>
          <td><?= htmlspecialchars($it['probabilidad']) ?></td>
          <td><?= htmlspecialchars($it['inicio_angulo']) ?></td>
          <td><?= htmlspecialchars($it['fin_angulo']) ?></td>
          <td class="text-nowrap">
            <a class="btn btn-sm btn-outline-primary" href="premios.php?action=edit&id=<?= (int)$it['id'] ?>&ruleta_id=<?= (int)$ruleta_id ?>">Editar</a>
            <a class="btn btn-sm btn-outline-danger" href="premios.php?action=delete&id=<?= (int)$it['id'] ?>&ruleta_id=<?= (int)$ruleta_id ?>" onclick="return confirm('¿Eliminar premio?')">Eliminar</a>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if (!$items): ?><tr><td colspan="7" class="text-center text-muted">Sin premios</td></tr><?php endif; ?>
      </tbody>
    </table>
  </div></div>
</div>
</body>
</html>
