<?php
// admin/ruletas.php (con banners, background e icono fullscreen)
session_start();
require_once __DIR__ . '/db.php';
if (empty($_SESSION['admin_id'])) { header('Location: ../index.php'); exit; }

// Dónde guardar físicamente y cómo se verán públicamente (URL)
$UPLOAD_DIR = __DIR__ . '/../uploads/ruletas';          // físico
$PUBLIC_DIR = '/ruleta/uploads/ruletas';                // público (ajusta si tu base no es /ruleta)

if (!is_dir($UPLOAD_DIR)) { @mkdir($UPLOAD_DIR, 0775, true); }

// ---------- helpers ----------
function sanitize_filename($name) {
  $name = preg_replace('/[^A-Za-z0-9._-]/', '_', $name);
  return substr($name, 0, 180);
}
function upload_image($field, $UPLOAD_DIR, $PUBLIC_DIR) {
  if (!isset($_FILES[$field]) || $_FILES[$field]['error'] === UPLOAD_ERR_NO_FILE) return null;
  $f = $_FILES[$field];
  if ($f['error'] !== UPLOAD_ERR_OK) throw new RuntimeException("Error subiendo $field (código {$f['error']}).");
  $finfo = new finfo(FILEINFO_MIME_TYPE);
  $mime = $finfo->file($f['tmp_name']);
  $allowed = ['image/png'=>'png','image/jpeg'=>'jpg','image/webp'=>'webp'];
  if (!isset($allowed[$mime])) throw new RuntimeException("Formato no permitido para $field. Usa PNG/JPG/WEBP.");
  if ($f['size'] > 5 * 1024 * 1024) throw new RuntimeException("Archivo muy grande para $field (máx 5MB).");
  $ext = $allowed[$mime];
  $base = sanitize_filename(pathinfo($f['name'], PATHINFO_FILENAME));
  $fname = $base . '-' . uniqid() . '.' . $ext;
  $dest = rtrim($UPLOAD_DIR, "/\\") . DIRECTORY_SEPARATOR . $fname;
  if (!move_uploaded_file($f['tmp_name'], $dest)) throw new RuntimeException("No se pudo guardar el archivo de $field.");
  return rtrim($PUBLIC_DIR, '/') . '/' . $fname; // ruta pública para <img src="">
}
function get_ruleta(mysqli $conn, $id) {
  $stmt = $conn->prepare("SELECT id, nombre, descripcion,
    imagen_ruleta, imagen_puntero,
    banner_1, banner_2, banner_3, banner_4,
    background_image, fullscreen_icon
    FROM ruletas WHERE id=?");
  $stmt->bind_param("i", $id); $stmt->execute();
  return $stmt->get_result()->fetch_assoc();
}

$msg = $err = '';
$action = $_GET['action'] ?? '';
$id = (int)($_GET['id'] ?? 0);

// ---------- create / update ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $rid            = (int)($_POST['id'] ?? 0);
  $nombre         = trim($_POST['nombre'] ?? '');
  $descripcion    = trim($_POST['descripcion'] ?? '');

  // valores previos (para mantener si no se sube nuevo archivo)
  $old = [
    'imagen_ruleta'   => trim($_POST['old_imagen_ruleta'] ?? ''),
    'imagen_puntero'  => trim($_POST['old_imagen_puntero'] ?? ''),
    'banner_1'        => trim($_POST['old_banner_1'] ?? ''),
    'banner_2'        => trim($_POST['old_banner_2'] ?? ''),
    'banner_3'        => trim($_POST['old_banner_3'] ?? ''),
    'banner_4'        => trim($_POST['old_banner_4'] ?? ''),
    'background_image'=> trim($_POST['old_background_image'] ?? ''),
    'fullscreen_icon' => trim($_POST['old_fullscreen_icon'] ?? ''),
  ];

  if ($nombre === '') {
    $err = "El nombre es obligatorio.";
  } else {
    try {
      // nuevas subidas (si vienen)
      $new = [
        'imagen_ruleta'   => upload_image('imagen_ruleta',   $UPLOAD_DIR, $PUBLIC_DIR),
        'imagen_puntero'  => upload_image('imagen_puntero',  $UPLOAD_DIR, $PUBLIC_DIR),
        'banner_1'        => upload_image('banner_1',        $UPLOAD_DIR, $PUBLIC_DIR),
        'banner_2'        => upload_image('banner_2',        $UPLOAD_DIR, $PUBLIC_DIR),
        'banner_3'        => upload_image('banner_3',        $UPLOAD_DIR, $PUBLIC_DIR),
        'banner_4'        => upload_image('banner_4',        $UPLOAD_DIR, $PUBLIC_DIR),
        'background_image'=> upload_image('background_image',$UPLOAD_DIR, $PUBLIC_DIR),
        'fullscreen_icon' => upload_image('fullscreen_icon', $UPLOAD_DIR, $PUBLIC_DIR),
      ];
      // decidir final (nuevo o viejo o null)
      $vals = [];
      foreach ($new as $k => $v) {
        $vals[$k] = $v ?: ($old[$k] ?: null);
      }

      if ($rid > 0) {
        $stmt = $conn->prepare("UPDATE ruletas SET
          nombre=?, descripcion=?,
          imagen_ruleta=?, imagen_puntero=?,
          banner_1=?, banner_2=?, banner_3=?, banner_4=?,
          background_image=?, fullscreen_icon=?
          WHERE id=?");
        $stmt->bind_param(
          "ssssssssssi",
          $nombre, $descripcion,
          $vals['imagen_ruleta'], $vals['imagen_puntero'],
          $vals['banner_1'], $vals['banner_2'], $vals['banner_3'], $vals['banner_4'],
          $vals['background_image'], $vals['fullscreen_icon'],
          $rid
        );
        $stmt->execute();
        $msg = "Ruleta actualizada.";
      } else {
        $stmt = $conn->prepare("INSERT INTO ruletas
          (nombre, descripcion, imagen_ruleta, imagen_puntero,
           banner_1, banner_2, banner_3, banner_4,
           background_image, fullscreen_icon)
          VALUES (?,?,?,?,?,?,?,?,?,?)");
        $stmt->bind_param(
          "ssssssssss",
          $nombre, $descripcion,
          $vals['imagen_ruleta'], $vals['imagen_puntero'],
          $vals['banner_1'], $vals['banner_2'], $vals['banner_3'], $vals['banner_4'],
          $vals['background_image'], $vals['fullscreen_icon']
        );
        $stmt->execute();
        $msg = "Ruleta creada.";
      }
    } catch (Throwable $e) {
      $err = $e->getMessage();
    }
  }
}

// ---------- delete ----------
if ($action === 'delete' && $id > 0) {
  $stmt = $conn->prepare("DELETE FROM ruletas WHERE id=?");
  $stmt->bind_param("i", $id); $stmt->execute();
  $msg = "Ruleta eliminada.";
}

// ---------- edit load + list ----------
$edit = null;
if ($action === 'edit' && $id > 0) { $edit = get_ruleta($conn, $id); }

$res = $conn->query("SELECT id, nombre, descripcion,
  imagen_ruleta, imagen_puntero,
  banner_1, banner_2, banner_3, banner_4,
  background_image, fullscreen_icon, fecha_creacion
  FROM ruletas ORDER BY id DESC");
$items = $res->fetch_all(MYSQLI_ASSOC);
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <title>Ruletas | 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">
  <style>.thumb{width:70px;height:70px;object-fit:cover;border-radius:.5rem;}</style>
</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="premios.php">Premios</a>
      <a class="btn btn-outline-light btn-sm" href="jugadas.php">Jugadas</a>
      <a class="btn btn-outline-light btn-sm" href="../index.php?action=logout">Salir</a>
    </div>
  </div>
</nav>

<div class="container py-4">
  <h3 class="mb-3">Ruletas</h3>

  <?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 ruleta' : 'Nueva ruleta' ?></h5>
    <form method="post" enctype="multipart/form-data" class="row g-3">
      <input type="hidden" name="id" value="<?= (int)($edit['id'] ?? 0) ?>">
      <!-- old values para conservar si no se sube -->
      <input type="hidden" name="old_imagen_ruleta"   value="<?= htmlspecialchars($edit['imagen_ruleta']   ?? '') ?>">
      <input type="hidden" name="old_imagen_puntero"  value="<?= htmlspecialchars($edit['imagen_puntero']  ?? '') ?>">
      <input type="hidden" name="old_banner_1"        value="<?= htmlspecialchars($edit['banner_1']        ?? '') ?>">
      <input type="hidden" name="old_banner_2"        value="<?= htmlspecialchars($edit['banner_2']        ?? '') ?>">
      <input type="hidden" name="old_banner_3"        value="<?= htmlspecialchars($edit['banner_3']        ?? '') ?>">
      <input type="hidden" name="old_banner_4"        value="<?= htmlspecialchars($edit['banner_4']        ?? '') ?>">
      <input type="hidden" name="old_background_image"value="<?= htmlspecialchars($edit['background_image'] ?? '') ?>">
      <input type="hidden" name="old_fullscreen_icon" value="<?= htmlspecialchars($edit['fullscreen_icon'] ?? '') ?>">

      <div class="col-md-4">
        <label class="form-label">Nombre</label>
        <input name="nombre" class="form-control" required value="<?= htmlspecialchars($edit['nombre'] ?? '') ?>">
      </div>
      <div class="col-md-8">
        <label class="form-label">Descripción</label>
        <input name="descripcion" class="form-control" value="<?= htmlspecialchars($edit['descripcion'] ?? '') ?>">
      </div>

      <div class="col-md-6">
        <label class="form-label">Imagen de la ruleta</label>
        <input type="file" name="imagen_ruleta" class="form-control" accept=".png,.jpg,.jpeg,.webp">
        <?php if (!empty($edit['imagen_ruleta'])): ?>
          <div class="mt-2"><img src="<?= htmlspecialchars($edit['imagen_ruleta']) ?>" class="thumb" alt="ruleta">
            <small class="text-muted ms-2">Se mantiene si no subes otra.</small></div>
        <?php endif; ?>
      </div>
      <div class="col-md-6">
        <label class="form-label">Imagen del puntero</label>
        <input type="file" name="imagen_puntero" class="form-control" accept=".png,.jpg,.jpeg,.webp">
        <?php if (!empty($edit['imagen_puntero'])): ?>
          <div class="mt-2"><img src="<?= htmlspecialchars($edit['imagen_puntero']) ?>" class="thumb" alt="puntero"></div>
        <?php endif; ?>
      </div>

      <div class="col-12"><hr></div>

      <div class="col-md-6">
        <label class="form-label">Banner 1</label>
        <input type="file" name="banner_1" class="form-control" accept=".png,.jpg,.jpeg,.webp">
        <?php if (!empty($edit['banner_1'])): ?>
          <div class="mt-2"><img src="<?= htmlspecialchars($edit['banner_1']) ?>" class="thumb" alt="b1"></div>
        <?php endif; ?>
      </div>
      <div class="col-md-6">
        <label class="form-label">Banner 2</label>
        <input type="file" name="banner_2" class="form-control" accept=".png,.jpg,.jpeg,.webp">
        <?php if (!empty($edit['banner_2'])): ?>
          <div class="mt-2"><img src="<?= htmlspecialchars($edit['banner_2']) ?>" class="thumb" alt="b2"></div>
        <?php endif; ?>
      </div>
      <div class="col-md-6">
        <label class="form-label">Banner 3</label>
        <input type="file" name="banner_3" class="form-control" accept=".png,.jpg,.jpeg,.webp">
        <?php if (!empty($edit['banner_3'])): ?>
          <div class="mt-2"><img src="<?= htmlspecialchars($edit['banner_3']) ?>" class="thumb" alt="b3"></div>
        <?php endif; ?>
      </div>
      <div class="col-md-6">
        <label class="form-label">Banner 4</label>
        <input type="file" name="banner_4" class="form-control" accept=".png,.jpg,.jpeg,.webp">
        <?php if (!empty($edit['banner_4'])): ?>
          <div class="mt-2"><img src="<?= htmlspecialchars($edit['banner_4']) ?>" class="thumb" alt="b4"></div>
        <?php endif; ?>
      </div>

      <div class="col-md-6">
        <label class="form-label">Background (imagen)</label>
        <input type="file" name="background_image" class="form-control" accept=".png,.jpg,.jpeg,.webp">
        <?php if (!empty($edit['background_image'])): ?>
          <div class="mt-2"><img src="<?= htmlspecialchars($edit['background_image']) ?>" class="thumb" alt="bg"></div>
        <?php endif; ?>
      </div>
      <div class="col-md-6">
        <label class="form-label">Ícono botón Fullscreen</label>
        <input type="file" name="fullscreen_icon" class="form-control" accept=".png,.jpg,.jpeg,.webp">
        <?php if (!empty($edit['fullscreen_icon'])): ?>
          <div class="mt-2"><img src="<?= htmlspecialchars($edit['fullscreen_icon']) ?>" class="thumb" alt="fs"></div>
        <?php endif; ?>
      </div>

      <div class="col-12">
        <button class="btn btn-primary"><?= $edit ? 'Actualizar' : 'Crear' ?></button>
        <?php if ($edit): ?><a href="ruletas.php" 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>Nombre</th>
          <th>Ruleta</th><th>Puntero</th><th>BG</th>
          <th>B1</th><th>B2</th><th>B3</th><th>B4</th>
          <th>FS</th><th>Creado</th><th>Acciones</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($items as $r): ?>
          <tr>
            <td><?= (int)$r['id'] ?></td>
            <td><?= htmlspecialchars($r['nombre']) ?></td>
            <td><?php if ($r['imagen_ruleta']):  ?><img class="thumb" src="<?= htmlspecialchars($r['imagen_ruleta'])  ?>"><?php else: ?>—<?php endif; ?></td>
            <td><?php if ($r['imagen_puntero']): ?><img class="thumb" src="<?= htmlspecialchars($r['imagen_puntero']) ?>"><?php else: ?>—<?php endif; ?></td>
            <td><?php if ($r['background_image']): ?><img class="thumb" src="<?= htmlspecialchars($r['background_image']) ?>"><?php else: ?>—<?php endif; ?></td>
            <td><?php if ($r['banner_1']): ?><img class="thumb" src="<?= htmlspecialchars($r['banner_1']) ?>"><?php else: ?>—<?php endif; ?></td>
            <td><?php if ($r['banner_2']): ?><img class="thumb" src="<?= htmlspecialchars($r['banner_2']) ?>"><?php else: ?>—<?php endif; ?></td>
            <td><?php if ($r['banner_3']): ?><img class="thumb" src="<?= htmlspecialchars($r['banner_3']) ?>"><?php else: ?>—<?php endif; ?></td>
            <td><?php if ($r['banner_4']): ?><img class="thumb" src="<?= htmlspecialchars($r['banner_4']) ?>"><?php else: ?>—<?php endif; ?></td>
            <td><?php if ($r['fullscreen_icon']): ?><img class="thumb" src="<?= htmlspecialchars($r['fullscreen_icon']) ?>"><?php else: ?>—<?php endif; ?></td>
            <td><?= htmlspecialchars($r['fecha_creacion'] ?? '') ?></td>
            <td class="text-nowrap">
              <a class="btn btn-sm btn-outline-primary" href="ruletas.php?action=edit&id=<?= (int)$r['id'] ?>">Editar</a>
              <a class="btn btn-sm btn-outline-danger" href="ruletas.php?action=delete&id=<?= (int)$r['id'] ?>" onclick="return confirm('¿Eliminar ruleta?')">Eliminar</a>
              <a class="btn btn-sm btn-outline-success" href="premios.php?ruleta_id=<?= (int)$r['id'] ?>">Premios</a>
              <a class="btn-outline-warning" href="/../ruleta/index.html?ruleta_id=<?= (int)$r['id'] ?>" target="_blank" rel="noopener noreferrer">Ver</a>
            </td>
          </tr>
        <?php endforeach; ?>
        <?php if (!$items): ?>
          <tr><td colspan="12" class="text-center text-muted">Sin ruletas</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div></div>
</div>
</body>
</html>
