<?php
/**
 * CRUD de Usuarios - Backoffice administrativo
 * Turpial Airlines, C.A.
 */

$page_title = 'Gestión de Usuarios';

require_once '../includes/functions.php';
require_once '../includes/User.php';

// Verificar autenticación y permisos
requireLogin();

$user = new User();
$message = '';
$messageType = '';

// Procesar acciones
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    switch ($action) {
        case 'create':
            try {
                // Validar datos
                $required = ['username', 'email', 'full_name', 'password', 'role_id'];
                foreach ($required as $field) {
                    if (empty($_POST[$field])) {
                        throw new Exception("El campo {$field} es requerido");
                    }
                }
                
                // Validar email
                if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
                    throw new Exception('Email inválido');
                }
                
                // Validar longitud de contraseña
                if (strlen($_POST['password']) < 6) {
                    throw new Exception('La contraseña debe tener al menos 6 caracteres');
                }
                
                $data = [
                    'username' => trim($_POST['username']),
                    'email' => trim($_POST['email']),
                    'full_name' => trim($_POST['full_name']),
                    'password' => $_POST['password'],
                    'role_id' => (int)$_POST['role_id']
                ];
                
                $user->create($data);
                $message = 'Usuario creado exitosamente';
                $messageType = 'success';
                
            } catch (Exception $e) {
                $message = 'Error al crear usuario: ' . $e->getMessage();
                $messageType = 'danger';
            }
            break;
            
        case 'update':
            try {
                $id = (int)$_POST['id'];
                if ($id <= 0) {
                    throw new Exception('ID de usuario inválido');
                }
                
                $data = [
                    'username' => trim($_POST['username']),
                    'email' => trim($_POST['email']),
                    'full_name' => trim($_POST['full_name']),
                    'role_id' => (int)$_POST['role_id'],
                    'is_active' => isset($_POST['is_active']) ? 1 : 0
                ];
                
                // Solo actualizar contraseña si se proporciona
                if (!empty($_POST['password'])) {
                    if (strlen($_POST['password']) < 6) {
                        throw new Exception('La contraseña debe tener al menos 6 caracteres');
                    }
                    $data['password'] = $_POST['password'];
                }
                
                $user->update($id, $data);
                $message = 'Usuario actualizado exitosamente';
                $messageType = 'success';
                
            } catch (Exception $e) {
                $message = 'Error al actualizar usuario: ' . $e->getMessage();
                $messageType = 'danger';
            }
            break;
            
        case 'delete':
            try {
                $id = (int)$_POST['id'];
                if ($id <= 0) {
                    throw new Exception('ID de usuario inválido');
                }
                
                // No permitir eliminar el propio usuario
                if ($id == $_SESSION['user_id']) {
                    throw new Exception('No puedes desactivar tu propio usuario');
                }
                
                $user->delete($id);
                $message = 'Usuario desactivado exitosamente';
                $messageType = 'success';
                
            } catch (Exception $e) {
                $message = 'Error al desactivar usuario: ' . $e->getMessage();
                $messageType = 'danger';
            }
            break;
    }
}

// Obtener datos
$users = $user->getAllUsers();
$roles = $user->getRoles();

include 'includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="mb-0">
        <i class="fas fa-users me-2"></i>Gestión de Usuarios
    </h2>
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createUserModal">
        <i class="fas fa-plus me-2"></i>Nuevo Usuario
    </button>
</div>

<?php if ($message): ?>
<div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
    <i class="fas fa-<?php echo $messageType === 'success' ? 'check-circle' : 'exclamation-triangle'; ?> me-2"></i>
    <?php echo escape($message); ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Estadísticas rápidas -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="card border-left-primary shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                            Total Usuarios
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                            <?php echo count($users); ?>
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-users fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="card border-left-success shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                            Usuarios Activos
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                            <?php echo count(array_filter($users, function($u) { return $u['is_active']; })); ?>
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-user-check fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="card border-left-warning shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                            Administradores
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                            <?php echo count(array_filter($users, function($u) { return $u['role_id'] == 1; })); ?>
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-user-shield fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="card border-left-info shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                            Total Roles
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                            <?php echo count($roles); ?>
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-user-tag fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Tabla de usuarios -->
<div class="card shadow">
    <div class="card-header">
        <h6 class="m-0 font-weight-bold text-primary">
            <i class="fas fa-table me-2"></i>Lista de Usuarios
        </h6>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered table-hover">
                <thead class="table-dark">
                    <tr>
                        <th>ID</th>
                        <th>Usuario</th>
                        <th>Nombre Completo</th>
                        <th>Email</th>
                        <th>Rol</th>
                        <th>Estado</th>
                        <th>Creado</th>
                        <th>Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $userData): ?>
                    <tr>
                        <td><?php echo $userData['id']; ?></td>
                        <td>
                            <strong><?php echo escape($userData['username']); ?></strong>
                        </td>
                        <td><?php echo escape($userData['full_name']); ?></td>
                        <td>
                            <i class="fas fa-envelope me-1"></i>
                            <?php echo escape($userData['email']); ?>
                        </td>
                        <td>
                            <span class="badge bg-<?php echo $userData['role_id'] == 1 ? 'danger' : 'primary'; ?>">
                                <?php echo escape($userData['role_name']); ?>
                            </span>
                        </td>
                        <td>
                            <?php if ($userData['is_active']): ?>
                                <span class="badge bg-success">Activo</span>
                            <?php else: ?>
                                <span class="badge bg-secondary">Inactivo</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <small class="text-muted">
                                <?php echo date('d/m/Y H:i', strtotime($userData['created_at'])); ?>
                            </small>
                        </td>
                        <td>
                            <div class="btn-group" role="group">
                                <button type="button" class="btn btn-sm btn-outline-primary" 
                                        onclick="editUser(<?php echo htmlspecialchars(json_encode($userData)); ?>)"
                                        data-bs-toggle="modal" data-bs-target="#editUserModal">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <?php if ($userData['id'] != $_SESSION['user_id']): ?>
                                <button type="button" class="btn btn-sm btn-outline-danger"
                                        onclick="deleteUser(<?php echo $userData['id']; ?>, '<?php echo escape($userData['username']); ?>')">
                                    <i class="fas fa-trash"></i>
                                </button>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modal Crear Usuario -->
<div class="modal fade" id="createUserModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-user-plus me-2"></i>Crear Nuevo Usuario
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <input type="hidden" name="action" value="create">
                    
                    <div class="mb-3">
                        <label for="createUsername" class="form-label">Nombre de Usuario *</label>
                        <input type="text" class="form-control" id="createUsername" name="username" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="createEmail" class="form-label">Email *</label>
                        <input type="email" class="form-control" id="createEmail" name="email" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="createFullName" class="form-label">Nombre Completo *</label>
                        <input type="text" class="form-control" id="createFullName" name="full_name" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="createPassword" class="form-label">Contraseña *</label>
                        <input type="password" class="form-control" id="createPassword" name="password" required minlength="6">
                        <div class="form-text">Mínimo 6 caracteres</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="createRole" class="form-label">Rol *</label>
                        <select class="form-control" id="createRole" name="role_id" required>
                            <option value="">Seleccionar rol...</option>
                            <?php foreach ($roles as $role): ?>
                            <option value="<?php echo $role['id']; ?>">
                                <?php echo escape($role['name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-2"></i>Crear Usuario
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal Editar Usuario -->
<div class="modal fade" id="editUserModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-user-edit me-2"></i>Editar Usuario
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="post" id="editUserForm">
                <div class="modal-body">
                    <input type="hidden" name="action" value="update">
                    <input type="hidden" name="id" id="editUserId">
                    
                    <div class="mb-3">
                        <label for="editUsername" class="form-label">Nombre de Usuario *</label>
                        <input type="text" class="form-control" id="editUsername" name="username" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="editEmail" class="form-label">Email *</label>
                        <input type="email" class="form-control" id="editEmail" name="email" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="editFullName" class="form-label">Nombre Completo *</label>
                        <input type="text" class="form-control" id="editFullName" name="full_name" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="editPassword" class="form-label">Nueva Contraseña</label>
                        <input type="password" class="form-control" id="editPassword" name="password" minlength="6">
                        <div class="form-text">Dejar vacío para mantener la contraseña actual</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="editRole" class="form-label">Rol *</label>
                        <select class="form-control" id="editRole" name="role_id" required>
                            <?php foreach ($roles as $role): ?>
                            <option value="<?php echo $role['id']; ?>">
                                <?php echo escape($role['name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="editIsActive" name="is_active">
                            <label class="form-check-label" for="editIsActive">
                                Usuario activo
                            </label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-2"></i>Actualizar Usuario
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal Confirmar Eliminación -->
<div class="modal fade" id="deleteUserModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title text-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>Confirmar Desactivación
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>¿Estás seguro de que deseas desactivar el usuario <strong id="deleteUserName"></strong>?</p>
                <p class="text-muted">El usuario será desactivado pero no eliminado de la base de datos.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                <form method="post" style="display: inline;">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" id="deleteUserId">
                    <button type="submit" class="btn btn-danger">
                        <i class="fas fa-user-times me-2"></i>Desactivar Usuario
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function editUser(userData) {
    document.getElementById('editUserId').value = userData.id;
    document.getElementById('editUsername').value = userData.username;
    document.getElementById('editEmail').value = userData.email;
    document.getElementById('editFullName').value = userData.full_name;
    document.getElementById('editRole').value = userData.role_id;
    document.getElementById('editIsActive').checked = userData.is_active == 1;
    
    // Limpiar campo de contraseña
    document.getElementById('editPassword').value = '';
}

function deleteUser(id, username) {
    document.getElementById('deleteUserId').value = id;
    document.getElementById('deleteUserName').textContent = username;
    
    var modal = new bootstrap.Modal(document.getElementById('deleteUserModal'));
    modal.show();
}
</script>

<?php include 'includes/footer.php'; ?>