<?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'] ?? '');
        $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.';
        } else {
            if (!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 = ?, senha = ? WHERE id = ?");
                $stmt->bind_param("ssssi", $nome, $email, $telefone, $senha_hash, $usuario_id);
            } else {
                $stmt = $conn->prepare("UPDATE usuarios SET nome = ?, email = ?, telefone = ? WHERE id = ?");
                $stmt->bind_param("sssi", $nome, $email, $telefone, $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 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;
        }
        
        .header-fixed h2 {
            margin: 0;
            flex-grow: 1;
            text-align: center;
        }
        
 /* Menu Lateral Recolhível - AGORA NA ESQUERDA */
        .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:hover {
            width: 250px;
        }
*/        
        .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 a:hover {
            background-color: #f5f5f5;
        }
*/       
        .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;
        }

        /* Classes para menu */
        .menu-btn-success {
            color: #6B8E23;
        }
        
        .menu-btn-primary {
            color: #0000FF;
        }
        
        .menu-btn-danger {
            color: #e74c3c;
        }
        
        /* Conteúdo Principal */
        .content-wrapper {
            margin-top: 120px;
            padding: 20px;
        }
        
        .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);
        }
        
        /* Estilos para o perfil */
        .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);
        }
        
        .profile-info ul {
            list-style: none;
            padding: 0;
        }
        
        .profile-info li {
            padding: 15px 0;
            border-bottom: 1px solid #eee;
            font-size: 1.1em;
        }
        
        .profile-info li:last-child {
            border-bottom: none;
        }
        
        .profile-info strong {
            display: inline-block;
            width: 200px;
            color: #555;
        }
        
        /* Responsividade */
        @media (max-width: 768px) {
            .header-fixed {
                padding: 12px 15px;
            }
            
            .header-fixed h2 {
                font-size: 1.3rem;
            }
            
            .content-wrapper {
                margin-top: 80px;
                padding: 15px;
            }
            
            .container {
                padding: 18px;
            }
            
            .profile-info li {
                font-size: 1em;
            }
            
            .profile-info strong {
                width: 120px;
            }
        }
    


        body { font-family: Arial; background: #f5f5f5; padding: 40px; }
        .container { max-width: 600px; margin: 0 auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 0 10px #ccc; }
        h2 { margin-bottom: 20px; }
        .form-group { margin-bottom: 15px; }
        label { display: block; font-weight: bold; margin-bottom: 5px; }
        input[type="text"], input[type="email"], input[type="password"] {
            width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px;
        }
        .btn { background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
        .btn:hover { background: #0056b3; }
        .alert { padding: 10px; border-radius: 4px; margin-bottom: 15px; }
        .alert-success { background: #d4edda; color: #155724; }
        .alert-error { background: #f8d7da; color: #721c24; }
    </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="container">
    <h2><i class="fas fa-user-edit"></i> Editar Perfil</h2>

    <?php if ($erro): ?>
        <div class="alert alert-error"><?= htmlspecialchars($erro) ?></div>
    <?php elseif ($sucesso): ?>
        <div class="alert alert-success"><?= htmlspecialchars($sucesso) ?></div>
    <?php endif; ?>

    <form method="post">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf_token) ?>">

        <div class="form-group">
            <label for="nome">Nome:</label>
            <input type="text" id="nome" name="nome" value="<?= htmlspecialchars($usuario['nome'] ?? '') ?>" required>
        </div>

        <div class="form-group">
            <label for="email">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="nova_senha">Nova Senha:</label>
            <input type="password" id="nova_senha" name="nova_senha" placeholder="Deixe em branco para não alterar">
        </div>

        <div class="form-group">
            <label for="confirmar_senha">Confirmar Nova Senha:</label>
            <input type="password" id="confirmar_senha" name="confirmar_senha">
        </div>

        <button type="submit" class="btn"><i class="fas fa-save"></i> Salvar Alterações</button>
    </form>
</div>

</body>
</html>
