<?php
// admin_beneficios.php
@session_start();
require __DIR__ . '/db.php';

$pdo = pdo();

// Asegurar tabla
$pdo->exec("CREATE TABLE IF NOT EXISTS beneficios (
  id INT AUTO_INCREMENT PRIMARY KEY,
  titulo VARCHAR(190) NOT NULL,
  descripcion TEXT NOT NULL,
  imagen VARCHAR(255) DEFAULT NULL,
  orden INT DEFAULT NULL,
  estado ENUM('borrador','publicado') NOT NULL DEFAULT 'publicado',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

// Helpers
function h($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

// Manejo de eliminación
if (isset($_GET['eliminar'])) {
  $id = (int)$_GET['eliminar'];
  $stmt = $pdo->prepare("SELECT imagen FROM beneficios WHERE id=?");
  $stmt->execute([$id]);
  if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    if (!empty($row['imagen'])) {
      $file = __DIR__ . '/img/beneficios/' . $row['imagen'];
      if (is_file($file)) { @unlink($file); }
    }
  }
  $pdo->prepare("DELETE FROM beneficios WHERE id=?")->execute([$id]);
  header('Location: admin_beneficios.php?msg=eliminado');
  exit;
}

// Manejo de alta / edición
$editing = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $id          = isset($_POST['id']) ? (int)$_POST['id'] : 0;
  $titulo      = trim($_POST['titulo'] ?? '');
  $descripcion = trim($_POST['descripcion'] ?? '');
  $estado      = ($_POST['estado'] ?? 'publicado') === 'borrador' ? 'borrador' : 'publicado';
  $orden       = ($_POST['orden'] ?? '') !== '' ? (int)$_POST['orden'] : null;

  if ($titulo === '' || $descripcion === '') {
    $error = 'El título y la descripción son obligatorios.';
  } else {
    // Imagen existente si es edición
    $imagenNombre = null;
    if ($id) {
      $stmt = $pdo->prepare("SELECT imagen FROM beneficios WHERE id=?");
      $stmt->execute([$id]);
      $actual = $stmt->fetch(PDO::FETCH_ASSOC);
      $imagenNombre = $actual['imagen'] ?? null;
    }

    // Subida de imagen nueva
    if (!empty($_FILES['imagen']['name']) && $_FILES['imagen']['error'] === UPLOAD_ERR_OK) {
      $ext = strtolower(pathinfo($_FILES['imagen']['name'], PATHINFO_EXTENSION));
      $permitidas = ['jpg','jpeg','png','webp','gif'];
      if (!in_array($ext, $permitidas)) {
        $error = 'Formato de imagen no permitido. Usá JPG, PNG, WEBP o GIF.';
      } else {
        if (!is_dir(__DIR__ . '/img/beneficios')) {
          @mkdir(__DIR__ . '/img/beneficios', 0775, true);
        }
        $nuevoNombre = 'benef_' . time() . '_' . mt_rand(1000,9999) . '.' . $ext;
        $destino = __DIR__ . '/img/beneficios/' . $nuevoNombre;
        if (move_uploaded_file($_FILES['imagen']['tmp_name'], $destino)) {
          if (!empty($imagenNombre)) {
            $old = __DIR__ . '/img/beneficios/' . $imagenNombre;
            if (is_file($old)) { @unlink($old); }
          }
          $imagenNombre = $nuevoNombre;
        } else {
          $error = 'No se pudo guardar la imagen en el servidor.';
        }
      }
    }

    if (!isset($error)) {
      if ($id) {
        $sql = "UPDATE beneficios
                  SET titulo=?, descripcion=?, estado=?, orden=?, imagen=?
                WHERE id=?";
        $pdo->prepare($sql)->execute([
          $titulo,
          $descripcion,
          $estado,
          $orden,
          $imagenNombre,
          $id
        ]);
        header('Location: admin_beneficios.php?msg=actualizado');
        exit;
      } else {
        $sql = "INSERT INTO beneficios (titulo, descripcion, estado, orden, imagen)
                VALUES (?,?,?,?,?)";
        $pdo->prepare($sql)->execute([
          $titulo,
          $descripcion,
          $estado,
          $orden,
          $imagenNombre
        ]);
        header('Location: admin_beneficios.php?msg=creado');
        exit;
      }
    }
  }
}

// Carga para edición
if (isset($_GET['editar'])) {
  $id = (int)$_GET['editar'];
  $stmt = $pdo->prepare("SELECT * FROM beneficios WHERE id=?");
  $stmt->execute([$id]);
  $editing = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}

// Listado
$stmt = $pdo->query("SELECT * FROM beneficios ORDER BY COALESCE(orden, 9999), created_at DESC");
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <title>Administrar beneficios | Fe.Tr.A</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">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
  /* Placeholder blanco */
::placeholder {
  color: #ffffff !important;
  opacity: 1; /* Para que no quede grisáceo en algunos navegadores */
}

/* Firefox */
::-moz-placeholder {
  color: #ffffff !important;
}

/* Edge / IE */
:-ms-input-placeholder {
  color: #ffffff !important;
}

/* Chrome, Safari, Opera */
::-webkit-input-placeholder {
  color: #ffffff !important;
}
.card-title {
  color: #fff !important;
}

    :root {
      --primary: #6366f1;
      --primary-dark: #4f46e5;
      --secondary: #10b981;
      --dark-bg: #0f172a;
      --dark-card: #1e293b;
      --dark-border: #334155;
      --text-primary: #f8fafc;
      --text-secondary: #cbd5e1;
      --text-muted: #94a3b8;
      --success: #10b981;
      --danger: #ef4444;
      --warning: #f59e0b;
    }
    
    * {
      box-sizing: border-box;
    }
    
    body {
      background: var(--dark-bg);
      color: var(--text-primary);
      font-family: 'Inter', system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
      line-height: 1.6;
      min-height: 100vh;
      overflow-x: hidden;
    }
    
    .page-wrap {
      max-width: 1400px;
      margin: 0 auto;
      padding: 24px;
    }
    
    .page-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      gap: 16px;
      margin-bottom: 32px;
      padding-bottom: 16px;
      border-bottom: 1px solid var(--dark-border);
    }
    
    .page-title {
      font-size: 2rem;
      font-weight: 700;
      margin: 0;
      background: linear-gradient(90deg, var(--primary), var(--secondary));
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
    
    .page-subtitle {
      margin: 8px 0 0;
      color: var(--text-secondary);
      font-size: 1rem;
      max-width: 600px;
    }
    
    .card-pro {
      border-radius: 20px;
      background: var(--dark-card);
      border: 1px solid var(--dark-border);
      box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
      transition: all 0.3s ease;
      overflow: hidden;
    }
    
    .card-pro:hover {
      transform: translateY(-5px);
      box-shadow: 0 15px 35px rgba(0, 0, 0, 0.4);
    }
    
    .card-header {
      background: rgba(30, 41, 59, 0.8);
      border-bottom: 1px solid var(--dark-border);
      padding: 20px 24px;
    }
    
    .card-title {
      font-size: 1.25rem;
      font-weight: 600;
      margin: 0;
      display: flex;
      align-items: center;
      gap: 10px;
    }
    
    .card-title i {
      color: var(--primary);
    }
    
    .form-label {
      font-weight: 500;
      font-size: 0.9rem;
      margin-bottom: 8px;
      color: var(--text-secondary);
    }
    
    .form-control, .form-select {
      background: rgba(15, 23, 42, 0.7);
      border: 1px solid var(--dark-border);
      color: var(--text-primary);
      border-radius: 12px;
      padding: 10px 16px;
      transition: all 0.3s ease;
    }
    
    .form-control:focus, .form-select:focus {
      background: rgba(15, 23, 42, 0.9);
      border-color: var(--primary);
      box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.2);
      color: var(--text-primary);
    }
    
    .badge-estado {
      font-size: 0.75rem;
      text-transform: uppercase;
      letter-spacing: .05em;
      padding: 6px 12px;
      border-radius: 20px;
      font-weight: 600;
    }
    
    .tabla-img {
      width: 80px;
      height: 60px;
      object-fit: cover;
      border-radius: 12px;
      border: 1px solid var(--dark-border);
      transition: transform 0.3s ease;
    }
    
    .tabla-img:hover {
      transform: scale(1.05);
    }
    
    .small-muted {
      font-size: 0.85rem;
      color: var(--text-muted);
    }
    
    a {
      text-decoration: none;
      transition: all 0.3s ease;
    }
    
    .table {
      --bs-table-bg: transparent;
      --bs-table-color: var(--text-primary);
      --bs-table-border-color: var(--dark-border);
    }
    
    .table thead {
      border-color: var(--dark-border);
    }
    
    .table thead th {
      color: var(--text-muted);
      font-weight: 600;
      text-transform: uppercase;
      font-size: 0.8rem;
      letter-spacing: 0.05em;
      border-bottom: 2px solid var(--dark-border);
      padding: 16px 12px;
    }
    
    .table tbody tr {
      border-color: var(--dark-border);
      transition: all 0.3s ease;
    }
    
    .table tbody tr:hover {
      background: rgba(30, 41, 59, 0.5);
    }
    
    .table tbody td {
      padding: 16px 12px;
      vertical-align: middle;
    }
    
    .btn {
      border-radius: 12px;
      font-weight: 500;
      padding: 10px 20px;
      transition: all 0.3s ease;
      display: inline-flex;
      align-items: center;
      gap: 8px;
    }
    
    .btn-sm {
      padding: 8px 16px;
      font-size: 0.875rem;
    }
    
    .btn-primary {
      background: var(--primary);
      border-color: var(--primary);
    }
    
    .btn-primary:hover {
      background: var(--primary-dark);
      border-color: var(--primary-dark);
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(99, 102, 241, 0.4);
    }
    
    .btn-outline-light {
      color: var(--text-secondary);
      border-color: var(--dark-border);
    }
    
    .btn-outline-light:hover {
      background: rgba(255, 255, 255, 0.1);
      border-color: var(--text-secondary);
      color: var(--text-primary);
      transform: translateY(-2px);
    }
    
    .btn-outline-danger {
      color: var(--danger);
      border-color: var(--danger);
    }
    
    .btn-outline-danger:hover {
      background: var(--danger);
      color: white;
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(239, 68, 68, 0.4);
    }
    
    .alert {
      border-radius: 16px;
      border: none;
      padding: 16px 20px;
      margin-bottom: 24px;
      display: flex;
      align-items: center;
      gap: 12px;
    }
    
    .alert-danger {
      background: rgba(239, 68, 68, 0.15);
      color: #fca5a5;
      border-left: 4px solid var(--danger);
    }
    
    .alert-success {
      background: rgba(16, 185, 129, 0.15);
      color: #6ee7b7;
      border-left: 4px solid var(--success);
    }
    
    .empty-state {
      text-align: center;
      padding: 40px 20px;
      color: var(--text-muted);
    }
    
    .empty-state i {
      font-size: 3rem;
      margin-bottom: 16px;
      opacity: 0.5;
    }
    
    .empty-state h3 {
      font-size: 1.25rem;
      margin-bottom: 8px;
      color: var(--text-secondary);
    }
    
    .stats-card {
      background: linear-gradient(135deg, var(--primary), var(--primary-dark));
      border-radius: 16px;
      padding: 20px;
      color: white;
      margin-bottom: 24px;
    }
    
    .stats-number {
      font-size: 2.5rem;
      font-weight: 700;
      margin-bottom: 8px;
    }
    
    .stats-label {
      font-size: 0.9rem;
      opacity: 0.9;
    }
    
    .floating-action {
      position: fixed;
      bottom: 30px;
      right: 30px;
      z-index: 100;
    }
    
    .floating-btn {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      background: var(--primary);
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 10px 25px rgba(99, 102, 241, 0.5);
      transition: all 0.3s ease;
      border: none;
    }
    
    .floating-btn:hover {
      transform: scale(1.1) rotate(90deg);
      box-shadow: 0 15px 30px rgba(99, 102, 241, 0.7);
    }
    
    @media (max-width: 992px) {
      .page-header {
        flex-direction: column;
        align-items: flex-start;
      }
      
      .page-title {
        font-size: 1.75rem;
      }
    }
    
    @media (max-width: 768px) {
      .page-wrap {
        padding: 16px;
      }
      
      .table-responsive {
        border-radius: 16px;
        border: 1px solid var(--dark-border);
      }
      
      .floating-action {
        bottom: 20px;
        right: 20px;
      }
    }
    
    /* Animaciones */
    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(20px); }
      to { opacity: 1; transform: translateY(0); }
    }
    
    .fade-in {
      animation: fadeIn 0.5s ease forwards;
    }
    
    .delay-1 { animation-delay: 0.1s; }
    .delay-2 { animation-delay: 0.2s; }
    .delay-3 { animation-delay: 0.3s; }
    
    /* Scroll personalizado */
    ::-webkit-scrollbar {
      width: 8px;
    }
    
    ::-webkit-scrollbar-track {
      background: var(--dark-bg);
    }
    
    ::-webkit-scrollbar-thumb {
      background: var(--dark-border);
      border-radius: 10px;
    }
    
    ::-webkit-scrollbar-thumb:hover {
      background: var(--text-muted);
    }
  </style>
</head>
<body>
  <div class="page-wrap">
    <div class="page-header fade-in">
      <div>
        <h1 class="page-title">Administrar Beneficios</h1>
        <p class="page-subtitle">Gestiona los beneficios que se muestran en la página pública. Crea, edita y organiza el contenido de manera sencilla.</p>
      </div>
      <div class="text-end">
        <a href="admin/dashboard_fetra.php" class="btn btn-outline-light">
          <i class="fas fa-arrow-left me-2"></i>Volver al Panel
        </a>
      </div>
    </div>

    <?php if (!empty($error)): ?>
      <div class="alert alert-danger fade-in">
        <i class="fas fa-exclamation-circle"></i>
        <div><?php echo h($error); ?></div>
      </div>
    <?php endif; ?>

    <?php if (!empty($_GET['msg'])): ?>
      <div class="alert alert-success fade-in">
        <i class="fas fa-check-circle"></i>
        <div>
          <?php if ($_GET['msg']==='creado')   echo 'Beneficio creado correctamente.'; ?>
          <?php if ($_GET['msg']==='actualizado') echo 'Beneficio actualizado exitosamente.'; ?>
          <?php if ($_GET['msg']==='eliminado') echo 'Beneficio eliminado.'; ?>
        </div>
      </div>
    <?php endif; ?>

    <div class="row g-4">
      <div class="col-lg-4">
        <div class="stats-card fade-in">
          <div class="stats-number"><?php echo count($items); ?></div>
          <div class="stats-label">Beneficios Totales</div>
        </div>
        
        <div class="card card-pro fade-in delay-1">
          <div class="card-header">
            <h2 class="card-title">
              <i class="fas fa-<?php echo $editing ? 'edit' : 'plus'; ?>"></i>
              <?php echo $editing ? 'Editar Beneficio' : 'Nuevo Beneficio'; ?>
            </h2>
          </div>
          <div class="card-body p-4">
            <form method="post" enctype="multipart/form-data">
              <?php if ($editing): ?>
                <input type="hidden" name="id" value="<?php echo (int)$editing['id']; ?>">
              <?php endif; ?>

              <div class="mb-4">
                <label class="form-label">Título</label>
                <input type="text" name="titulo" class="form-control" maxlength="190" required
                       value="<?php echo h($editing['titulo'] ?? ''); ?>" placeholder="Ingresa un título atractivo">
              </div>

              <div class="mb-4">
                <label class="form-label">Descripción</label>
                <textarea name="descripcion" rows="4" class="form-control" required placeholder="Describe el beneficio en detalle"><?php echo h($editing['descripcion'] ?? ''); ?></textarea>
              </div>

              <div class="row g-3 mb-4">
                <div class="col-6">
                  <label class="form-label">Estado</label>
                  <select name="estado" class="form-select">
                    <option value="publicado" <?php echo (($editing['estado'] ?? 'publicado')==='publicado')?'selected':''; ?>>Publicado</option>
                    <option value="borrador"  <?php echo (($editing['estado'] ?? '')==='borrador')?'selected':''; ?>>Borrador</option>
                  </select>
                </div>
                <div class="col-6">
                  <label class="form-label">Orden</label>
                  <input type="number" name="orden" class="form-control"
                         value="<?php echo h($editing['orden'] ?? ''); ?>" placeholder="1, 2, 3...">
                  <div class="small-muted mt-1">Opcional</div>
                </div>
              </div>

              <div class="mb-4">
                <label class="form-label">Imagen</label>
                <input type="file" name="imagen" class="form-control" accept="image/*">
                <div class="small-muted mt-2">Formatos: JPG, PNG, WEBP, GIF. Tamaño recomendado: 1200x800px</div>
                <?php if (!empty($editing['imagen'])): ?>
                  <div class="mt-3">
                    <img src="img/beneficios/<?php echo h($editing['imagen']); ?>" alt="Imagen actual" class="tabla-img" style="max-width:200px;">
                    <div class="small-muted mt-1">Imagen actual</div>
                  </div>
                <?php endif; ?>
              </div>

              <div class="d-grid gap-2">
                <button type="submit" class="btn btn-primary">
                  <i class="fas fa-<?php echo $editing ? 'save' : 'plus'; ?> me-2"></i>
                  <?php echo $editing ? 'Guardar Cambios' : 'Crear Beneficio'; ?>
                </button>
                <?php if ($editing): ?>
                  <a href="admin_beneficios.php" class="btn btn-outline-light">
                    <i class="fas fa-times me-2"></i>Cancelar
                  </a>
                <?php endif; ?>
              </div>
            </form>
          </div>
        </div>
      </div>

      <div class="col-lg-8">
        <div class="card card-pro fade-in delay-2">
          <div class="card-header d-flex justify-content-between align-items-center">
            <h2 class="card-title">
              <i class="fas fa-list"></i>
              Beneficios Cargados
            </h2>
            <span class="badge bg-primary rounded-pill"><?php echo count($items); ?></span>
          </div>
          <div class="card-body p-0">
            <?php if (!$items): ?>
              <div class="empty-state">
                <i class="fas fa-inbox"></i>
                <h3>No hay beneficios cargados</h3>
                <p>Comienza creando tu primer beneficio usando el formulario.</p>
              </div>
            <?php else: ?>
              <div class="table-responsive">
                <table class="table table-hover mb-0">
                  <thead>
                    <tr>
                      <th>Imagen</th>
                      <th>Información</th>
                      <th class="text-center">Orden</th>
                      <th class="text-center">Estado</th>
                      <th class="text-end">Acciones</th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php foreach ($items as $b): ?>
                      <tr class="fade-in">
                        <td>
                          <?php if (!empty($b['imagen'])): ?>
                            <img src="img/beneficios/<?php echo h($b['imagen']); ?>" class="tabla-img" alt="">
                          <?php else: ?>
                            <div class="tabla-img d-flex align-items-center justify-content-center bg-dark">
                              <i class="fas fa-image text-muted"></i>
                            </div>
                          <?php endif; ?>
                        </td>
                        <td>
                          <div class="fw-semibold"><?php echo h($b['titulo']); ?></div>
                          <div class="small-muted text-truncate" style="max-width:300px;"><?php echo h($b['descripcion']); ?></div>
                        </td>
                        <td class="text-center">
                          <?php if ($b['orden'] !== null): ?>
                            <span class="badge bg-dark rounded-pill"><?php echo (int)$b['orden']; ?></span>
                          <?php else: ?>
                            <span class="small-muted">-</span>
                          <?php endif; ?>
                        </td>
                        <td class="text-center">
                          <?php if ($b['estado']==='publicado'): ?>
                            <span class="badge bg-success badge-estado">
                              <i class="fas fa-eye me-1"></i>Publicado
                            </span>
                          <?php else: ?>
                            <span class="badge bg-secondary badge-estado">
                              <i class="fas fa-eye-slash me-1"></i>Borrador
                            </span>
                          <?php endif; ?>
                        </td>
                        <td class="text-end">
                          <div class="btn-group">
                            <a href="admin_beneficios.php?editar=<?php echo (int)$b['id']; ?>" class="btn btn-sm btn-outline-light">
                              <i class="fas fa-edit"></i>
                            </a>
                            <a href="admin_beneficios.php?eliminar=<?php echo (int)$b['id']; ?>" class="btn btn-sm btn-outline-danger"
                               onclick="return confirm('¿Estás seguro de eliminar este beneficio?');">
                              <i class="fas fa-trash"></i>
                            </a>
                          </div>
                        </td>
                      </tr>
                    <?php endforeach; ?>
                  </tbody>
                </table>
              </div>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="floating-action">
    <a href="#top" class="floating-btn">
      <i class="fas fa-arrow-up"></i>
    </a>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    // Animación de entrada para elementos
    document.addEventListener('DOMContentLoaded', function() {
      const elements = document.querySelectorAll('.fade-in');
      elements.forEach(el => {
        el.style.opacity = '0';
      });
      
      setTimeout(() => {
        elements.forEach((el, index) => {
          setTimeout(() => {
            el.style.opacity = '1';
            el.style.transform = 'translateY(0)';
          }, index * 100);
        });
      }, 100);
    });
    
    // Confirmación para eliminación
    const deleteButtons = document.querySelectorAll('a[href*="eliminar"]');
    deleteButtons.forEach(button => {
      button.addEventListener('click', function(e) {
        if (!confirm('¿Estás seguro de que deseas eliminar este beneficio? Esta acción no se puede deshacer.')) {
          e.preventDefault();
        }
      });
    });
  </script>
</body>
</html>