<style>
    /* Estilos para formularios (con nuevo estilo para <select>) */
    .form-container { width: 100%; }
    .page-header {
        margin-bottom: 25px; padding-bottom: 15px; border-bottom: 1px solid var(--border-color);
    }
    .page-header h3 { margin: 0; font-size: 22px; color: var(--text-dark); }
    .form-section-title {
        font-size: 18px; color: var(--text-dark); padding-bottom: 10px;
        border-bottom: 1px solid var(--border-color); margin-top: 30px; margin-bottom: 20px;
    }
    .form-grid { display: grid; gap: 25px; grid-template-columns: 1fr; }
    @media (min-width: 992px) {
        .form-grid { grid-template-columns: repeat(2, 1fr); }
    }
    .form-group { margin-bottom: 20px; }
    .form-grid .form-group { margin-bottom: 0; }
    .form-group label { display: block; font-weight: 600; color: var(--text-dark); margin-bottom: 8px; }
    
    /* Estilo unificado para todos los campos de entrada */
    .form-group input[type="text"],
    .form-group input[type="email"],
    .form-group input[type="file"],
    .form-group textarea,
    .form-group select,
    .form-group input[disabled] {
        width: 100%; padding: 12px; border: 1px solid var(--border-color);
        border-radius: 6px; font-size: 16px; font-family: inherit; box-sizing: border-box;
        transition: border-color 0.3s ease, box-shadow 0.3s ease;
    }
    .form-group input[type="file"] { padding: 9px; }
    .form-group select {
        -webkit-appearance: none; appearance: none;
        background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e");
        background-repeat: no-repeat;
        background-position: right 12px center;
        background-size: 16px 12px;
        padding-right: 40px;
    }
    .form-group input[disabled] { background-color: #e9ecef; cursor: not-allowed; }
    .form-group input:focus,
    .form-group textarea:focus,
    .form-group select:focus {
        outline: none; border-color: var(--primary-color);
        box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.25);
    }
    .form-group textarea { min-height: 120px; resize: vertical; }
    .form-group small { display: block; margin-top: 5px; color: #6c757d; font-size: 13px; }
    .form-actions { display: flex; gap: 15px; align-items: center; margin-top: 30px; }
    .btn {
        text-decoration: none; color: #fff; background-color: var(--primary-color);
        padding: 12px 25px; border: none; border-radius: 6px; font-weight: 500;
        font-size: 16px; cursor: pointer; transition: background-color 0.3s ease, transform 0.2s ease;
        display: inline-block;
    }
    .btn:hover { background-color: #0056b3; transform: translateY(-2px); }
    .btn-secondary { color: var(--text-dark); background-color: transparent; font-weight: 500; text-decoration: none; }
    .btn-secondary:hover { text-decoration: underline; }
    .message.error {
        color: #842029; background-color: #f8d7da; border: 1px solid #f5c2c7;
        padding: 15px; margin-bottom: 20px; border-radius: 6px;
    }
    /* Estilos para la previsualización de la galería */
    .gallery-preview-container {
        margin-top: 15px; padding: 10px; border: 1px dashed var(--border-color);
        border-radius: 6px; display: flex; flex-wrap: wrap; gap: 15px;
        min-height: 80px; align-items: center; justify-content: flex-start;
    }
    .gallery-preview-container img {
        width: 100px; height: 100px; object-fit: cover;
        border-radius: 6px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    }
    .gallery-preview-container .placeholder { color: #999; font-size: 14px; }
</style>

<div class="form-container">
    <div class="page-header">
        <h3><?php 
            if (isset($this->project->id) && !empty($this->project->id)) {
                echo 'Editar Proyecto: ' . htmlspecialchars($this->project->title);
            } else {
                echo 'Crear Nuevo Proyecto';
            }
        ?></h3>
    </div>

    <?php if (isset($error)): ?>
        <div class="message error"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <form action="<?php echo isset($this->project->id) && !empty($this->project->id) ? url('admin/projects/edit?id=' . $this->project->id) : url('admin/projects/create'); ?>" method="POST" enctype="multipart/form-data">
        
        <h4 class="form-section-title">Información Principal</h4>
        <div class="form-grid">
            <div class="form-group">
                <label for="id">ID del Proyecto (Único)</label>
                <input type="text" id="id" name="id" value="<?php echo htmlspecialchars($this->project->id ?? ''); ?>" <?php echo (isset($this->project->id) && !empty($this->project->id)) ? 'disabled' : 'required'; ?>>
            </div>

            <div class="form-group">
                <label for="title">Título</label>
                <input type="text" id="title" name="title" value="<?php echo htmlspecialchars($this->project->title ?? ''); ?>" required>
            </div>

            <div class="form-group">
                <label for="client">Cliente</label>
                <input type="text" id="client" name="client" value="<?php echo htmlspecialchars($this->project->client ?? ''); ?>">
            </div>

            <div class="form-group">
                <label for="category">Categoría</label>
                <input type="text" id="category" name="category" value="<?php echo htmlspecialchars($this->project->category ?? ''); ?>">
            </div>

            <div class="form-group">
                <label for="service_id">Servicio Relacionado</label>
                <select id="service_id" name="service_id">
                    <option value="">-- Seleccione un Servicio --</option>
                    <?php if (!empty($services)): ?>
                        <?php foreach ($services as $service): ?>
                            <option value="<?php echo htmlspecialchars($service['id']); ?>"
                                <?php echo (isset($this->project->service_id) && $this->project->service_id == $service['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($service['title']); ?>
                            </option>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </select>
            </div>

            <div class="form-group">
                <label for="cover_image">Imagen de Portada</label>
                <?php if (isset($this->project->cover_image) && !empty($this->project->cover_image)): ?>
                    <div style="margin-bottom: 10px;">
                        <img src="<?php echo url(ltrim($this->project->cover_image, '/')); ?>" alt="Imagen Actual" style="max-width: 200px; border-radius: 6px;">
                        <p><small>Imagen actual. Sube una nueva para reemplazarla.</small></p>
                    </div>
                <?php endif; ?>
                <input type="file" id="cover_image" name="cover_image" accept="image/jpeg, image/png, image/webp">
            </div>
        </div>

        <h4 class="form-section-title">Detalles del Proyecto</h4>
        <div class="form-group">
            <label for="short_description">Descripción Corta</label>
            <textarea id="short_description" name="short_description" rows="3"><?php echo htmlspecialchars($this->project->short_description ?? ''); ?></textarea>
        </div>
        <div class="form-group">
            <label for="challenge">El Reto</label>
            <textarea id="challenge" name="challenge" rows="4"><?php echo htmlspecialchars($this->project->challenge ?? ''); ?></textarea>
        </div>
        <div class="form-group">
            <label for="solution">La Solución</label>
            <textarea id="solution" name="solution" rows="4"><?php echo htmlspecialchars($this->project->solution ?? ''); ?></textarea>
        </div>
        <div class="form-group">
            <label for="outcome">El Resultado</label>
            <textarea id="outcome" name="outcome" rows="4"><?php echo htmlspecialchars($this->project->outcome ?? ''); ?></textarea>
        </div>
        
        <h4 class="form-section-title">Contenido Adicional</h4>
        <div class="form-group">
            <label for="technologies">Tecnologías</label>
            <textarea id="technologies" name="technologies" rows="4"><?php echo htmlspecialchars(is_array($this->project->technologies) ? implode("\n", $this->project->technologies) : ''); ?></textarea>
            <small>Escribe una tecnología por línea.</small>
        </div>
        
        <div class="form-group">
            <label for="gallery">Imágenes de Galería</label>
            <input type="file" id="gallery" name="gallery[]" multiple accept="image/jpeg, image/png, image/webp">
            <small>Puedes seleccionar varias imágenes a la vez. Las nuevas imágenes se añadirán a las existentes.</small>
            <div class="gallery-preview-container" id="gallery-preview">
                <?php if (isset($this->project->gallery) && is_array($this->project->gallery) && !empty($this->project->gallery)): ?>
                    <?php foreach ($this->project->gallery as $image_path): ?>
                        <img src="<?php echo url(ltrim($image_path, '/')); ?>" alt="Imagen de galería">
                    <?php endforeach; ?>
                <?php else: ?>
                    <span class="placeholder">Las imágenes nuevas o existentes aparecerán aquí.</span>
                <?php endif; ?>
            </div>
        </div>
        
        <h4 class="form-section-title">Llamada a la Acción (CTA)</h4>
        <div class="form-grid">
             <div class="form-group">
                <label for="cta_text">Texto del Botón (CTA)</label>
                <input type="text" id="cta_text" name="cta_text" value="<?php echo htmlspecialchars($this->project->cta_text ?? ''); ?>">
            </div>

            <div class="form-group">
                <label for="cta_whatsapp_message">Mensaje de WhatsApp (CTA)</label>
                <textarea id="cta_whatsapp_message" name="cta_whatsapp_message" rows="3"><?php echo htmlspecialchars($this->project->cta_whatsapp_message ?? ''); ?></textarea>
            </div>
        </div>

        <div class="form-actions">
            <button type="submit" class="btn">
                <?php echo isset($this->project->id) && !empty($this->project->id) ? 'Actualizar Proyecto' : 'Crear Proyecto'; ?>
            </button>
            <a href="<?php echo url('admin/projects'); ?>" class="btn-secondary">Cancelar</a>
        </div>
    </form>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const galleryInput = document.getElementById('gallery');
        const previewContainer = document.getElementById('gallery-preview');

        if (galleryInput) {
            galleryInput.addEventListener('change', function(event) {
                // No limpia las previsualizaciones existentes al editar, solo añade las nuevas
                const existingImages = previewContainer.querySelectorAll('img');
                if (event.target.files.length > 0) {
                    // Si es la primera vez que se seleccionan, limpia el placeholder
                    if (previewContainer.querySelector('.placeholder')) {
                         previewContainer.innerHTML = '';
                    } else if (existingImages.length > 0) {
                        // Si ya hay imágenes, podrías decidir limpiarlas o no.
                        // Por ahora, las dejamos para que el usuario vea todo.
                        // Para una UX más avanzada, se podría añadir un botón de "limpiar selección".
                    }
                } else {
                     return; // Si no se seleccionan archivos, no hagas nada
                }

                Array.from(event.target.files).forEach(file => {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const img = document.createElement('img');
                        img.src = e.target.result;
                        previewContainer.appendChild(img);
                    }
                    reader.readAsDataURL(file);
                });
            });
        }
    });
</script>