<?php
session_start();
require_once __DIR__ . '/../../shared/utils/helpers.php';
require_once __DIR__ . '/../../shared/auth/jwt.php';

$userData = JWTAuth::authenticate();

if (!$userData) {
    header('Location: /login.php?redirect=' . urlencode($_SERVER['REQUEST_URI']));
    exit;
}

if ($userData->rol !== 'Admin') {
    die('Acceso denegado. Se requieren permisos de Administrador.');
}
?>
<!DOCTYPE html>
<html lang="<?php echo $userData->idioma ?? 'es'; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestión de Usuarios - Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #34495e;
            --accent-color: #3498db;
            --success-color: #27ae60;
            --danger-color: #c0392b;
            --light-bg: #ecf0f1;
        }
        
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: var(--light-bg);
            min-height: 100vh;
            padding: 20px;
        }
        
        .header {
            background: white;
            border-radius: 15px;
            padding: 20px 30px;
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
        }
        
        .header h1 { color: var(--primary-color); font-size: 24px; }
        
        .container { max-width: 1200px; margin: 0 auto; }
        
        .card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        
        th, td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        
        th {
            background-color: #f8f9fa;
            color: var(--secondary-color);
            font-weight: 600;
        }
        
        tr:hover { background-color: #f8f9fa; }
        
        .btn {
            padding: 8px 16px;
            border-radius: 8px;
            text-decoration: none;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-primary { background: var(--accent-color); color: white; }
        .btn-primary:hover { background: #2980b9; }
        
        .btn-secondary { background: #95a5a6; color: white; }
        .btn-secondary:hover { background: #7f8c8d; }
        
        .btn-danger { background: var(--danger-color); color: white; }
        .btn-danger:hover { background: #a93226; }
        
        .badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .badge-admin { background: #e74c3c; color: white; }
        .badge-editor { background: #3498db; color: white; }
        .badge-user { background: #95a5a6; color: white; }
        
        .actions { display: flex; gap: 10px; }
        
        /* Modal */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        
        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 30px;
            border-radius: 15px;
            width: 90%;
            max-width: 600px;
            position: relative;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .close {
            position: absolute;
            right: 20px;
            top: 20px;
            font-size: 24px;
            cursor: pointer;
            color: #999;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1><i class="fas fa-users-cog"></i> Gestión de Usuarios</h1>
        <div style="display: flex; gap: 10px;">
            <a href="/index.php" class="btn btn-secondary">
                <i class="fas fa-home"></i> Inicio
            </a>
            <button onclick="openCreateModal()" class="btn btn-primary">
                <i class="fas fa-plus"></i> Nuevo Usuario
            </button>
        </div>
    </div>
    
    <div class="container">
        <div class="card">
            <div id="loading" style="text-align: center; padding: 20px;">
                <i class="fas fa-spinner fa-spin fa-2x"></i> Cargando usuarios...
            </div>
            
            <table id="usersTable" style="display: none;">
                <thead>
                    <tr>
                        <th>Usuario</th>
                        <th>Email</th>
                        <th>Rol</th>
                        <th>Último Acceso</th>
                        <th>Acciones</th>
                    </tr>
                </thead>
                <tbody id="usersList">
                    <!-- JS will populate this -->
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- Modal Container -->
    <div id="userModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal()">&times;</span>
            <div id="modalBody">
                <!-- Form will be loaded here -->
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', loadUsers);

        async function loadUsers() {
            try {
                const response = await fetch('/admin/api/users/list.php');
                const data = await response.json();
                
                if (data.success) {
                    const tbody = document.getElementById('usersList');
                    tbody.innerHTML = '';
                    
                    data.users.forEach(user => {
                        const rolClass = user.rol_nombre === 'Admin' ? 'badge-admin' : 
                                       (user.rol_nombre === 'Editor' ? 'badge-editor' : 'badge-user');
                        
                        const tr = document.createElement('tr');
                        tr.innerHTML = `
                            <td>
                                <div style="font-weight: 600;">${user.username}</div>
                                <div style="font-size: 12px; color: #999;">Creado: ${new Date(user.fecha_creacion).toLocaleDateString()}</div>
                            </td>
                            <td>${user.email || '-'}</td>
                            <td><span class="badge ${rolClass}">${user.rol_nombre}</span></td>
                            <td>${user.ultimo_acceso ? new Date(user.ultimo_acceso).toLocaleString() : 'Nunca'}</td>
                            <td class="actions">
                                <button onclick="editUser(${user.id})" class="btn btn-secondary" style="padding: 6px 12px; font-size: 13px;">
                                    <i class="fas fa-edit"></i>
                                </button>
                                ${user.id != <?php echo $userData->userId; ?> ? `
                                <button onclick="deleteUser(${user.id}, '${user.username}')" class="btn btn-danger" style="padding: 6px 12px; font-size: 13px;">
                                    <i class="fas fa-trash"></i>
                                </button>
                                ` : ''}
                            </td>
                        `;
                        tbody.appendChild(tr);
                    });
                    
                    document.getElementById('loading').style.display = 'none';
                    document.getElementById('usersTable').style.display = 'table';
                } else {
                    alert('Error cargando usuarios: ' + data.error);
                }
            } catch (error) {
                console.error('Error:', error);
                alert('Error de conexión');
            }
        }

        async function openCreateModal() {
            const modal = document.getElementById('userModal');
            const modalBody = document.getElementById('modalBody');
            
            modalBody.innerHTML = '<div style="text-align: center;"><i class="fas fa-spinner fa-spin"></i> Cargando formulario...</div>';
            modal.style.display = 'block';
            
            try {
                const response = await fetch('form.php');
                const html = await response.text();
                modalBody.innerHTML = html;
                
                // Inicializar formulario para creación
                initForm(); 
            } catch (error) {
                modalBody.innerHTML = '<p style="color: red;">Error cargando formulario</p>';
            }
        }

        async function editUser(userId) {
            const modal = document.getElementById('userModal');
            const modalBody = document.getElementById('modalBody');
            
            modalBody.innerHTML = '<div style="text-align: center;"><i class="fas fa-spinner fa-spin"></i> Cargando datos...</div>';
            modal.style.display = 'block';
            
            try {
                // Cargar formulario base
                const formResponse = await fetch('form.php');
                const formHtml = await formResponse.text();
                modalBody.innerHTML = formHtml;
                
                // Cargar datos del usuario
                const dataResponse = await fetch(`/admin/api/users/get.php?id=${userId}`);
                const data = await dataResponse.json();
                
                if (data.success) {
                    initForm(data);
                } else {
                    alert('Error cargando datos: ' + data.error);
                    closeModal();
                }
            } catch (error) {
                console.error(error);
                modalBody.innerHTML = '<p style="color: red;">Error cargando datos</p>';
            }
        }

        async function deleteUser(userId, username) {
            if (!confirm(`¿Estás seguro de eliminar al usuario "${username}"? Esta acción no se puede deshacer.`)) {
                return;
            }
            
            try {
                const response = await fetch('/admin/api/users/delete.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ id: userId })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    alert('Usuario eliminado correctamente');
                    loadUsers();
                } else {
                    alert('Error: ' + result.error);
                }
            } catch (error) {
                alert('Error de conexión');
            }
        }

        function closeModal() {
            document.getElementById('userModal').style.display = 'none';
        }

        window.onclick = function(event) {
            const modal = document.getElementById('userModal');
            if (event.target == modal) {
                closeModal();
            }
        }

        // Form Logic
        async function initForm(userData = null) {
            let roles = [];
            let allPermisos = [];
            
            if (userData) {
                // Modo Edición
                document.getElementById('formTitle').textContent = 'Editar Usuario';
                document.getElementById('userId').value = userData.user.id;
                document.getElementById('username').value = userData.user.username;
                document.getElementById('email').value = userData.user.email || '';
                
                document.getElementById('passReq').style.display = 'none';
                document.getElementById('password').required = false;
                document.getElementById('passHelp').style.display = 'block';
                
                roles = userData.roles;
                allPermisos = userData.all_permisos;
                
                renderRoles(roles, userData.user.rol_id);
                renderPermissions(allPermisos, userData.user_permisos);
                
            } else {
                // Modo Creación
                try {
                    const response = await fetch('/admin/api/users/metadata.php');
                    const data = await response.json();
                    
                    roles = data.roles;
                    allPermisos = data.all_permisos;
                    
                    document.getElementById('password').required = true;
                    
                    renderRoles(roles);
                    renderPermissions(allPermisos);
                    
                } catch (e) {
                    console.error(e);
                    alert('Error cargando metadatos del formulario');
                }
            }
            
            // Handle Submit
            const form = document.getElementById('userForm');
            form.onsubmit = async function(e) {
                e.preventDefault();
                
                const formData = new FormData(this);
                const data = Object.fromEntries(formData.entries());
                
                // Collect checked permissions
                const checkedPerms = [];
                document.querySelectorAll('input[name="permisos[]"]:checked').forEach(cb => {
                    checkedPerms.push(cb.value);
                });
                data.permisos = checkedPerms;
                
                const url = data.id ? '/admin/api/users/update.php' : '/admin/api/users/create.php';
                
                try {
                    const response = await fetch(url, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(data)
                    });
                    
                    const result = await response.json();
                    
                    if (result.success) {
                        alert(result.message);
                        closeModal();
                        loadUsers();
                    } else {
                        alert('Error: ' + result.error);
                    }
                } catch (error) {
                    alert('Error de conexión');
                }
            };
        }
        
        function renderRoles(roles, selectedId = null) {
            const select = document.getElementById('rol_id');
            select.innerHTML = '<option value="">Seleccionar Rol</option>';
            roles.forEach(rol => {
                const option = document.createElement('option');
                option.value = rol.id;
                option.textContent = rol.nombre;
                if (selectedId && rol.id == selectedId) option.selected = true;
                select.appendChild(option);
            });
        }
        
        function renderPermissions(allPermisos, userPerms = []) {
            const container = document.getElementById('permissionsList');
            container.innerHTML = '';
            
            // Agrupar por módulo
            const grouped = {};
            allPermisos.forEach(p => {
                if (!grouped[p.modulo]) grouped[p.modulo] = [];
                grouped[p.modulo].push(p);
            });
            
            for (const [modulo, perms] of Object.entries(grouped)) {
                const groupTitle = document.createElement('div');
                groupTitle.style.gridColumn = '1 / -1';
                groupTitle.style.fontWeight = 'bold';
                groupTitle.style.marginTop = '10px';
                groupTitle.style.textTransform = 'capitalize';
                groupTitle.textContent = modulo;
                container.appendChild(groupTitle);
                
                perms.forEach(p => {
                    const div = document.createElement('div');
                    div.className = 'perm-item';
                    
                    const checkbox = document.createElement('input');
                    checkbox.type = 'checkbox';
                    checkbox.name = 'permisos[]';
                    checkbox.value = p.id;
                    checkbox.id = 'perm_' + p.id;
                    
                    if (userPerms.includes(p.id) || userPerms.includes(String(p.id))) {
                        checkbox.checked = true;
                    }
                    
                    const label = document.createElement('label');
                    label.htmlFor = 'perm_' + p.id;
                    label.textContent = p.nombre;
                    label.title = p.descripcion || '';
                    
                    div.appendChild(checkbox);
                    div.appendChild(label);
                    container.appendChild(div);
                });
            }
        }
        
        function updatePermissionsView() {
            // Opcional: Auto-seleccionar permisos según rol
        }
    </script>
</body>
</html>
