<?php
$title = 'Configuración - Sistema de Gestión de Proyectos';
$page_title = 'Configuración del Sistema';
$current_page = 'settings';
$showSidebar = true;
$csrf_token = csrf_token();

ob_start();
?>

<div class="max-w-4xl">
    <!-- Header -->
    <div class="mb-6">
        <h2 class="text-2xl font-bold text-gray-900">Configuración General</h2>
        <p class="text-gray-600 mt-1">Personaliza el nombre y logo de tu aplicación</p>
    </div>

    <!-- Settings Form -->
    <div class="bg-white shadow rounded-lg">
        <form id="settingsForm" enctype="multipart/form-data" class="p-6 space-y-6">
            <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">

            <!-- App Name -->
            <div>
                <label for="app_name" class="block text-sm font-medium text-gray-700 mb-2">
                    <i class="fas fa-heading mr-2"></i>Nombre de la Aplicación
                </label>
                <input 
                    type="text" 
                    id="app_name" 
                    name="app_name" 
                    value="<?= htmlspecialchars($settings['app_name'] ?? 'Sistema de Gestión de Proyectos') ?>"
                    class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    required
                    maxlength="100"
                >
                <p class="text-xs text-gray-500 mt-1">Este nombre aparecerá en la barra de navegación y en los correos</p>
            </div>

            <!-- App Logo -->
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">
                    <i class="fas fa-image mr-2"></i>Logo de la Aplicación
                </label>
                
                <!-- Current Logo -->
                <?php if (!empty($settings['app_logo'])): ?>
                <div class="mb-4 p-4 bg-gray-50 rounded-lg border border-gray-200">
                    <p class="text-sm text-gray-600 mb-2">Logo actual:</p>
                    <img 
                        src="<?= htmlspecialchars($settings['app_logo']) ?>" 
                        alt="Logo actual" 
                        class="h-16 object-contain"
                        id="currentLogo"
                    >
                </div>
                <?php endif; ?>

                <!-- Upload New Logo -->
                <div class="flex items-center space-x-4">
                    <label class="flex items-center px-4 py-2 bg-white border border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                        <i class="fas fa-upload mr-2 text-gray-600"></i>
                        <span class="text-sm text-gray-700">Seleccionar archivo</span>
                        <input 
                            type="file" 
                            id="app_logo" 
                            name="app_logo" 
                            accept="image/*"
                            class="hidden"
                            onchange="previewLogo(this)"
                        >
                    </label>
                    <span id="fileName" class="text-sm text-gray-500">Ningún archivo seleccionado</span>
                </div>
                <p class="text-xs text-gray-500 mt-2">Formatos permitidos: JPG, PNG, GIF, SVG. Tamaño máximo: 2MB</p>

                <!-- Logo Preview -->
                <div id="logoPreview" class="hidden mt-4 p-4 bg-gray-50 rounded-lg border border-gray-200">
                    <p class="text-sm text-gray-600 mb-2">Vista previa:</p>
                    <img id="previewImage" src="" alt="Vista previa" class="h-16 object-contain">
                </div>
            </div>

            <!-- Save Button -->
            <div class="flex items-center justify-between pt-4 border-t border-gray-200">
                <button 
                    type="button" 
                    onclick="window.location.href='/dashboard'"
                    class="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50"
                >
                    <i class="fas fa-times mr-2"></i>Cancelar
                </button>
                <button 
                    type="submit"
                    class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                >
                    <i class="fas fa-save mr-2"></i>Guardar Cambios
                </button>
            </div>
        </form>
    </div>

    <!-- Additional Settings Preview -->
    <div class="mt-8 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-lg p-6">
        <div class="flex items-start">
            <div class="flex-shrink-0">
                <i class="fas fa-info-circle text-blue-600 text-xl"></i>
            </div>
            <div class="ml-4">
                <h3 class="text-lg font-medium text-gray-900 mb-2">Próximas Funcionalidades</h3>
                <ul class="text-sm text-gray-600 space-y-1">
                    <li><i class="fas fa-circle text-blue-500 mr-2" style="font-size: 6px;"></i>Configuración de correo electrónico (SMTP)</li>
                    <li><i class="fas fa-circle text-blue-500 mr-2" style="font-size: 6px;"></i>Personalización de colores del tema</li>
                    <li><i class="fas fa-circle text-blue-500 mr-2" style="font-size: 6px;"></i>Configuración de notificaciones</li>
                    <li><i class="fas fa-circle text-blue-500 mr-2" style="font-size: 6px;"></i>Integración con servicios externos</li>
                </ul>
            </div>
        </div>
    </div>
</div>

<!-- Toast Container -->
<div id="toast-container" class="fixed top-4 right-4 z-50"></div>

<script>
function previewLogo(input) {
    const fileName = document.getElementById('fileName');
    const logoPreview = document.getElementById('logoPreview');
    const previewImage = document.getElementById('previewImage');

    if (input.files && input.files[0]) {
        const file = input.files[0];
        fileName.textContent = file.name;

        // Mostrar preview
        const reader = new FileReader();
        reader.onload = function(e) {
            previewImage.src = e.target.result;
            logoPreview.classList.remove('hidden');
        };
        reader.readAsDataURL(file);
    } else {
        fileName.textContent = 'Ningún archivo seleccionado';
        logoPreview.classList.add('hidden');
    }
}

document.getElementById('settingsForm').addEventListener('submit', async function(e) {
    e.preventDefault();

    const formData = new FormData(this);
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;

    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Guardando...';

    try {
        const response = await fetch('/settings', {
            method: 'POST',
            body: formData
        });

        const data = await response.json();

        if (data.success) {
            showToast(data.message, 'success');
            
            // Actualizar logo actual si se subió uno nuevo
            if (data.logo_path) {
                const currentLogo = document.getElementById('currentLogo');
                if (currentLogo) {
                    currentLogo.src = data.logo_path;
                } else {
                    location.reload();
                }
            }

            // Limpiar preview
            document.getElementById('logoPreview').classList.add('hidden');
            document.getElementById('fileName').textContent = 'Ningún archivo seleccionado';
            document.getElementById('app_logo').value = '';
        } else {
            showToast(data.message || 'Error al guardar configuración', 'error');
        }
    } catch (error) {
        console.error('Error:', error);
        showToast('Error de conexión', 'error');
    } finally {
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
    }
});

function showToast(message, type = 'info') {
    const container = document.getElementById('toast-container');
    const toast = document.createElement('div');
    
    const bgColor = type === 'success' ? 'bg-green-500' : type === 'error' ? 'bg-red-500' : 'bg-blue-500';
    const icon = type === 'success' ? 'fa-check-circle' : type === 'error' ? 'fa-exclamation-circle' : 'fa-info-circle';
    
    toast.className = `${bgColor} text-white px-6 py-4 rounded-lg shadow-lg mb-4 flex items-center min-w-[300px] animate-slide-in`;
    toast.innerHTML = `
        <i class="fas ${icon} mr-3"></i>
        <span>${message}</span>
    `;
    
    container.appendChild(toast);
    
    setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transform = 'translateX(100%)';
        toast.style.transition = 'all 0.3s ease';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}
</script>

<style>
@keyframes slide-in {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

.animate-slide-in {
    animation: slide-in 0.3s ease forwards;
}
</style>

<?php
$content = ob_get_clean();
include __DIR__ . '/../layouts/app.php';
?>
