<?php
@session_start();
require_once '../db.php';
$pdo = pdo();

// Validar ID
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    die("ID inválido");
}

// Traer datos del modelo
$stmt = $pdo->prepare("SELECT * FROM modelos_casas WHERE id = :id LIMIT 1");
$stmt->execute([':id' => $id]);
$modelo = $stmt->fetch();

if (!$modelo) {
    die("Modelo no encontrado");
}

$errores = [];
$ok = false;

// Datos iniciales
$data = [
    'nombre'             => $modelo['nombre'],
    'descripcion_corta'  => $modelo['descripcion_corta'],
    'descripcion_larga'  => $modelo['descripcion_larga'],
    'metros_cubiertos'   => $modelo['metros_cubiertos'],
    'metros_galeria'     => $modelo['metros_galeria'],
    'sistema_default'    => $modelo['sistema_default'],
    'precio_desde'       => $modelo['precio_desde'],
    'precio_lista'       => $modelo['precio_lista'],
    'activo'             => $modelo['activo'],
    'orden'              => $modelo['orden'],
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    foreach ($data as $k => $v) {
        if (isset($_POST[$k])) {
            $data[$k] = trim($_POST[$k]);
        }
    }

    if ($data['nombre'] === '') {
        $errores[] = "El nombre es obligatorio.";
    }

    $imgPath = $modelo['imagen_portada'];

    // Imagen nueva
    if (!empty($_FILES['imagen']['name'])) {

        $dir = __DIR__ . '/uploads/modelos/';
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }

        $ext = pathinfo($_FILES['imagen']['name'], PATHINFO_EXTENSION);
        $fname = 'modelo_' . time() . '_' . rand(1000,9999) . '.' . $ext;

        $dest = $dir . $fname;

        if (move_uploaded_file($_FILES['imagen']['tmp_name'], $dest)) {

            // Borrar la imagen anterior si existe
            if (!empty($modelo['imagen_portada'])) {
                $old = __DIR__ . '/' . $modelo['imagen_portada'];
                if (file_exists($old)) {
                    unlink($old);
                }
            }

            $imgPath = 'uploads/modelos/' . $fname;

        } else {
            $errores[] = "Error al subir la nueva imagen.";
        }
    }

    if (empty($errores)) {

        $stmt = $pdo->prepare("
            UPDATE modelos_casas
            SET nombre = :nombre,
                descripcion_corta = :desc_corta,
                descripcion_larga = :desc_larga,
                metros_cubiertos = :metros_cubiertos,
                metros_galeria = :metros_galeria,
                sistema_default = :sistema_default,
                precio_desde = :precio_desde,
                precio_lista = :precio_lista,
                imagen_portada = :imagen_portada,
                activo = :activo,
                orden = :orden,
                updated_at = NOW()
            WHERE id = :id
        ");

        $stmt->execute([
            ':nombre'            => $data['nombre'],
            ':desc_corta'        => $data['descripcion_corta'],
            ':desc_larga'        => $data['descripcion_larga'],
            ':metros_cubiertos'  => $data['metros_cubiertos'],
            ':metros_galeria'    => $data['metros_galeria'],
            ':sistema_default'   => $data['sistema_default'],
            ':precio_desde'      => $data['precio_desde'],
            ':precio_lista'      => $data['precio_lista'],
            ':imagen_portada'    => $imgPath,
            ':activo'            => $data['activo'],
            ':orden'             => $data['orden'],
            ':id'                => $id
        ]);

        $ok = true;

        // refrescar datos
        $stmt = $pdo->prepare("SELECT * FROM modelos_casas WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $modelo = $stmt->fetch();
    }
}
?>
<!DOCTYPE html>
<html lang="es" data-bs-theme="light">
<head>
    <meta charset="UTF-8">
    <title>Editar Modelo - Panel Administrativo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <!-- Bootstrap 5 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --warning-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            --glass-bg: rgba(255, 255, 255, 0.9);
            --shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.08);
            --shadow-md: 0 8px 32px rgba(0, 0, 0, 0.1);
            --shadow-lg: 0 20px 60px rgba(0, 0, 0, 0.15);
            --border-radius-sm: 12px;
            --border-radius-md: 16px;
            --border-radius-lg: 24px;
            --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        * {
            font-family: 'Inter', sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            padding-top: 20px;
            padding-bottom: 40px;
        }
        
        .glass-card {
            background: var(--glass-bg);
            backdrop-filter: blur(20px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: var(--shadow-lg);
            border-radius: var(--border-radius-lg);
            overflow: hidden;
        }
        
        .header-section {
            background: var(--warning-gradient);
            color: white;
            padding: 2.5rem 0;
            border-radius: 0 0 var(--border-radius-lg) var(--border-radius-lg);
            position: relative;
            overflow: hidden;
        }
        
        .header-section::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 100" preserveAspectRatio="none"><path d="M0,0V100H1000V0C750,50 500,100 250,50S0,0,0,0Z" fill="rgba(255,255,255,0.1)"/></svg>');
            background-size: cover;
        }
        
        .header-title {
            font-weight: 700;
            font-size: 2.2rem;
            margin-bottom: 0.5rem;
            text-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .header-subtitle {
            font-weight: 400;
            opacity: 0.9;
            font-size: 1.1rem;
        }
        
        .form-section {
            padding: 2.5rem;
        }
        
        .section-title {
            color: #2d3748;
            font-weight: 600;
            font-size: 1.1rem;
            margin-bottom: 1.2rem;
            padding-bottom: 0.8rem;
            border-bottom: 2px solid #e2e8f0;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .section-title i {
            color: #f5576c;
            font-size: 1.2rem;
        }
        
        .form-label {
            font-weight: 500;
            color: #4a5568;
            margin-bottom: 0.5rem;
            font-size: 0.95rem;
        }
        
        .form-control, .form-select {
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            padding: 0.75rem 1rem;
            font-size: 1rem;
            transition: var(--transition);
            background-color: white;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #f5576c;
            box-shadow: 0 0 0 3px rgba(245, 87, 108, 0.1);
            transform: translateY(-1px);
        }
        
        .form-control:hover, .form-select:hover {
            border-color: #cbd5e0;
        }
        
        textarea.form-control {
            min-height: 120px;
            resize: vertical;
        }
        
        .required::after {
            content: " *";
            color: #e53e3e;
        }
        
        .input-group-icon {
            position: relative;
        }
        
        .input-group-icon .form-control {
            padding-left: 2.8rem;
        }
        
        .input-group-icon i {
            position: absolute;
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: #a0aec0;
            z-index: 10;
        }
        
        .btn-warning-custom {
            background: var(--warning-gradient);
            border: none;
            color: white;
            padding: 0.85rem 2rem;
            border-radius: 12px;
            font-weight: 600;
            font-size: 1rem;
            transition: var(--transition);
            box-shadow: 0 4px 15px rgba(245, 87, 108, 0.3);
        }
        
        .btn-warning-custom:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(245, 87, 108, 0.4);
            color: white;
        }
        
        .btn-secondary-custom {
            background: #718096;
            border: none;
            color: white;
            padding: 0.85rem 2rem;
            border-radius: 12px;
            font-weight: 600;
            font-size: 1rem;
            transition: var(--transition);
        }
        
        .btn-secondary-custom:hover {
            background: #4a5568;
            transform: translateY(-2px);
            color: white;
        }
        
        .success-card {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border-radius: var(--border-radius-md);
            padding: 2.5rem;
            text-align: center;
            box-shadow: var(--shadow-md);
            margin-bottom: 2rem;
        }
        
        .success-icon {
            font-size: 4rem;
            margin-bottom: 1.5rem;
            display: inline-block;
            animation: bounceIn 1s ease;
        }
        
        .alert-danger-custom {
            background: linear-gradient(135deg, #fed7e2 0%, #fbb6ce 100%);
            border: none;
            border-radius: var(--border-radius-md);
            border-left: 5px solid #e53e3e;
            color: #742a2a;
            box-shadow: var(--shadow-sm);
            margin-bottom: 2rem;
        }
        
        .image-upload-section {
            background: linear-gradient(135deg, rgba(245, 87, 108, 0.05) 0%, rgba(102, 126, 234, 0.05) 100%);
            border-radius: 16px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .current-image-container {
            text-align: center;
            padding: 1.5rem;
            background: white;
            border-radius: 12px;
            box-shadow: var(--shadow-sm);
            margin-top: 1.5rem;
        }
        
        .current-image-label {
            font-weight: 600;
            color: #4a5568;
            margin-bottom: 1rem;
            display: block;
            font-size: 1.1rem;
        }
        
        .current-image {
            max-width: 100%;
            border-radius: 12px;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
            transition: var(--transition);
            border: 3px solid white;
        }
        
        .current-image:hover {
            transform: scale(1.02);
            box-shadow: 0 12px 35px rgba(0, 0, 0, 0.15);
        }
        
        .file-upload-area {
            border: 3px dashed #f5576c;
            border-radius: 16px;
            padding: 2.5rem;
            text-align: center;
            transition: var(--transition);
            background: rgba(245, 87, 108, 0.05);
            cursor: pointer;
            margin-top: 1.5rem;
        }
        
        .file-upload-area:hover {
            border-color: #667eea;
            background: rgba(102, 126, 234, 0.05);
            transform: translateY(-2px);
        }
        
        .file-upload-area.dragover {
            border-color: #667eea;
            background: rgba(102, 126, 234, 0.1);
        }
        
        .file-upload-icon {
            font-size: 3rem;
            color: #f5576c;
            margin-bottom: 1rem;
        }
        
        .preview-image {
            max-width: 100%;
            border-radius: 12px;
            margin-top: 1rem;
            display: none;
            box-shadow: var(--shadow-sm);
        }
        
        .modelo-id-badge {
            background: var(--warning-gradient);
            color: white;
            padding: 0.5rem 1.5rem;
            border-radius: 50px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            box-shadow: var(--shadow-sm);
            margin-bottom: 1rem;
        }
        
        .info-badge {
            background: rgba(245, 87, 108, 0.1);
            color: #f5576c;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-size: 0.9rem;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            margin-top: 0.5rem;
        }
        
        @keyframes bounceIn {
            0% { transform: scale(0.3); opacity: 0; }
            50% { transform: scale(1.05); }
            70% { transform: scale(0.9); }
            100% { transform: scale(1); opacity: 1; }
        }
        
        .fade-in {
            animation: fadeIn 0.5s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .stats-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: var(--shadow-sm);
            border-left: 4px solid #f5576c;
        }
        
        .stats-label {
            font-size: 0.9rem;
            color: #718096;
            font-weight: 500;
        }
        
        .stats-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #2d3748;
            margin-top: 0.5rem;
        }
        
        @media (max-width: 768px) {
            .form-section {
                padding: 1.5rem;
            }
            
            .header-title {
                font-size: 1.8rem;
            }
            
            .file-upload-area {
                padding: 1.5rem;
            }
            
            .image-upload-section {
                padding: 1.5rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-12 col-xl-10">
                <div class="glass-card fade-in">
                    <!-- Header -->
                    <div class="header-section text-center">
                        <div class="position-relative">
                            <h1 class="header-title">
                                <i class="fas fa-edit"></i> Editar Modelo
                            </h1>
                            <p class="header-subtitle">
                                Modificar modelo existente en el catálogo
                            </p>
                            <div class="modelo-id-badge">
                                <i class="fas fa-hashtag"></i> ID: <?php echo htmlspecialchars($id); ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Content -->
                    <div class="form-section">
                        <?php if ($ok): ?>
                            <!-- Success Message -->
                            <div class="success-card fade-in">
                                <div class="success-icon">
                                    <i class="fas fa-check-circle"></i>
                                </div>
                                <h3 class="mb-3">¡Cambios guardados exitosamente!</h3>
                                <p class="mb-4">El modelo ha sido actualizado correctamente en la base de datos.</p>
                            </div>
                        <?php endif; ?>
                        
                        <?php if (!empty($errores)): ?>
                            <!-- Error Messages -->
                            <div class="alert alert-danger-custom fade-in">
                                <h5 class="alert-heading mb-3">
                                    <i class="fas fa-exclamation-triangle me-2"></i> Se encontraron errores
                                </h5>
                                <ul class="mb-0 ps-3">
                                    <?php foreach ($errores as $e): ?>
                                        <li><?php echo htmlspecialchars($e); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        <?php endif; ?>
                        
                        <!-- Quick Stats -->
                        <div class="row mb-5">
                            <div class="col-md-4 mb-3">
                                <div class="stats-card">
                                    <div class="stats-label">Fecha Creación</div>
                                    <div class="stats-value">
                                        <?php echo date('d/m/Y', strtotime($modelo['created_at'] ?? 'N/A')); ?>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4 mb-3">
                                <div class="stats-card">
                                    <div class="stats-label">Última Actualización</div>
                                    <div class="stats-value">
                                        <?php echo isset($modelo['updated_at']) ? date('d/m/Y', strtotime($modelo['updated_at'])) : 'Nunca'; ?>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4 mb-3">
                                <div class="stats-card">
                                    <div class="stats-label">Estado</div>
                                    <div class="stats-value">
                                        <span class="badge bg-<?php echo $modelo['activo'] ? 'success' : 'danger'; ?> p-2">
                                            <?php echo $modelo['activo'] ? 'Activo' : 'Inactivo'; ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Form -->
                        <form method="post" enctype="multipart/form-data" id="modeloForm">
                            <!-- Información Básica -->
                            <div class="row mb-5">
                                <div class="col-12">
                                    <h4 class="section-title">
                                        <i class="fas fa-info-circle"></i> Información Básica
                                    </h4>
                                </div>
                                
                                <div class="col-md-6 mb-4">
                                    <label class="form-label required">Nombre del Modelo</label>
                                    <div class="input-group-icon">
                                        <i class="fas fa-home"></i>
                                        <input type="text" name="nombre" class="form-control" 
                                               required value="<?php echo htmlspecialchars($data['nombre']); ?>"
                                               placeholder="Ej: Modelo Moderno 2024">
                                    </div>
                                    <div class="info-badge">
                                        <i class="fas fa-info-circle"></i> Nombre único para identificar el modelo
                                    </div>
                                </div>
                                
                                <div class="col-md-6 mb-4">
                                    <label class="form-label">Descripción Corta</label>
                                    <input type="text" name="descripcion_corta" class="form-control"
                                           value="<?php echo htmlspecialchars($data['descripcion_corta']); ?>"
                                           placeholder="Breve descripción para listados">
                                </div>
                                
                                <div class="col-12 mb-4">
                                    <label class="form-label">Descripción Larga</label>
                                    <textarea name="descripcion_larga" class="form-control" rows="4"
                                              placeholder="Descripción detallada del modelo..."><?php echo htmlspecialchars($data['descripcion_larga']); ?></textarea>
                                </div>
                            </div>
                            
                            <!-- Imagen de Portada -->
                            <div class="row mb-5">
                                <div class="col-12">
                                    <h4 class="section-title">
                                        <i class="fas fa-image"></i> Imagen de Portada
                                    </h4>
                                </div>
                                
                                <div class="col-12">
                                    <div class="image-upload-section">
                                        <!-- Imagen Actual -->
                                        <?php if (!empty($modelo['imagen_portada'])): ?>
                                            <div class="current-image-container fade-in">
                                                <span class="current-image-label">
                                                    <i class="fas fa-image me-2"></i> Imagen Actual
                                                </span>
                                                <img src="<?php echo htmlspecialchars($modelo['imagen_portada']); ?>" 
                                                     class="current-image" alt="Imagen actual del modelo">
                                                <p class="text-muted mt-2 mb-0">
                                                    <small>Esta imagen será reemplazada si subes una nueva</small>
                                                </p>
                                            </div>
                                        <?php else: ?>
                                            <div class="alert alert-warning">
                                                <i class="fas fa-exclamation-triangle me-2"></i> 
                                                Este modelo no tiene imagen de portada asignada.
                                            </div>
                                        <?php endif; ?>
                                        
                                        <!-- Área de Subida -->
                                        <div class="file-upload-area" id="fileUploadArea">
                                            <div class="file-upload-icon">
                                                <i class="fas fa-cloud-upload-alt"></i>
                                            </div>
                                            <h5 class="mb-2">Subir nueva imagen</h5>
                                            <p class="text-muted mb-3">Arrastra y suelta o haz clic para seleccionar</p>
                                            <input type="file" name="imagen" id="imagenInput" class="d-none" accept="image/*">
                                            <button type="button" class="btn btn-outline-danger px-4" onclick="document.getElementById('imagenInput').click()">
                                                <i class="fas fa-camera me-2"></i> Seleccionar nueva imagen
                                            </button>
                                            <p class="text-muted mt-3 mb-0">Formatos permitidos: JPG, PNG, WEBP, GIF</p>
                                            <img id="imagePreview" class="preview-image">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Especificaciones Técnicas -->
                            <div class="row mb-5">
                                <div class="col-12">
                                    <h4 class="section-title">
                                        <i class="fas fa-ruler-combined"></i> Especificaciones Técnicas
                                    </h4>
                                </div>
                                
                                <div class="col-md-4 mb-4">
                                    <label class="form-label required">Metros Cubiertos (m²)</label>
                                    <div class="input-group-icon">
                                        <i class="fas fa-vector-square"></i>
                                        <input type="number" step="0.01" name="metros_cubiertos" class="form-control" required
                                               value="<?php echo htmlspecialchars($data['metros_cubiertos']); ?>"
                                               placeholder="Ej: 120.50">
                                    </div>
                                </div>
                                
                                <div class="col-md-4 mb-4">
                                    <label class="form-label">Metros Galería (m²)</label>
                                    <div class="input-group-icon">
                                        <i class="fas fa-border-all"></i>
                                        <input type="number" step="0.01" name="metros_galeria" class="form-control"
                                               value="<?php echo htmlspecialchars($data['metros_galeria']); ?>"
                                               placeholder="Opcional">
                                    </div>
                                </div>
                                
                                <div class="col-md-4 mb-4">
                                    <label class="form-label required">Sistema por Defecto</label>
                                    <select name="sistema_default" class="form-select">
                                        <option value="estructura" <?php echo $data['sistema_default']==='estructura'?'selected':''; ?>>🏗️ Estructura</option>
                                        <option value="estructura_plataforma" <?php echo $data['sistema_default']==='estructura_plataforma'?'selected':''; ?>>🏗️➕ Estructura + Plataforma</option>
                                        <option value="llave_en_mano" <?php echo $data['sistema_default']==='llave_en_mano'?'selected':''; ?>>🔑 Llave en Mano</option>
                                    </select>
                                </div>
                            </div>
                            
                            <!-- Precios y Configuración -->
                            <div class="row mb-5">
                                <div class="col-12">
                                    <h4 class="section-title">
                                        <i class="fas fa-dollar-sign"></i> Precios y Configuración
                                    </h4>
                                </div>
                                
                                <div class="col-md-4 mb-4">
                                    <label class="form-label required">Precio Desde ($)</label>
                                    <div class="input-group-icon">
                                        <i class="fas fa-tag"></i>
                                        <input type="number" step="0.01" name="precio_desde" class="form-control" required
                                               value="<?php echo htmlspecialchars($data['precio_desde']); ?>"
                                               placeholder="Ej: 75000.00">
                                    </div>
                                </div>
                                
                                <div class="col-md-4 mb-4">
                                    <label class="form-label required">Precio Lista ($)</label>
                                    <div class="input-group-icon">
                                        <i class="fas fa-receipt"></i>
                                        <input type="number" step="0.01" name="precio_lista" class="form-control" required
                                               value="<?php echo htmlspecialchars($data['precio_lista']); ?>"
                                               placeholder="Ej: 85000.00">
                                    </div>
                                </div>
                                
                                <div class="col-md-2 mb-4">
                                    <label class="form-label">Estado</label>
                                    <select name="activo" class="form-select">
                                        <option value="1" <?php echo $data['activo']==1?'selected':''; ?>>✅ Activo</option>
                                        <option value="0" <?php echo $data['activo']==0?'selected':''; ?>>❌ Inactivo</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-2 mb-4">
                                    <label class="form-label">Orden</label>
                                    <div class="input-group-icon">
                                        <i class="fas fa-sort-numeric-down"></i>
                                        <input type="number" name="orden" class="form-control" 
                                               value="<?php echo htmlspecialchars($data['orden']); ?>"
                                               placeholder="0">
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Action Buttons -->
                            <div class="row mt-5 pt-4 border-top">
                                <div class="col-12 d-flex justify-content-between">
                                    <a href="modelos_listar.php" class="btn btn-secondary-custom">
                                        <i class="fas fa-arrow-left me-2"></i> Volver al Listado
                                    </a>
                                    <div>
                                        <button type="button" class="btn btn-outline-danger me-2" data-bs-toggle="modal" data-bs-target="#deleteModal">
                                            <i class="fas fa-trash me-2"></i> Eliminar
                                        </button>
                                        <button type="submit" class="btn btn-warning-custom">
                                            <i class="fas fa-save me-2"></i> Guardar Cambios
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Delete Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title" id="deleteModalLabel">
                        <i class="fas fa-exclamation-triangle me-2"></i> Confirmar Eliminación
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p class="lead">¿Estás seguro de que deseas eliminar este modelo?</p>
                    <p class="text-danger">
                        <i class="fas fa-exclamation-circle me-1"></i>
                        <strong>¡Advertencia!</strong> Esta acción no se puede deshacer.
                    </p>
                    <p>Se eliminarán todos los datos del modelo, incluyendo la imagen asociada.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-2"></i> Cancelar
                    </button>
                    <a href="modelos_eliminar.php?id=<?php echo $id; ?>" class="btn btn-danger">
                        <i class="fas fa-trash me-2"></i> Sí, Eliminar Modelo
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Image preview and drag & drop
        const fileUploadArea = document.getElementById('fileUploadArea');
        const imagenInput = document.getElementById('imagenInput');
        const imagePreview = document.getElementById('imagePreview');
        
        // File input change event
        imagenInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                previewImage(file);
            }
        });
        
        // Drag & drop events
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            fileUploadArea.addEventListener(eventName, preventDefaults, false);
        });
        
        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }
        
        ['dragenter', 'dragover'].forEach(eventName => {
            fileUploadArea.addEventListener(eventName, highlight, false);
        });
        
        ['dragleave', 'drop'].forEach(eventName => {
            fileUploadArea.addEventListener(eventName, unhighlight, false);
        });
        
        function highlight() {
            fileUploadArea.classList.add('dragover');
        }
        
        function unhighlight() {
            fileUploadArea.classList.remove('dragover');
        }
        
        fileUploadArea.addEventListener('drop', handleDrop, false);
        
        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            
            if (files.length > 0) {
                imagenInput.files = files;
                previewImage(files[0]);
            }
        }
        
        function previewImage(file) {
            const reader = new FileReader();
            
            reader.onload = function(e) {
                imagePreview.src = e.target.result;
                imagePreview.style.display = 'block';
                imagePreview.classList.add('fade-in');
            }
            
            reader.readAsDataURL(file);
        }
        
        // Form validation feedback
        const form = document.getElementById('modeloForm');
        const requiredFields = form.querySelectorAll('[required]');
        
        requiredFields.forEach(field => {
            field.addEventListener('invalid', function(e) {
                e.preventDefault();
                this.classList.add('is-invalid');
                
                if (!this.nextElementSibling || !this.nextElementSibling.classList.contains('invalid-feedback')) {
                    const errorDiv = document.createElement('div');
                    errorDiv.className = 'invalid-feedback d-block mt-1';
                    errorDiv.innerHTML = `<i class="fas fa-exclamation-circle me-1"></i> Este campo es obligatorio`;
                    this.parentNode.appendChild(errorDiv);
                }
            });
            
            field.addEventListener('input', function() {
                this.classList.remove('is-invalid');
                const errorDiv = this.parentNode.querySelector('.invalid-feedback');
                if (errorDiv) {
                    errorDiv.remove();
                }
            });
        });
        
        // Form submit animation
        form.addEventListener('submit', function(e) {
            const submitBtn = this.querySelector('button[type="submit"]');
            if (submitBtn) {
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> Guardando...';
                submitBtn.disabled = true;
            }
        });
        
        // Auto-hide success message after 5 seconds
        <?php if ($ok): ?>
            setTimeout(() => {
                const successCard = document.querySelector('.success-card');
                if (successCard) {
                    successCard.style.transition = 'opacity 0.5s ease';
                    successCard.style.opacity = '0';
                    setTimeout(() => {
                        successCard.style.display = 'none';
                    }, 500);
                }
            }, 5000);
        <?php endif; ?>
    </script>
</body>
</html>