<?php
session_start();
require_once 'conexao.php';

// Verifica se o usuário está logado
if (!isset($_SESSION['logado']) || !isset($_SESSION['usuario_id'])) {
    header('Location: login.php');
    exit;
}

$usuario_id = $_SESSION['usuario_id'];
$csrf_token = $_SESSION['csrf_token'] ?? bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $csrf_token;

$erro = '';
$sucesso = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $erro = 'Token CSRF inválido.';
    } else {
        $nome = trim($_POST['nome'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $telefone = trim($_POST['telefone'] ?? '');
        $cargo = trim($_POST['cargo'] ?? '');
        $nova_senha = trim($_POST['nova_senha'] ?? '');
        $confirmar_senha = trim($_POST['confirmar_senha'] ?? '');

        if (empty($nome) || empty($email)) {
            $erro = 'Nome e e-mail são obrigatórios.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $erro = 'E-mail inválido.';
        } elseif (!empty($nova_senha) && $nova_senha !== $confirmar_senha) {
            $erro = 'As senhas não coincidem.';
        } elseif (!empty($nova_senha) && strlen($nova_senha) < 8) {
            $erro = 'A nova senha deve ter no mínimo 8 caracteres.';
        }

        if (empty($erro)) {
            // Atualizar dados
            if (!empty($nova_senha)) {
                $senha_hash = password_hash($nova_senha, PASSWORD_DEFAULT);
                $stmt = $conn->prepare("UPDATE usuarios SET nome = ?, email = ?, telefone = ?, cargo = ?, senha = ? WHERE id = ?");
                $stmt->bind_param("sssssi", $nome, $email, $telefone, $cargo, $senha_hash, $usuario_id);
            } else {
                $stmt = $conn->prepare("UPDATE usuarios SET nome = ?, email = ?, telefone = ?, cargo = ? WHERE id = ?");
                $stmt->bind_param("ssssi", $nome, $email, $telefone, $cargo, $usuario_id);
            }

            if ($stmt->execute()) {
                $sucesso = 'Dados atualizados com sucesso!';
                $_SESSION['nome_usuario'] = $nome;
                $_SESSION['email_usuario'] = $email;
            } else {
                $erro = 'Erro ao atualizar: ' . $conn->error;
            }

            $stmt->close();
        }
    }
}

// Carregar dados atuais do usuário
$stmt = $conn->prepare("SELECT nome, email, telefone, cargo FROM usuarios WHERE id = ?");
$stmt->bind_param("i", $usuario_id);
$stmt->execute();
$result = $stmt->get_result();
$usuario = $result->fetch_assoc();
$stmt->close();
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <title>Editar Perfil</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        
        .header-fixed {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            background-color: #f5f5f5;
            padding: 15px 20px;
            z-index: 1000;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header-fixed img {
            height: 50px;
            margin-right: 15px;
        }
        
        /* Menu Lateral Recolhível */
        .sidebar {
            position: fixed;
            left: 0;
            top: 80px;
            height: calc(100vh - 80px);
            width: 60px;
            background: white;
            box-shadow: 2px 0 5px rgba(0,0,0,0.1);
            z-index: 999;
            transition: width 0.3s ease;
            overflow-x: hidden;
        }
        
        .sidebar-menu {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        
        .sidebar-menu li {
            border-bottom: 1px solid #eee;
        }
        
        .sidebar-menu a {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            text-decoration: none;
            color: #333;
            white-space: nowrap;
            transition: background-color 0.3s;
        }
        
        .sidebar-menu i {
            width: 24px;
            height: 24px;
            margin-right: 15px;
            text-align: center;
            flex-shrink: 0;
        }
        
        .sidebar-menu .menu-text {
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .content-wrapper {
            margin-top: 80px;
            margin-left: 60px;
            padding: 20px;
            transition: margin-left 0.3s ease;
        }
        
        .container {
            max-width: 1800px;
            margin: 0 auto;
            background: white;
            padding: 25px;
            border-radius: 8px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.05);
        }
        
        .profile-container {
            max-width: 800px;
            margin: 0 auto;
        }
        
        .profile-info {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.05);
        }
        
        /* Estilos do formulário */
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #555;
        }
        
        .form-group input[type="text"],
        .form-group input[type="email"],
        .form-group input[type="password"] {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
            box-sizing: border-box;
            transition: border-color 0.3s;
        }
        
        .form-group input:focus {
            border-color: #007bff;
            outline: none;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
        }
        
        /* Mensagens de alerta */
        .alert {
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .alert i {
            font-size: 18px;
        }
        
        /* Botões */
        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            font-size: 16px;
            transition: background-color 0.3s;
            font-weight: 500;
        }
        
        .btn-primary {
            background: #007bff;
            color: white;
        }
        
        .btn-primary:hover {
            background: #0056b3;
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #545b62;
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background: #1e7e34;
        }
        
        .action-buttons {
            margin-top: 30px;
            display: flex;
            gap: 15px;
        }
        
        .required::after {
            content: " *";
            color: #dc3545;
        }
        
        /* Informações de ajuda */
        .form-help {
            font-size: 14px;
            color: #6c757d;
            margin-top: 5px;
            font-style: italic;
        }
        
        /* Responsividade */
        @media (max-width: 768px) {
            .header-fixed {
                padding: 12px 15px;
            }
            
            .sidebar {
                top: 70px;
                height: calc(100vh - 70px);
            }
            
            .content-wrapper {
                margin-top: 70px;
                margin-left: 0;
                padding: 15px;
            }
            
            .container {
                padding: 18px;
            }
            
            .profile-info {
                padding: 20px;
            }
            
            .action-buttons {
                flex-direction: column;
            }
            
            .btn {
                width: 100%;
                justify-content: center;
            }
        }
    </style>
</head>
<body>
  <div class="header-fixed">
    <img src="tvitec.png" alt="Logo TVITEC" style="height:40px; margin-right: 15px;">

    <div class="user-info" style="display:flex; align-items:center; gap:10px;">
      <?php if (!empty($_SESSION['foto_perfil'])): ?>
        <img src="<?php echo htmlspecialchars($_SESSION['foto_perfil']); ?>" class="user-photo" alt="Foto do usuário" style="width:40px; height:40px; border-radius:50%;">
      <?php else: ?>
        <div class="user-initial" style="width:40px; height:40px; border-radius:50%; background:#ccc; display:flex; align-items:center; justify-content:center; font-weight:bold; font-size:1.2em;">
          <?php echo strtoupper(substr($_SESSION['nome_usuario'] ?? 'U', 0, 1)); ?>
        </div>
      <?php endif; ?>
      <div style="text-align:left;">
        <div style="font-weight: bold; color: #333; font-size: 1.1em;">
          <?php echo htmlspecialchars($_SESSION['nome_usuario'] ?? 'Usuário'); ?>
        </div>
        <div style="font-size: 0.9em; color: #555;">
          <?php echo htmlspecialchars($_SESSION['email_usuario'] ?? ''); ?>
        </div>
      </div>
    </div>
  </div>

  <?php include 'menu_lateral.php'; ?>

  <div class="content-wrapper">
    <div class="container">
      <div class="profile-container">
        <h2><i class="fas fa-user-edit"></i> Editar Perfil</h2>
        
        <?php if ($erro): ?>
            <div class="alert alert-error">
                <i class="fas fa-exclamation-circle"></i>
                <span><?= htmlspecialchars($erro) ?></span>
            </div>
        <?php endif; ?>
        
        <?php if ($sucesso): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <span><?= htmlspecialchars($sucesso) ?></span>
            </div>
        <?php endif; ?>
        
        <div class="profile-info">
            <form method="post" autocomplete="off">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf_token) ?>">
                
                <div class="form-group">
                    <label for="nome" class="required">Nome:</label>
                    <input type="text" id="nome" name="nome" value="<?= htmlspecialchars($usuario['nome'] ?? '') ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="email" class="required">E-mail:</label>
                    <input type="email" id="email" name="email" value="<?= htmlspecialchars($usuario['email'] ?? '') ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="telefone">Telefone:</label>
                    <input type="text" id="telefone" name="telefone" value="<?= htmlspecialchars($usuario['telefone'] ?? '') ?>">
                </div>
                
                <div class="form-group">
                    <label for="cargo">Cargo:</label>
                    <input type="text" id="cargo" name="cargo" value="<?= htmlspecialchars($usuario['cargo'] ?? '') ?>">
                </div>
                
                <div class="form-group">
                    <label for="nova_senha">Nova Senha:</label>
                    <input type="password" id="nova_senha" name="nova_senha" placeholder="Deixe em branco para não alterar" autocomplete="new-password">
                    <div class="form-help">Mínimo de 8 caracteres</div>
                </div>
                
                <div class="form-group">
                    <label for="confirmar_senha">Confirmar Nova Senha:</label>
                    <input type="password" id="confirmar_senha" name="confirmar_senha" autocomplete="new-password">
                </div>
                
                <div class="action-buttons">
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-save"></i> Salvar Alterações
                    </button>
                    
                    <a href="perfil_usuario.php" class="btn btn-secondary">
                        <i class="fas fa-times"></i> Cancelar
                    </a>
                </div>
            </form>
        </div>
      </div>
    </div>
  </div>

  <script>
    document.addEventListener("DOMContentLoaded", function () {
        // Limpa campos de senha para evitar autofill persistente
        const novaSenha = document.getElementById("nova_senha");
        const confirmarSenha = document.getElementById("confirmar_senha");
        
        if (novaSenha) novaSenha.value = "";
        if (confirmarSenha) confirmarSenha.value = "";
        
        // Fechar alertas automaticamente após 5 segundos
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => {
            setTimeout(() => {
                alert.style.transition = 'opacity 0.5s ease';
                alert.style.opacity = '0';
                setTimeout(() => {
                    if (alert.parentNode) {
                        alert.parentNode.removeChild(alert);
                    }
                }, 500);
            }, 5000);
        });
        
        // Fechar alerta ao clicar no X
        alerts.forEach(alert => {
            const closeBtn = document.createElement('button');
            closeBtn.innerHTML = '&times;';
            closeBtn.style.cssText = `
                background: none;
                border: none;
                color: inherit;
                font-size: 20px;
                cursor: pointer;
                margin-left: auto;
                padding: 0;
                line-height: 1;
            `;
            closeBtn.addEventListener('click', () => {
                alert.style.transition = 'opacity 0.3s ease';
                alert.style.opacity = '0';
                setTimeout(() => {
                    if (alert.parentNode) {
                        alert.parentNode.removeChild(alert);
                    }
                }, 300);
            });
            alert.style.display = 'flex';
            alert.style.alignItems = 'center';
            alert.appendChild(closeBtn);
        });
        
        // Validação de senhas em tempo real
        const novaSenhaInput = document.getElementById('nova_senha');
        const confirmarSenhaInput = document.getElementById('confirmar_senha');
        
        function validatePasswords() {
            if (novaSenhaInput.value && confirmarSenhaInput.value) {
                if (novaSenhaInput.value !== confirmarSenhaInput.value) {
                    confirmarSenhaInput.style.borderColor = '#dc3545';
                } else {
                    confirmarSenhaInput.style.borderColor = '#28a745';
                }
            } else {
                confirmarSenhaInput.style.borderColor = '#ddd';
            }
        }
        
        if (novaSenhaInput && confirmarSenhaInput) {
            novaSenhaInput.addEventListener('input', validatePasswords);
            confirmarSenhaInput.addEventListener('input', validatePasswords);
        }
    });
  </script>
</body>
</html>
<?php
// Fechar conexão
$conn->close();
?>