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

$UPLOAD_DIR = __DIR__ . '/../uploads/rasca';
$PUBLIC_DIR = '/ruleta/uploads/rasca';
if (!is_dir($UPLOAD_DIR)) { @mkdir($UPLOAD_DIR, 0775, true); }

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.");
  $mime=(new finfo(FILEINFO_MIME_TYPE))->file($f['tmp_name']);
  $allowed=['image/png'=>'png','image/jpeg'=>'jpg','image/webp'=>'webp'];
  if(!isset($allowed[$mime])) throw new RuntimeException("Formato no permitido.");
  if($f['size']>5*1024*1024) throw new RuntimeException("Máximo 5MB.");
  $ext=$allowed[$mime]; $base=sanitize_filename(pathinfo($f['name'],PATHINFO_FILENAME));
  $name=$base.'-'.uniqid().'.'.$ext; $dest=rtrim($UPLOAD_DIR,'/\\').DIRECTORY_SEPARATOR.$name;
  if(!move_uploaded_file($f['tmp_name'],$dest)) throw new RuntimeException("No se pudo guardar $field.");
  return rtrim($PUBLIC_DIR,'/') . '/' . $name;
}
function upload_or_keep($name,$old,$UPLOAD_DIR,$PUBLIC_DIR){
  try{ $v=upload_image($name,$UPLOAD_DIR,$PUBLIC_DIR); return $v?:($old?:null); }
  catch(Throwable $e){ return $old?:null; }
}

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

if($_SERVER['REQUEST_METHOD']==='POST'){
  $rid=(int)($_POST['rasca_id']??0);
  $nombre=trim($_POST['nombre']??'');
  $olds=[
    'banner_1'=>$_POST['old_banner_1']??'','banner_2'=>$_POST['old_banner_2']??'',
    'banner_3'=>$_POST['old_banner_3']??'','banner_4'=>$_POST['old_banner_4']??'',
    'background_image'=>$_POST['old_background_image']??'','fullscreen_icon'=>$_POST['old_fullscreen_icon']??'',
    'fg_image'=>$_POST['old_fg_image']??'','bg_image'=>$_POST['old_bg_image']??'',
  ];
  if($rid<=0 || $nombre===''){ $err='Indica rasca_id y nombre.'; }
  else{
    try{
      $new=[
        'banner_1'=>upload_or_keep('banner_1',$olds['banner_1'],$UPLOAD_DIR,$PUBLIC_DIR),
        'banner_2'=>upload_or_keep('banner_2',$olds['banner_2'],$UPLOAD_DIR,$PUBLIC_DIR),
        'banner_3'=>upload_or_keep('banner_3',$olds['banner_3'],$UPLOAD_DIR,$PUBLIC_DIR),
        'banner_4'=>upload_or_keep('banner_4',$olds['banner_4'],$UPLOAD_DIR,$PUBLIC_DIR),
        'background_image'=>upload_or_keep('background_image',$olds['background_image'],$UPLOAD_DIR,$PUBLIC_DIR),
        'fullscreen_icon'=>upload_or_keep('fullscreen_icon',$olds['fullscreen_icon'],$UPLOAD_DIR,$PUBLIC_DIR),
        'fg_image'=>upload_or_keep('fg_image',$olds['fg_image'],$UPLOAD_DIR,$PUBLIC_DIR),
        'bg_image'=>upload_or_keep('bg_image',$olds['bg_image'],$UPLOAD_DIR,$PUBLIC_DIR),
      ];
      $sql="INSERT INTO rasca_config (rasca_id,nombre,banner_1,banner_2,banner_3,banner_4,background_image,fullscreen_icon,fg_image,bg_image)
            VALUES (?,?,?,?,?,?,?,?,?,?)
            ON DUPLICATE KEY UPDATE nombre=VALUES(nombre),
              banner_1=VALUES(banner_1), banner_2=VALUES(banner_2), banner_3=VALUES(banner_3), banner_4=VALUES(banner_4),
              background_image=VALUES(background_image), fullscreen_icon=VALUES(fullscreen_icon),
              fg_image=VALUES(fg_image), bg_image=VALUES(bg_image)";
      $st=$conn->prepare($sql);
      $st->bind_param("isssssssss",$rid,$nombre,$new['banner_1'],$new['banner_2'],$new['banner_3'],$new['banner_4'],$new['background_image'],$new['fullscreen_icon'],$new['fg_image'],$new['bg_image']);
      $st->execute(); $msg='Configuración guardada.'; $rasca_id=$rid;
    }catch(Throwable $e){ $err=$e->getMessage(); }
  }
}
if($action==='delete' && $rasca_id>0){ $st=$conn->prepare("DELETE FROM rasca_config WHERE rasca_id=?"); $st->bind_param("i",$rasca_id); $st->execute(); $msg='Configuración eliminada.'; $rasca_id=0; }
$edit=null; if($action==='edit' && $rasca_id>0){ $st=$conn->prepare("SELECT * FROM rasca_config WHERE rasca_id=?"); $st->bind_param("i",$rasca_id); $st->execute(); $edit=$st->get_result()->fetch_assoc(); }
$list=$conn->query("SELECT * FROM rasca_config ORDER BY rasca_id ASC");
?>
<!doctype html>
<html lang="es"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Rasca | Configuración</title>
<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-dark bg-dark"><div class="container-fluid">
  <a class="navbar-brand" href="dashboard.php">Admin</a>
  <div class="d-flex gap-2">
    <a class="btn btn-outline-light btn-sm" href="rasca_config.php">Config Rasca</a>
    <a class="btn btn-outline-light btn-sm" href="rasca_premios.php">Premios Rasca</a>
    <a class="btn btn-outline-light btn-sm" href="rasca_jugadas.php">Jugadas Rasca</a>
    <a class="btn btn-outline-light btn-sm" href="../index.php?action=logout">Salir</a>
  </div>
</div></nav>

<div class="container py-4">
  <?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':'Nuevo/Actualizar (por rasca_id)' ?></h5>
    <form method="post" enctype="multipart/form-data" class="row g-3">
      <?php foreach(['banner_1','banner_2','banner_3','banner_4','background_image','fullscreen_icon','fg_image','bg_image'] as $h): ?>
        <input type="hidden" name="old_<?= $h ?>" value="<?= htmlspecialchars($edit[$h]??'') ?>">
      <?php endforeach; ?>
      <div class="col-md-2"><label class="form-label">Rasca ID</label><input type="number" name="rasca_id" class="form-control" required value="<?= htmlspecialchars($edit['rasca_id']??'') ?>"></div>
      <div class="col-md-5"><label class="form-label">Nombre</label><input name="nombre" class="form-control" required value="<?= htmlspecialchars($edit['nombre']??'') ?>"></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"></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"></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"></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"></div><?php endif;?></div>
      <div class="col-md-6"><label class="form-label">Background</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"></div><?php endif;?></div>
      <div class="col-md-6"><label class="form-label">Ícono 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"></div><?php endif;?></div>
      <div class="col-md-6"><label class="form-label">Imagen FG (raspable)</label><input type="file" name="fg_image" class="form-control" accept=".png,.jpg,.jpeg,.webp"><?php if(!empty($edit['fg_image'])):?><div class="mt-2"><img src="<?= htmlspecialchars($edit['fg_image']) ?>" class="thumb"></div><?php endif;?></div>
      <div class="col-md-6"><label class="form-label">Imagen BG (base/premio)</label><input type="file" name="bg_image" class="form-control" accept=".png,.jpg,.jpeg,.webp"><?php if(!empty($edit['bg_image'])):?><div class="mt-2"><img src="<?= htmlspecialchars($edit['bg_image']) ?>" class="thumb"></div><?php endif;?></div>

      <div class="col-12"><button class="btn btn-primary">Guardar</button><?php if($edit):?><a href="rasca_config.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>Rasca ID</th><th>Nombre</th><th>B1</th><th>B2</th><th>B3</th><th>B4</th><th>BG</th><th>FS</th><th>FG</th><th>Base</th><th>Acciones</th></tr></thead>
      <tbody>
      <?php while($r=$list->fetch_assoc()): ?>
        <tr>
          <td><?= (int)$r['rasca_id'] ?></td>
          <td><?= htmlspecialchars($r['nombre']) ?></td>
          <td><?= $r['banner_1']?'<img class="thumb" src="'.htmlspecialchars($r['banner_1']).'">':'—' ?></td>
          <td><?= $r['banner_2']?'<img class="thumb" src="'.htmlspecialchars($r['banner_2']).'">':'—' ?></td>
          <td><?= $r['banner_3']?'<img class="thumb" src="'.htmlspecialchars($r['banner_3']).'">':'—' ?></td>
          <td><?= $r['banner_4']?'<img class="thumb" src="'.htmlspecialchars($r['banner_4']).'">':'—' ?></td>
          <td><?= $r['background_image']?'<img class="thumb" src="'.htmlspecialchars($r['background_image']).'">':'—' ?></td>
          <td><?= $r['fullscreen_icon']?'<img class="thumb" src="'.htmlspecialchars($r['fullscreen_icon']).'">':'—' ?></td>
          <td><?= $r['fg_image']?'<img class="thumb" src="'.htmlspecialchars($r['fg_image']).'">':'—' ?></td>
          <td><?= $r['bg_image']?'<img class="thumb" src="'.htmlspecialchars($r['bg_image']).'">':'—' ?></td>
          <td class="text-nowrap">
            <a class="btn btn-sm btn-outline-primary" href="rasca_config.php?action=edit&rasca_id=<?= (int)$r['rasca_id'] ?>">Editar</a>
            <a class="btn btn-sm btn-outline-danger" href="rasca_config.php?action=delete&rasca_id=<?= (int)$r['rasca_id'] ?>" onclick="return confirm('¿Eliminar config?')">Eliminar</a>
            <a class="btn-outline-warning" href="/../ruleta/rasca_index.html?rasca_id=<?= (int)$r['rasca_id'] ?>" target="_blank" rel="noopener noreferrer">Ver</a>
          </td>
        </tr>
      <?php endwhile; ?>
      </tbody>
    </table>
  </div></div>
</div>
</body></html>
