<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Editar publicaciones</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link rel="icon" href="../img/logo.png" type="image/png">

    <style>
        :root {
            --primary-color: #000000;
            --secondary-color: #ffb50a;
            --accent-color: #ffcc33;
            --light-color: #f8f9fa;
            --dark-color: #212529;
            --success-color: #38b000;
            --danger-color: #dc3545;
            --warning-color: #ffc107;
        }
        body{background:linear-gradient(135deg,#ffb50a 0%,#ffcc33 100%);font-family:'Segoe UI',Roboto,'Helvetica Neue',sans-serif;min-height:100vh}
        .navbar{background:linear-gradient(to right,var(--primary-color),#1a1a1a)!important;box-shadow:0 4px 12px rgba(0,0,0,.1)}
        .navbar-brand{font-weight:700;letter-spacing:.5px;background:linear-gradient(to right,var(--secondary-color),#ffcc33);-webkit-background-clip:text;-webkit-text-fill-color:transparent}
        .nav-link{font-weight:500;padding:.5rem 1rem;border-radius:.5rem;transition:.3s}
        .nav-link:hover,.nav-link.active{background-color:rgba(255,181,10,.15);color:var(--secondary-color)!important;transform:translateY(-2px)}
        .container{max-width:1200px}
        h2{color:var(--dark-color);font-weight:700;position:relative;padding-bottom:15px;margin-bottom:30px}
        h2:after{content:'';position:absolute;bottom:0;left:50%;transform:translateX(-50%);width:80px;height:4px;background:linear-gradient(to right,var(--primary-color),var(--accent-color));border-radius:2px}
        .card{border:none;border-radius:12px;overflow:hidden;transition:.3s cubic-bezier(.25,.8,.25,1);background:#fff;box-shadow:0 4px 6px rgba(0,0,0,.05);margin-bottom:2rem;animation:fadeIn .5s ease forwards;opacity:0}
        .card:hover{transform:translateY(-5px);box-shadow:0 14px 28px rgba(0,0,0,.1),0 10px 10px rgba(0,0,0,.05)}
        .card-img{height:200px;object-fit:cover;border-radius:8px;margin-bottom:1rem;transition:.3s}
        .card:hover .card-img{transform:scale(1.02)}
        .form-control,.form-select{border-radius:8px;padding:.75rem 1rem;border:1px solid #e0e0e0;transition:.3s}
        .form-control:focus,.form-select:focus{border-color:var(--accent-color);box-shadow:0 0 0 .25rem rgba(255,181,10,.25)}
        label{font-weight:600;color:var(--dark-color);margin-bottom:.5rem}
        .btn-save{background:linear-gradient(to right,var(--primary-color),#333);border:none;font-weight:600;padding:.75rem 1.5rem;transition:.3s;color:#fff}
        .btn-save:hover{transform:translateY(-2px);box-shadow:0 4px 8px rgba(0,0,0,.3);background:linear-gradient(to right,#333,var(--primary-color));color:#fff}
        .btn-delete{background:linear-gradient(to right,var(--danger-color),#e02d3c);border:none;font-weight:600;padding:.75rem 1.5rem;transition:.3s;color:#fff}
        .btn-delete:hover{transform:translateY(-2px);box-shadow:0 4px 8px rgba(220,53,69,.3);color:#fff}
        .alert{border-radius:8px;border:none;box-shadow:0 4px 6px rgba(0,0,0,.05)}
        .alert-success{background:linear-gradient(to right,var(--success-color),#70e000);color:#fff}
        .alert-danger{background:linear-gradient(to right,var(--danger-color),#e02d3c);color:#fff}
        .file-upload{position:relative;overflow:hidden;border:2px dashed #e0e0e0;border-radius:8px;padding:2rem;text-align:center;transition:.3s}
        .file-upload:hover{border-color:var(--accent-color);background-color:rgba(255,181,10,.05)}
        .file-upload input[type="file"]{position:absolute;top:0;right:0;bottom:0;left:0;width:100%;height:100%;opacity:0;cursor:pointer}
        .file-upload-label{display:flex;flex-direction:column;align-items:center;color:#6c757d}
        .file-upload-label i{font-size:2rem;margin-bottom:.5rem;color:var(--accent-color)}
        footer{background:linear-gradient(to right,var(--primary-color),#1a1a1a);color:#fff;padding:1.5rem 0;margin-top:3rem}
        .social-icons a{display:inline-block;margin:0 10px;transition:.3s;color:#fff}
        .social-icons a:hover{color:var(--secondary-color);transform:translateY(-2px)}
        @keyframes fadeIn{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}
        .card:nth-child(1){animation-delay:.1s}.card:nth-child(2){animation-delay:.2s}.card:nth-child(3){animation-delay:.3s}
        .card:nth-child(4){animation-delay:.4s}.card:nth-child(5){animation-delay:.5s}.card:nth-child(6){animation-delay:.6s}
        @media (max-width:768px){.card-img{height:150px}h2{font-size:1.8rem}}
    </style>
</head>
<body class="bg-light">

<nav class="navbar navbar-expand-lg navbar-dark">
  <div class="container">
    <a class="navbar-brand" href="#"><i class="fas fa-cogs"></i> Editar/administrar publicaciones</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarContent">
      <ul class="navbar-nav ms-auto mb-2 mb-lg-0">
        <li class="nav-item"><a class="nav-link active" href="dashboard.php"><i class="fas fa-tachometer-alt me-1"></i> Dashboard</a></li>
        <li class="nav-item"><a class="nav-link" href="formulario.html"><i class="fas fa-plus-circle me-1"></i> Cargar</a></li>
        <li class="nav-item"><a class="nav-link" href="ver_publicaciones.php"><i class="fas fa-eye me-1"></i> Ver</a></li>
        <li class="nav-item"><a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt me-1"></i> Cerrar Sesión</a></li>
      </ul>
    </div>
  </div>
</nav>

<div class="container py-5">
    <h2 class="mb-4 text-center">Editar Generadores publicados</h2>

    <?php
    $dir = 'publicaciones';
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['archivo'])) {
        $archivo = $dir . '/' . basename($_POST['archivo']);

        // ELIMINAR (no requiere precio ni nada)
        if (isset($_POST['eliminar']) && $_POST['eliminar'] == '1') {
            if (file_exists($archivo)) { unlink($archivo); }
            echo '<div class="alert alert-danger mb-4"><i class="fas fa-trash-alt me-2"></i> Publicación eliminada correctamente.</div>';
        } else {
            // EDITAR (precio puede venir vacío)
            $data = json_decode(@file_get_contents($archivo), true);
            if (!is_array($data)) { $data = []; }
            $data['titulo']    = $_POST['titulo'] ?? '';
            $data['contenido'] = $_POST['contenido'] ?? '';
            $data['precio']    = $_POST['precio'] ?? ''; // ahora opcional
            $data['link']      = $_POST['link'] ?? '';

            if (isset($_FILES['imagen']) && $_FILES['imagen']['error'] === UPLOAD_ERR_OK) {
                $nombre_imagen = time() . '_' . basename($_FILES['imagen']['name']);
                @move_uploaded_file($_FILES['imagen']['tmp_name'], $dir . '/' . $nombre_imagen);
                $data['imagen'] = $nombre_imagen;
            }
            @file_put_contents($archivo, json_encode($data, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE));
            echo '<div class="alert alert-success mb-4"><i class="fas fa-check-circle me-2"></i> Publicación actualizada correctamente.</div>';
        }
    }

    if (is_dir($dir)) {
        foreach (glob($dir . '/*.json') as $archivo) {
            $nombre    = basename($archivo);
            $data      = json_decode(@file_get_contents($archivo), true);
            if (!$data) continue;
            $titulo    = htmlspecialchars($data['titulo'] ?? '', ENT_QUOTES, 'UTF-8');
            $contenido = htmlspecialchars($data['contenido'] ?? '', ENT_QUOTES, 'UTF-8');
            $precio    = htmlspecialchars($data['precio'] ?? '', ENT_QUOTES, 'UTF-8');
            $link      = htmlspecialchars($data['link'] ?? '', ENT_QUOTES, 'UTF-8');
            $imagen    = $data['imagen'] ?? '';
    ?>
    <div class="col">
        <div class="card p-4">
            <form method="post" enctype="multipart/form-data" class="form-publicacion">
                <input type="hidden" name="archivo" value="<?= $nombre ?>">

                <div class="row">
                    <div class="col-md-4 mb-3 mb-md-0">
                        <?php if (!empty($imagen) && file_exists("$dir/$imagen")): ?>
                            <img src="<?= "$dir/$imagen" ?>" class="card-img w-100" alt="<?= $titulo ?>">
                        <?php else: ?>
                            <div class="file-upload">
                                <label class="file-upload-label">
                                    <i class="fas fa-image"></i>
                                    <span>No hay imagen</span>
                                </label>
                                <input type="file" name="imagen">
                            </div>
                        <?php endif; ?>

                        <div class="file-upload mt-3">
                            <label class="file-upload-label">
                                <i class="fas fa-camera"></i>
                                <span>Cambiar imagen</span>
                            </label>
                            <input type="file" name="imagen">
                        </div>
                    </div>

                    <div class="col-md-8">
                        <div class="mb-3">
                            <label class="form-label">Título</label>
                            <input type="text" class="form-control" name="titulo" value="<?= $titulo ?>" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Descripción</label>
                            <textarea class="form-control" name="contenido" rows="4" required><?= $contenido ?></textarea>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Precio <span class="text-muted">(opcional)</span></label>
                                <div class="input-group">
                                    <span class="input-group-text">$</span>
                                    <!-- sin required -->
                                    <input type="number" step="0.01" class="form-control" name="precio" value="<?= $precio ?>">
                                </div>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label">Link de compra (opcional)</label>
                                <input type="url" class="form-control" name="link" value="<?= $link ?>" placeholder="https://...">
                            </div>
                        </div>

                        <div class="d-flex justify-content-between mt-4">
                            <button type="submit" class="btn btn-save">
                                <i class="fas fa-save me-2"></i>Guardar cambios
                            </button>

                            <!-- Eliminar: salta validación HTML5 -->
                            <button type="submit"
                                    name="eliminar" value="1"
                                    class="btn btn-delete btn-eliminar"
                                    formnovalidate>
                                <i class="fas fa-trash-alt me-2"></i>Eliminar
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <?php
        }
    }
    ?>
</div>

<footer>
    <div class="container text-center">
        <p class="mb-2">© 2025 NETFAN. Todos los derechos reservados.</p>
        <div class="col-md-6 text-center text-md-end mx-auto">
            <small class="text-white-50">Diseño y desarrollo por <a href="https://netfan.host" class="text-white">NETFAN</a></small>
        </div>
        <div class="social-icons mt-3">
            <a href="https://netfan.host" class="text-white mx-2"><i class="fas fa-question-circle"></i> Ayuda</a>
            <a href="https://netfan.host" class="text-white mx-2"><i class="fas fa-envelope"></i> Soporte</a>
        </div>
    </div>
</footer>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
  // Mostrar nombre de archivo al seleccionar imagen
  document.querySelectorAll('input[type="file"]').forEach(input => {
    input.addEventListener('change', function (e) {
      const fileName = e.target.files[0]?.name || 'Ningún archivo seleccionado';
      const label = this.closest('.file-upload')?.querySelector('span');
      if (label) label.textContent = fileName;
    });
  });

  // Eliminar: confirmar y desactivar required para evitar bloqueos
  document.querySelectorAll('.btn-eliminar').forEach(btn => {
    btn.addEventListener('click', function (e) {
      const ok = confirm('⚠️ ATENCIÓN: Esta acción eliminará permanentemente la publicación.\n\n¿Estás seguro de que deseas continuar?');
      if (!ok) { e.preventDefault(); return; }

      const form = this.closest('form');
      if (!form) return;

      // Desactiva cualquier required del formulario antes de enviar
      form.querySelectorAll('[required]').forEach(el => el.removeAttribute('required'));
      // formnovalidate ya está en el botón, esto es “doble seguro”
    });
  });
});
</script>
</body>
</html>
