<?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'];

// Carregar dados do usuário
$stmt = $conn->prepare("SELECT nome, email, telefone, data_criacao, tenant_id FROM usuarios WHERE id = ?");
$stmt->bind_param("i", $usuario_id);
$stmt->execute();
$result = $stmt->get_result();
$usuario = $result->fetch_assoc();
$stmt->close();

// Buscar informações do tenant (empresa) - CORRIGIDO: usar tenant_id da sessão
$tenant_id = $_SESSION['tenant_id'] ?? $usuario['tenant_id'] ?? null;
$empresa_nome = 'Não informada';
$plano_contratado = 'Não informado';

if ($tenant_id) {
    $stmt_tenant = $conn->prepare("SELECT nome_fantasia, razao_social, plano_id FROM tenants WHERE id = ?");
    $stmt_tenant->bind_param("i", $tenant_id);
    $stmt_tenant->execute();
    $result_tenant = $stmt_tenant->get_result();
    
    if ($tenant_data = $result_tenant->fetch_assoc()) {
        // Usar nome_fantasia ou razao_social como nome da empresa
        $empresa_nome = $tenant_data['nome_fantasia'] ?? $tenant_data['razao_social'] ?? 'Não informada';
        
        // Buscar nome do plano
        if (isset($tenant_data['plano_id'])) {
            $stmt_plano = $conn->prepare("SELECT nome FROM planos WHERE id = ?");
            $stmt_plano->bind_param("i", $tenant_data['plano_id']);
            $stmt_plano->execute();
            $result_plano = $stmt_plano->get_result();
            
            if ($plano_data = $result_plano->fetch_assoc()) {
                $plano_contratado = $plano_data['nome'] ?? 'Não informado';
            }
            $stmt_plano->close();
        }
    }
    $stmt_tenant->close();
}

// ID do tenant para exibição
$id_exibicao = $tenant_id ?? 'Não informado';
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <title>Perfil do Usuário</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 - CORRIGIDO PARA 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-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; /* Espaço para o menu lateral */
            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);
        }
        
        .profile-info ul {
            list-style: none;
            padding: 0;
        }
        
        .profile-info li {
            padding: 15px 0;
            border-bottom: 1px solid #eee;
            font-size: 1.1em;
            display: flex;
            justify-content: space-between;
        }
        
        .profile-info li:last-child {
            border-bottom: none;
        }
        
        .profile-info strong {
            color: #555;
            min-width: 200px;
        }
        
        .profile-info span {
            color: #333;
            text-align: right;
        }
        
        .action-buttons {
            margin-top: 30px;
            display: flex;
            gap: 15px;
        }
        
        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            font-size: 1em;
            transition: background-color 0.3s;
        }
        
        .btn-primary {
            background: #007bff;
            color: white;
        }
        
        .btn-primary:hover {
            background: #0056b3;
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background: #1e7e34;
        }

        @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 li {
                flex-direction: column;
                gap: 5px;
            }
            
            .action-buttons {
                flex-direction: column;
            }
        }
    </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"></i> Perfil do Usuário</h2>
        
        <div class="profile-info">
          <ul>
            <li>
              <strong>Nome:</strong>
              <span><?php echo htmlspecialchars($usuario['nome'] ?? 'Não informado'); ?></span>
            </li>
            <li>
              <strong>E-mail:</strong>
              <span><?php echo htmlspecialchars($usuario['email'] ?? 'Não informado'); ?></span>
            </li>
            <li>
              <strong>Telefone:</strong>
              <span><?php echo htmlspecialchars($usuario['telefone'] ?? 'Não informado'); ?></span>
            </li>
            <li>
              <strong>Empresa:</strong>
              <span><?php echo htmlspecialchars($empresa_nome); ?></span>
            </li>
            <li>
              <strong>ID:</strong>
              <span><?php echo htmlspecialchars($id_exibicao); ?></span>
            </li>
            <li>
              <strong>Início:</strong>
              <span><?php 
                if (isset($usuario['data_criacao'])) {
                    echo date('d/m/Y', strtotime($usuario['data_criacao']));
                } else {
                    echo 'Não informado';
                }
              ?></span>
            </li>
            <li>
              <strong>Plano Contratado:</strong>
              <span><?php echo htmlspecialchars($plano_contratado); ?></span>
            </li>
          </ul>
          
          <div class="action-buttons">
            <a href="editar_perfil.php" class="btn btn-primary">
              <i class="fas fa-edit"></i> Editar Perfil
            </a>
            
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>