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

// VERIFICAÇÃO COMPATÍVEL COM AMBAS AS ESTRUTURAS
$isSuperAdmin = false;

// Verifica estrutura do arquivo que funciona
if (isset($_SESSION['logado']) && $_SESSION['logado'] && isset($_SESSION['permissao']) && $_SESSION['permissao'] === 'super_admin') {
    $isSuperAdmin = true;
}

// Verifica estrutura do arquivo original
if (isset($_SESSION['usuario']) && isset($_SESSION['usuario']['permissao']) && $_SESSION['usuario']['permissao'] === 'super_admin') {
    $isSuperAdmin = true;
}

if (!$isSuperAdmin) {
    header("HTTP/1.1 403 Forbidden");
    echo "Acesso restrito: apenas super administradores podem acessar esta página.";
    exit;
}

// Processar ativação/inativação do tenant
if (isset($_GET['action']) && isset($_GET['id']) && is_numeric($_GET['id'])) {
    $tenant_id = intval($_GET['id']);
    $action = $_GET['action'];
    
    // Verificar se o tenant existe
    $check_sql = "SELECT id, nome FROM tenants WHERE id = $tenant_id";
    $check_result = $conn->query($check_sql);
    
    if ($check_result && $check_result->num_rows > 0) {
        $tenant = $check_result->fetch_assoc();
        
        if ($action === 'inactivate') {
            // Inativar o tenant
            $update_sql = "UPDATE tenants SET ativo = 0 WHERE id = $tenant_id";
            $message = "Tenant '{$tenant['nome']}' inativado com sucesso!";
            $alert_type = 'warning';
        } elseif ($action === 'activate') {
            // Ativar o tenant
            $update_sql = "UPDATE tenants SET ativo = 1 WHERE id = $tenant_id";
            $message = "Tenant '{$tenant['nome']}' ativado com sucesso!";
            $alert_type = 'success';
        }
        
        if (isset($update_sql)) {
            if ($conn->query($update_sql)) {
                $_SESSION['alert_message'] = $message;
                $_SESSION['alert_type'] = $alert_type;
            } else {
                $_SESSION['alert_message'] = "Erro ao atualizar o tenant: " . $conn->error;
                $_SESSION['alert_type'] = 'danger';
            }
            
            // Redirecionar para evitar reenvio do formulário
            header("Location: " . $_SERVER['PHP_SELF'] . "?" . http_build_query($_GET));
            exit;
        }
    }
}

// Filtros e pesquisa
$filtroPlano = $_GET['filtro_plano'] ?? '';
$filtroStatus = $_GET['filtro_status'] ?? '';
$pesquisa = trim($_GET['pesquisa'] ?? '');

$where = ["t.ativo IN (0,1)"];

if ($pesquisa !== '') {
    $where[] = "(t.nome LIKE '%" . $conn->real_escape_string($pesquisa) . "%' OR 
                t.cnpj LIKE '%" . $conn->real_escape_string($pesquisa) . "%' OR
                t.razao_social LIKE '%" . $conn->real_escape_string($pesquisa) . "%' OR
                t.nome_fantasia LIKE '%" . $conn->real_escape_string($pesquisa) . "%')";
}

if ($filtroPlano !== '') {
    $where[] = "p.nome = '" . $conn->real_escape_string($filtroPlano) . "'";
}

if ($filtroStatus === 'ativa') {
    $where[] = "l.ativa = 1 AND CURDATE() <= l.data_fim";
} elseif ($filtroStatus === 'inativa') {
    $where[] = "(l.ativa = 0 OR l.ativa IS NULL OR CURDATE() > l.data_fim)";
}

$condicoes = count($where) ? 'WHERE ' . implode(' AND ', $where) : '';

// Estatísticas - CORRIGIDO: Usando LEFT JOIN para contar todos os tenants
$stats_query = "
    SELECT 
        COUNT(*) as total_tenants,
        SUM(CASE WHEN t.ativo = 1 THEN 1 ELSE 0 END) as tenants_ativos,
        SUM(CASE WHEN t.ativo = 0 THEN 1 ELSE 0 END) as tenants_inativos,
        SUM(CASE WHEN l.ativa = 1 AND CURDATE() BETWEEN l.data_inicio AND l.data_fim THEN 1 ELSE 0 END) as licencas_ativas,
        SUM(CASE WHEN l.ativa = 1 AND CURDATE() > l.data_fim THEN 1 ELSE 0 END) as licencas_expiradas
    FROM tenants t
    LEFT JOIN licencas l ON l.tenant_id = t.id
";

$stats_result = $conn->query($stats_query);
$stats = $stats_result->fetch_assoc();

// Tenants próximos do vencimento - Baseado na tabela licencas
$vencimento_proximo = $conn->query("
    SELECT 
        t.id,
        t.nome,
        l.data_fim,
        DATEDIFF(l.data_fim, CURDATE()) as dias_restantes,
        p.nome as plano
    FROM tenants t
    LEFT JOIN licencas l ON t.id = l.tenant_id AND l.ativa = 1
    LEFT JOIN planos p ON t.plano_id = p.id
    WHERE l.data_fim IS NOT NULL 
    AND l.data_fim BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY)
    ORDER BY l.data_fim ASC
    LIMIT 10
")->fetch_all(MYSQLI_ASSOC);

// Top tenants por uso
$top_tenants = $conn->query("
    SELECT 
        t.id,
        t.nome,
        t.quota_padrao_mb,
        COUNT(DISTINCT u.id) as usuarios,
        COUNT(DISTINCT c.id) as clientes,
        COALESCE(SUM(c.espaco_utilizado_mb), 0) as espaco_utilizado
    FROM tenants t
    LEFT JOIN usuarios u ON t.id = u.tenant_id AND u.ativo = 'sim'
    LEFT JOIN clientes c ON t.id = c.tenant_id AND c.deletado_em IS NULL
    GROUP BY t.id, t.nome, t.quota_padrao_mb
    ORDER BY clientes DESC
    LIMIT 5
")->fetch_all(MYSQLI_ASSOC);

// Query principal - CORRIGIDA: Agora faz JOIN direto com planos através do plano_id em tenants
$sql = "
SELECT 
    t.id AS tenant_id,
    t.nome AS empresa,
    t.cnpj,
    t.ativo,
    t.plano_id,
    t.quota_padrao_mb,
    t.notificar_quota_80,
    t.notificar_quota_90,
    t.data_inicio,
    t.data_fim,
    l.data_inicio as licenca_data_inicio,
    l.data_fim as licenca_data_fim,
    l.ativa AS licenca_ativa,
    p.nome AS plano,
    p.max_usuarios,
    p.valor AS valor_plano,
    p.codigo AS codigo_plano,
    p.permite_georreferenciada,
    p.permite_chat,
    p.permite_fluxos,
    p.permite_email_marketing,
    p.permite_formularios,
    p.max_armazenamento_mb,
    (SELECT COUNT(*) FROM usuarios u WHERE u.tenant_id = t.id AND u.ativo = 'sim') AS usuarios_ativos,
    (SELECT COUNT(*) FROM clientes c WHERE c.tenant_id = t.id AND c.deletado_em IS NULL) AS total_clientes
FROM tenants t
LEFT JOIN planos p ON t.plano_id = p.id
LEFT JOIN licencas l ON l.tenant_id = t.id AND l.ativa = 1
$condicoes
ORDER BY t.nome";

$tenants = $conn->query($sql);
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SON - Dashboard de Tenants</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: 20px;
            background-color: #f5f5f5;
            color: #333;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
        }

        .header {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            margin: 0;
            color: #2c3e50;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .btn {
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            color: white;
            cursor: pointer;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            font-size: 14px;
        }

        .btn-success {
            background-color: #2ecc71;
        }

        .btn-success:hover {
            background-color: #27ae60;
        }

        .btn-primary {
            background-color: #3498db;
        }

        .btn-primary:hover {
            background-color: #2980b9;
        }

        .btn-warning {
            background-color: #f39c12;
        }

        .btn-warning:hover {
            background-color: #d68910;
        }

        .btn-danger {
            background-color: #e74c3c;
        }

        .btn-danger:hover {
            background-color: #c0392b;
        }

        .btn-secondary {
            background-color: #95a5a6;
        }

        .btn-secondary:hover {
            background-color: #7f8c8d;
        }

        /* Alertas */
        .alert {
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 4px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            animation: fadeIn 0.5s;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border-left: 4px solid #28a745;
        }

        .alert-warning {
            background-color: #fff3cd;
            color: #856404;
            border-left: 4px solid #ffc107;
        }

        .alert-danger {
            background-color: #f8d7da;
            color: #721c24;
            border-left: 4px solid #dc3545;
        }

        .alert-info {
            background-color: #d1ecf1;
            color: #0c5460;
            border-left: 4px solid #17a2b8;
        }

        .alert-close {
            background: none;
            border: none;
            font-size: 1.5em;
            cursor: pointer;
            color: inherit;
        }

        /* Filtros */
        .filtros {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .filtros-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 15px;
        }

        .form-group {
            margin-bottom: 10px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            color: #2c3e50;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 8px 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .acoes-filtros {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }

        /* Stats Grid */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            text-align: center;
        }

        .stat-value {
            font-size: 2em;
            font-weight: bold;
            color: #2c3e50;
            margin: 10px 0;
        }

        .stat-label {
            color: #7f8c8d;
            font-size: 0.9em;
        }

        /* Alerts */
        .alerts-container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .alert-list {
            margin-top: 15px;
        }

        .alert-item {
            padding: 10px 15px;
            border-radius: 4px;
            background: #fff9e6;
            margin-bottom: 8px;
            border-left: 4px solid #f39c12;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .alert-item.danger {
            background: #ffe6e6;
            border-left-color: #e74c3c;
        }

        .alert-content {
            flex: 1;
        }

        .alert-title {
            font-weight: 600;
            color: #2c3e50;
        }

        .alert-message {
            color: #7f8c8d;
            font-size: 0.9em;
        }

        /* Top Tenants */
        .top-tenants {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .tenant-rank {
            display: flex;
            align-items: center;
            padding: 10px;
            border-bottom: 1px solid #eee;
        }

        .tenant-rank:last-child {
            border-bottom: none;
        }

        .rank-position {
            width: 30px;
            height: 30px;
            background: #3498db;
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 15px;
        }

        .tenant-info {
            flex: 1;
        }

        .tenant-name {
            font-weight: 600;
            color: #2c3e50;
        }

        .tenant-stats {
            color: #7f8c8d;
            font-size: 0.9em;
        }

        /* Table */
        .table-container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        thead {
            background: #2c3e50;
            color: white;
        }

        th {
            padding: 12px 15px;
            text-align: left;
            font-weight: 600;
        }

        tbody tr {
            border-bottom: 1px solid #eee;
        }

        tbody tr:hover {
            background-color: #f9f9f9;
        }

        td {
            padding: 12px 15px;
            vertical-align: middle;
        }

        /* Badges */
        .badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.85em;
            font-weight: 600;
        }

        .badge-success {
            background: #d4edda;
            color: #155724;
        }

        .badge-danger {
            background: #f8d7da;
            color: #721c24;
        }

        .badge-warning {
            background: #fff3cd;
            color: #856404;
        }

        .badge-info {
            background: #d1ecf1;
            color: #0c5460;
        }

        .badge-secondary {
            background: #e2e3e5;
            color: #383d41;
        }

        .badge-premium {
            background: linear-gradient(45deg, #FFD700, #FFA500);
            color: #000;
            font-weight: bold;
        }

        .badge-enterprise {
            background: linear-gradient(45deg, #8B008B, #4B0082);
            color: white;
            font-weight: bold;
        }

        /* Actions */
        .btn-small {
            padding: 5px 10px;
            font-size: 0.85em;
            border-radius: 3px;
            margin: 2px;
        }

        .actions-cell {
            white-space: nowrap;
        }

        /* Feature Icons */
        .feature-icons {
            display: flex;
            gap: 5px;
            margin-top: 5px;
        }

        .feature-icon {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.7em;
            background: #eee;
            color: #666;
        }

        .feature-icon.active {
            background: #3498db;
            color: white;
        }

        /* Modal de Confirmação */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            animation: fadeIn 0.3s;
        }

        .modal-content {
            background-color: white;
            margin: 10% auto;
            padding: 20px;
            border-radius: 8px;
            width: 80%;
            max-width: 500px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            animation: slideIn 0.3s;
        }

        @keyframes slideIn {
            from { transform: translateY(-50px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }

        .modal-header {
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }

        .modal-title {
            margin: 0;
            color: #2c3e50;
        }

        .modal-body {
            padding: 10px 0;
            margin-bottom: 20px;
        }

        .modal-footer {
            border-top: 1px solid #eee;
            padding-top: 20px;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        /* Informações adicionais */
        .info-box {
            background: #f8f9fa;
            border-left: 4px solid #3498db;
            padding: 10px 15px;
            margin: 10px 0;
            border-radius: 0 4px 4px 0;
        }

        .info-box.warning {
            border-left-color: #f39c12;
            background: #fff9e6;
        }

        .info-box.danger {
            border-left-color: #e74c3c;
            background: #ffe6e6;
        }

        .valor-plano {
            font-size: 0.9em;
            color: #666;
            margin-top: 5px;
            font-style: italic;
        }

        .plano-info {
            font-size: 0.85em;
            color: #666;
            margin-top: 3px;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .header {
                flex-direction: column;
                gap: 15px;
                text-align: center;
            }
            
            .filtros-grid {
                grid-template-columns: 1fr;
            }
            
            .acoes-filtros {
                flex-direction: column;
            }
            
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .table-container {
                padding: 10px;
            }
            
            table {
                font-size: 0.9em;
            }
            
            th, td {
                padding: 8px 5px;
            }
            
            .modal-content {
                width: 95%;
                margin: 5% auto;
            }
        }

        @media (max-width: 480px) {
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            body {
                padding: 10px;
            }
            
            .btn-small {
                padding: 4px 6px;
                font-size: 0.8em;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <h1>
                <i class="fas fa-tachometer-alt"></i>
                Dashboard de Tenants
            </h1>
            <div>
                <a href="cadastrar_tenant.php" class="btn btn-success">
                    <i class="fas fa-plus"></i> Novo Tenant
                </a>
                <a href="lista_tenants.php" class="btn btn-primary">
                    <i class="fas fa-list"></i> Lista Completa
                </a>
            </div>
        </div>

        <!-- Alertas de Sistema -->
        <?php if (isset($_SESSION['alert_message'])): ?>
        <div class="alert alert-<?= $_SESSION['alert_type'] ?>" id="system-alert">
            <div>
                <strong>
                    <?php if ($_SESSION['alert_type'] === 'success'): ?>
                        <i class="fas fa-check-circle"></i>
                    <?php elseif ($_SESSION['alert_type'] === 'warning'): ?>
                        <i class="fas fa-exclamation-triangle"></i>
                    <?php elseif ($_SESSION['alert_type'] === 'danger'): ?>
                        <i class="fas fa-times-circle"></i>
                    <?php else: ?>
                        <i class="fas fa-info-circle"></i>
                    <?php endif; ?>
                    <?= htmlspecialchars($_SESSION['alert_message']) ?>
                </strong>
            </div>
            <button class="alert-close" onclick="document.getElementById('system-alert').style.display='none'">&times;</button>
        </div>
        <?php 
        unset($_SESSION['alert_message']);
        unset($_SESSION['alert_type']);
        endif; 
        ?>

        <!-- Modal de Confirmação -->
        <div id="confirmationModal" class="modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title" id="modalTitle">Confirmar Ação</h3>
                </div>
                <div class="modal-body" id="modalBody">
                    Tem certeza que deseja realizar esta ação?
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancelar</button>
                    <button type="button" class="btn" id="confirmButton">Confirmar</button>
                </div>
            </div>
        </div>

        <!-- Filtros -->
        <div class="filtros">
            <form method="GET">
                <div class="filtros-grid">
                    <div class="form-group">
                        <label for="pesquisa"><i class="fas fa-search"></i> Buscar</label>
                        <input type="text" name="pesquisa" id="pesquisa" 
                               placeholder="Nome, CNPJ, razão social..." 
                               value="<?= htmlspecialchars($pesquisa) ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="filtro_plano"><i class="fas fa-layer-group"></i> Plano</label>
                        <select name="filtro_plano" id="filtro_plano">
                            <option value="">Todos os Planos</option>
                            <?php
                            // Buscar planos disponíveis do banco de dados
                            $planos_query = $conn->query("SELECT id, nome FROM planos ORDER BY id");
                            while($plano = $planos_query->fetch_assoc()):
                            ?>
                            <option value="<?= $plano['id'] ?>" 
                                    <?= $filtroPlano == $plano['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($plano['nome']) ?>
                            </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="filtro_status"><i class="fas fa-shield-alt"></i> Status Licença</label>
                        <select name="filtro_status" id="filtro_status">
                            <option value="">Todas as Licenças</option>
                            <option value="ativa" <?= $filtroStatus === 'ativa' ? 'selected' : '' ?>>Ativa</option>
                            <option value="inativa" <?= $filtroStatus === 'inativa' ? 'selected' : '' ?>>Inativa/Vencida</option>
                        </select>
                    </div>
                </div>
                
                <div class="acoes-filtros">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-filter"></i> Filtrar
                    </button>
                    <a href="dashboard_tenants.php" class="btn btn-warning">
                        <i class="fas fa-times"></i> Limpar Filtros
                    </a>
                </div>
            </form>
        </div>

        <!-- Estatísticas -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-value"><?= $stats['total_tenants'] ?? 0 ?></div>
                <div class="stat-label">Total de Tenants</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-value"><?= $stats['tenants_ativos'] ?? 0 ?></div>
                <div class="stat-label">Tenants Ativos</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-value"><?= $stats['tenants_inativos'] ?? 0 ?></div>
                <div class="stat-label">Tenants Inativos</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-value"><?= $stats['licencas_ativas'] ?? 0 ?></div>
                <div class="stat-label">Licenças Ativas</div>
            </div>
        </div>

        <!-- Alertas de Vencimento -->
        <?php if (!empty($vencimento_proximo)): ?>
        <div class="alerts-container">
            <h3><i class="fas fa-exclamation-triangle"></i> Licenças Próximas do Vencimento</h3>
            <div class="alert-list">
                <?php foreach ($vencimento_proximo as $vencimento): ?>
                <div class="alert-item <?= $vencimento['dias_restantes'] <= 3 ? 'danger' : '' ?>">
                    <div class="alert-content">
                        <div class="alert-title">
                            <?= htmlspecialchars($vencimento['nome']) ?> - <?= $vencimento['plano'] ?>
                        </div>
                        <div class="alert-message">
                            Vence em <?= $vencimento['dias_restantes'] ?> dias 
                            (<?= date('d/m/Y', strtotime($vencimento['data_fim'])) ?>)
                        </div>
                    </div>
                    <a href="editar_tenant.php?id=<?= $vencimento['id'] ?>" class="btn btn-small btn-primary">
                        <i class="fas fa-edit"></i> Ver
                    </a>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Top Tenants -->
        <?php if (!empty($top_tenants)): ?>
        <div class="top-tenants">
            <h3><i class="fas fa-trophy"></i> Top 5 Tenants (por clientes)</h3>
            <div class="alert-list">
                <?php foreach ($top_tenants as $index => $tenant): ?>
                <div class="tenant-rank">
                    <div class="rank-position"><?= $index + 1 ?></div>
                    <div class="tenant-info">
                        <div class="tenant-name"><?= htmlspecialchars($tenant['nome']) ?></div>
                        <div class="tenant-stats">
                            <?= $tenant['clientes'] ?> clientes • 
                            <?= $tenant['usuarios'] ?> usuários • 
                            <?= number_format($tenant['espaco_utilizado'], 1) ?> MB usado
                        </div>
                    </div>
                    <a href="editar_tenant.php?id=<?= $tenant['id'] ?>" class="btn btn-small btn-primary">
                        <i class="fas fa-eye"></i>
                    </a>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Tabela de Tenants -->
        <div class="table-container">
            <h3 style="margin: 0 0 15px 0; color: #2c3e50;">
                <i class="fas fa-table"></i> Lista de Tenants
                <span style="font-size: 0.9em; color: #7f8c8d; font-weight: normal;">
                    (<?= $tenants->num_rows ?> resultado(s))
                </span>
            </h3>
            
            <?php if ($tenants->num_rows > 0): ?>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Empresa</th>
                        <th>Plano</th>
                        <th>Licença</th>
                        <th>Status</th>
                        <th>Clientes</th>
                        <th>Usuários</th>
                        <th>Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while($row = $tenants->fetch_assoc()): 
                        // Verificar se tem licença ativa
                        $licenca_valida = $row['licenca_ativa'] && $row['licenca_data_fim'] && $row['licenca_data_fim'] >= date('Y-m-d');
                        $dias_restantes = 0;
                        
                        if ($row['licenca_data_fim']) {
                            $hoje = new DateTime();
                            $data_fim = new DateTime($row['licenca_data_fim']);
                            $dias_restantes = $hoje->diff($data_fim)->days;
                            if ($hoje > $data_fim) {
                                $dias_restantes = -$dias_restantes;
                            }
                        }
                    ?>
                    <tr>
                        <td>#<?= $row['tenant_id'] ?></td>
                        <td>
                            <strong><?= htmlspecialchars($row['empresa']) ?></strong><br>
                            <small style="color: #666;">
                                <?= $row['cnpj'] ? 'CNPJ: ' . htmlspecialchars($row['cnpj']) : 'Sem CNPJ' ?>
                            </small>
                        </td>
                        <td>
                            <?php if ($row['plano']): ?>
                                <span class="badge 
                                    <?= $row['codigo_plano'] == 'basic' ? 'badge-info' : 
                                       ($row['codigo_plano'] == 'pro' ? 'badge-warning' : 
                                       ($row['codigo_plano'] == 'enterprise' ? 'badge-enterprise' : 'badge-secondary')) ?>">
                                    <?= htmlspecialchars($row['plano']) ?>
                                </span>
                                <div class="plano-info">
                                    <?php if ($row['valor_plano']): ?>
                                        R$ <?= number_format($row['valor_plano'], 2, ',', '.') ?> •
                                    <?php endif; ?>
                                    <?= $row['max_usuarios'] ?> usuários •
                                    <?= $row['max_armazenamento_mb'] ?> MB
                                </div>
                                <?php if ($row['permite_chat'] || $row['permite_fluxos'] || $row['permite_email_marketing'] || $row['permite_formularios'] || $row['permite_georreferenciada']): ?>
                                <div class="feature-icons">
                                    <?php if ($row['permite_chat']): ?><span class="feature-icon active" title="Chat"><i class="fas fa-comments"></i></span><?php endif; ?>
                                    <?php if ($row['permite_fluxos']): ?><span class="feature-icon active" title="Fluxos"><i class="fas fa-stream"></i></span><?php endif; ?>
                                    <?php if ($row['permite_email_marketing']): ?><span class="feature-icon active" title="E-mail Marketing"><i class="fas fa-envelope"></i></span><?php endif; ?>
                                    <?php if ($row['permite_formularios']): ?><span class="feature-icon active" title="Formulários"><i class="fas fa-list-alt"></i></span><?php endif; ?>
                                    <?php if ($row['permite_georreferenciada']): ?><span class="feature-icon active" title="Georreferenciada"><i class="fas fa-map-marker-alt"></i></span><?php endif; ?>
                                </div>
                                <?php endif; ?>
                            <?php else: ?>
                                <span class="badge badge-danger">PLANO ID <?= $row['plano_id'] ?> NÃO ENCONTRADO</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($row['licenca_data_inicio'] && $row['licenca_data_fim']): ?>
                                <div style="font-size: 0.9em;">
                                    <div><strong>De:</strong> <?= date('d/m/Y', strtotime($row['licenca_data_inicio'])) ?></div>
                                    <div><strong>Até:</strong> <?= date('d/m/Y', strtotime($row['licenca_data_fim'])) ?></div>
                                    <?php if ($row['licenca_ativa'] && $licenca_valida): ?>
                                        <span class="badge badge-success">Ativa</span>
                                        <small style="color: #666;">(<?= $dias_restantes ?> dias restantes)</small>
                                    <?php elseif ($row['licenca_ativa'] && !$licenca_valida): ?>
                                        <span class="badge badge-danger">Expirada há <?= abs($dias_restantes) ?> dias</span>
                                    <?php else: ?>
                                        <span class="badge badge-secondary">Inativa</span>
                                    <?php endif; ?>
                                </div>
                            <?php elseif ($row['data_inicio'] && $row['data_fim']): ?>
                                <div style="font-size: 0.9em;">
                                    <div><strong>Início:</strong> <?= date('d/m/Y', strtotime($row['data_inicio'])) ?></div>
                                    <div><strong>Vigência:</strong> <?= $row['data_fim'] ? date('d/m/Y', strtotime($row['data_fim'])) : 'Indeterminada' ?></div>
                                    <span class="badge badge-info">Vigente</span>
                                </div>
                            <?php else: ?>
                                <span class="badge badge-secondary">Sem licença ativa</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="badge <?= $row['ativo'] ? 'badge-success' : 'badge-danger' ?>">
                                <?= $row['ativo'] ? 'Ativo' : 'Inativo' ?>
                            </span>
                        </td>
                        <td>
                            <?= $row['total_clientes'] ?><br>
                            <small style="color: #666;">
                                Quota: <?= $row['quota_padrao_mb'] ?> MB
                                <?php if ($row['notificar_quota_80']): ?><i class="fas fa-bell" title="Notifica em 80%"></i><?php endif; ?>
                                <?php if ($row['notificar_quota_90']): ?><i class="fas fa-bell" title="Notifica em 90%" style="color: #e74c3c;"></i><?php endif; ?>
                            </small>
                        </td>
                        <td>
                            <strong><?= $row['usuarios_ativos'] ?></strong>
                            <?php if ($row['max_usuarios']): ?>
                                <br><small style="color: <?= $row['usuarios_ativos'] >= $row['max_usuarios'] ? '#e74c3c' : '#666' ?>;">
                                    / <?= $row['max_usuarios'] ?> limite 
                                    (<?= $row['max_usuarios'] > 0 ? round(($row['usuarios_ativos'] / $row['max_usuarios']) * 100, 0) : 0 ?>%)
                                </small>
                            <?php endif; ?>
                        </td>
                        <td class="actions-cell">
                            <a href="editar_tenant.php?id=<?= $row['tenant_id'] ?>" 
                               class="btn btn-small btn-primary" title="Editar">
                                <i class="fas fa-edit"></i>
                            </a>
                            <a href="lista_tenants.php?pesquisa=<?= urlencode($row['empresa']) ?>" 
                               class="btn btn-small btn-warning" title="Ver Detalhes">
                                <i class="fas fa-eye"></i>
                            </a>
                            <?php if ($row['ativo']): ?>
                            <button type="button" 
                                    class="btn btn-small btn-danger" 
                                    title="Inativar Tenant"
                                    onclick="showConfirmation(<?= $row['tenant_id'] ?>, 'inactivate', '<?= htmlspecialchars(addslashes($row['empresa'])) ?>')">
                                <i class="fas fa-ban"></i>
                            </button>
                            <?php else: ?>
                            <button type="button" 
                                    class="btn btn-small btn-success" 
                                    title="Ativar Tenant"
                                    onclick="showConfirmation(<?= $row['tenant_id'] ?>, 'activate', '<?= htmlspecialchars(addslashes($row['empresa'])) ?>')">
                                <i class="fas fa-check"></i>
                            </button>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
            <?php else: ?>
                <div style="text-align: center; padding: 40px; color: #666;">
                    <i class="fas fa-building" style="font-size: 3em; margin-bottom: 20px; display: block; opacity: 0.3;"></i>
                    Nenhum tenant encontrado com os filtros atuais.
                    <?php if ($pesquisa || $filtroPlano || $filtroStatus): ?>
                        <br><small>Tente ajustar os filtros acima.</small>
                    <?php else: ?>
                        <br><small><a href="cadastrar_tenant.php">Cadastre o primeiro tenant</a>.</small>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        // Modal de Confirmação
        let currentAction = '';
        let currentId = 0;
        let currentTenantName = '';

        function showConfirmation(id, action, tenantName) {
            currentId = id;
            currentAction = action;
            currentTenantName = tenantName;
            
            const modal = document.getElementById('confirmationModal');
            const title = document.getElementById('modalTitle');
            const body = document.getElementById('modalBody');
            const confirmBtn = document.getElementById('confirmButton');
            
            if (action === 'inactivate') {
                title.innerHTML = '<i class="fas fa-ban"></i> Inativar Tenant';
                body.innerHTML = `
                    <p>Tem certeza que deseja inativar o tenant <strong>"${tenantName}"</strong>?</p>
                    <p style="color: #e74c3c; font-size: 0.9em;">
                        <i class="fas fa-exclamation-triangle"></i> Ao inativar:
                    </p>
                    <ul style="font-size: 0.9em; color: #666; margin-left: 20px;">
                        <li>O tenant não poderá mais acessar o sistema</li>
                        <li>Os usuários do tenant perderão acesso</li>
                        <li>Os dados serão mantidos no banco de dados</li>
                        <li>É possível reativar o tenant futuramente</li>
                    </ul>
                `;
                confirmBtn.className = 'btn btn-danger';
                confirmBtn.innerHTML = '<i class="fas fa-ban"></i> Inativar';
            } else if (action === 'activate') {
                title.innerHTML = '<i class="fas fa-check"></i> Ativar Tenant';
                body.innerHTML = `
                    <p>Tem certeza que deseja ativar o tenant <strong>"${tenantName}"</strong>?</p>
                    <p style="color: #2ecc71; font-size: 0.9em;">
                        <i class="fas fa-info-circle"></i> Ao ativar:
                    </p>
                    <ul style="font-size: 0.9em; color: #666; margin-left: 20px;">
                        <li>O tenant terá acesso ao sistema novamente</li>
                        <li>Os usuários do tenant recuperarão o acesso</li>
                        <li>A licença atual será considerada</li>
                    </ul>
                `;
                confirmBtn.className = 'btn btn-success';
                confirmBtn.innerHTML = '<i class="fas fa-check"></i> Ativar';
            }
            
            modal.style.display = 'block';
        }

        function closeModal() {
            document.getElementById('confirmationModal').style.display = 'none';
            currentAction = '';
            currentId = 0;
            currentTenantName = '';
        }

        function confirmAction() {
            if (currentId && currentAction) {
                // Construir a URL com todos os parâmetros atuais
                const urlParams = new URLSearchParams(window.location.search);
                urlParams.set('action', currentAction);
                urlParams.set('id', currentId);
                
                // Redirecionar para executar a ação
                window.location.href = window.location.pathname + '?' + urlParams.toString();
            }
        }

        // Configurar o botão de confirmação
        document.getElementById('confirmButton').addEventListener('click', confirmAction);

        // Fechar modal ao clicar fora
        window.onclick = function(event) {
            const modal = document.getElementById('confirmationModal');
            if (event.target == modal) {
                closeModal();
            }
        }

        // Fechar modal com ESC
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeModal();
            }
        });

        // Auto-focar na busca se tiver valor
        document.addEventListener('DOMContentLoaded', function() {
            const pesquisa = document.getElementById('pesquisa');
            if (pesquisa && pesquisa.value === '') {
                pesquisa.focus();
            }
            
            // Fechar alerta do sistema automaticamente após 5 segundos
            const systemAlert = document.getElementById('system-alert');
            if (systemAlert) {
                setTimeout(() => {
                    systemAlert.style.display = 'none';
                }, 5000);
            }
        });

        // Atalhos de teclado
        document.addEventListener('keydown', function(e) {
            // Ctrl+F para focar na busca
            if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
                e.preventDefault();
                const pesquisa = document.getElementById('pesquisa');
                if (pesquisa) {
                    pesquisa.focus();
                    pesquisa.select();
                }
            }
            
            // ESC para limpar filtros (se modal não estiver aberto)
            if (e.key === 'Escape' && !document.getElementById('confirmationModal').style.display === 'block') {
                window.location.href = 'dashboard_tenants.php';
            }
            
            // N para novo tenant
            if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
                e.preventDefault();
                window.location.href = 'cadastrar_tenant.php';
            }
            
            // L para lista completa
            if ((e.ctrlKey || e.metaKey) && e.key === 'l') {
                e.preventDefault();
                window.location.href = 'lista_tenants.php';
            }
        });
    </script>
</body>
</html>
<?php
$conn->close();
?>