<?php
// Variable para saber si estamos en modo 'Editar' o 'Crear'
$isEditing = isset($this->service->id) && !empty($this->service->id);
?>
<style>
    /* Estilos para formularios (idénticos a los anteriores) */
    .form-container { width: 100%; }
    .page-header {
        margin-bottom: 25px;
        padding-bottom: 15px;
        border-bottom: 1px solid #dee2e6;
    }
    .page-header h3 { margin: 0; font-size: 22px; color: #343a40; }
    .form-section-title {
        font-size: 18px; color: #343a40; padding-bottom: 10px;
        border-bottom: 1px solid #dee2e6; 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: #495057; margin-bottom: 8px; }
    .form-group input[type="text"],
    .form-group input[type="file"],
    .form-group textarea,
    .form-group input[disabled] {
        width: 100%; padding: 12px; border: 1px solid #ced4da;
        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 input[disabled] { background-color: #e9ecef; cursor: not-allowed; }
    .form-group input:focus,
    .form-group textarea:focus {
        outline: none; border-color: #80bdff;
        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: #007bff;
        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: #212529; background-color: #e9ecef; }
    .btn-secondary:hover { background-color: #dae0e5; }
    .message.error {
        color: #721c24; background-color: #f8d7da; border: 1px solid #f5c6cb;
        padding: 15px; margin-bottom: 20px; border-radius: 6px;
    }
    /* Estilos para la previsualización de la imagen */
    .image-preview-container { margin-top: 15px; }
    .image-preview {
        width: 100%;
        aspect-ratio: 16 / 9; /* Formato panorámico para servicios */
        border: 2px dashed #ced4da;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        color: #6c757d;
        overflow: hidden;
    }
    .image-preview img { width: 100%; height: 100%; object-fit: cover; }
</style>

<div class="form-container">
    <div class="page-header">
        <h3><?php echo $isEditing ? 'Editar Servicio' : 'Crear Nuevo Servicio'; ?></h3>
    </div>

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

    <form action="<?php echo $isEditing ? url('admin/services/edit') : url('admin/services/create'); ?>" method="POST" enctype="multipart/form-data">
        
        <?php if ($isEditing): ?>
            <input type="hidden" name="id" value="<?php echo htmlspecialchars($this->service->id ?? ''); ?>">
            <input type="hidden" name="current_image" value="<?php echo htmlspecialchars($this->service->image ?? ''); ?>">
        <?php endif; ?>
        
        <h4 class="form-section-title">Información Principal y SEO</h4>
        <div class="form-grid">
            <div class="form-group">
                <label for="id_display">ID del Servicio (Slug único)</label>
                <input type="text" id="id_display" name="<?php echo $isEditing ? '' : 'id'; ?>" value="<?php echo htmlspecialchars($this->service->id ?? ''); ?>" <?php echo $isEditing ? 'disabled' : 'required'; ?>>
                <small>Ej: desarrollo-web. No se puede cambiar después.</small>
            </div>

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

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

            <div class="form-group">
                <label for="seo_description">Descripción SEO</label>
                <textarea id="seo_description" name="seo_description" rows="3"><?php echo htmlspecialchars($this->service->seo_description ?? ''); ?></textarea>
            </div>
        </div>

        <h4 class="form-section-title">Contenido y Multimedia</h4>
        <div class="form-grid">
            <div class="form-group">
                <label for="icon">Ícono</label>
                <input type="text" id="icon" name="icon" value="<?php echo htmlspecialchars($this->service->icon ?? ''); ?>" placeholder="Ej: code, smartphone, globe">
                <small>Nombre del ícono de Lucide React o clase de otra librería.</small>
            </div>

            <div class="form-group">
                <label for="video">URL del Video (Opcional)</label>
                <input type="text" id="video" name="video" value="<?php echo htmlspecialchars($this->service->video ?? ''); ?>" placeholder="URL de YouTube o MP4">
            </div>
        </div>

        <div class="form-group">
            <label for="image">Imagen Principal</label>
            <input type="file" id="image" name="image" accept="image/jpeg, image/png, image/webp">
            <div class="image-preview-container">
                <div class="image-preview" id="image-preview">
                    <?php if ($isEditing && !empty($this->service->image)): ?>
                        <img src="<?php echo asset($this->service->image); ?>" alt="Imagen actual del servicio">
                    <?php else: ?>
                        <span>Previsualización de la imagen</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <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->service->short_description ?? ''); ?></textarea>
        </div>

        <div class="form-group">
            <label for="detailed_description">Descripción Detallada</label>
            <textarea id="detailed_description" name="detailed_description" rows="6"><?php echo htmlspecialchars($this->service->detailed_description ?? ''); ?></textarea>
        </div>

        <div class="form-group">
            <label for="key_offerings">Puntos Clave (uno por línea)</label>
            <textarea id="key_offerings" name="key_offerings" rows="5"><?php echo htmlspecialchars(is_array($this->service->key_offerings ?? null) ? implode("\n", $this->service->key_offerings) : ''); ?></textarea>
        </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->service->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->service->cta_whatsapp_message ?? ''); ?></textarea>
            </div>
        </div>

        <div class="form-actions">
            <button type="submit" class="btn btn-primary">
                <?php echo $isEditing ? 'Actualizar Servicio' : 'Crear Servicio'; ?>
            </button>
            <a href="<?php echo url('admin/services'); ?>" class="btn-secondary">Cancelar</a>
        </div>
    </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const imageInput = document.getElementById('image');
    const imagePreview = document.getElementById('image-preview');
    const originalContent = imagePreview.innerHTML;

    imageInput.addEventListener('change', function(event) {
        const file = event.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                imagePreview.innerHTML = '';
                const img = document.createElement('img');
                img.src = e.target.result;
                imagePreview.appendChild(img);
            }
            reader.readAsDataURL(file);
        } else {
            imagePreview.innerHTML = originalContent;
        }
    });
});
</script>