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

if (!isset($_SESSION['usuario']) || $_SESSION['usuario']['permissao'] !== 'super_admin') {
    header("HTTP/1.1 403 Forbidden");
    echo "Acesso restrito: apenas super administradores podem acessar esta página.";
    exit;
}

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

$where = [];

if ($pesquisa !== '') {
    $where[] = "t.nome 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 IS NULL OR CURDATE() > l.data_fim)";
}

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

// Contadores
$totalTenants = $conn->query("SELECT COUNT(*) AS total FROM tenants")->fetch_assoc()['total'];
$tenantsAtivos = $conn->query("SELECT COUNT(*) AS total FROM tenants WHERE ativo = 1")->fetch_assoc()['total'];
$licencasAtivas = $conn->query("SELECT COUNT(*) AS total FROM licencas WHERE ativa = 1 AND CURDATE() BETWEEN data_inicio AND data_fim")->fetch_assoc()['total'];
$licencasExpiradas = $conn->query("SELECT COUNT(*) AS total FROM licencas WHERE ativa = 1 AND CURDATE() > data_fim")->fetch_assoc()['total'];

// Query principal
$sql = "
SELECT 
    t.id AS tenant_id,
    t.nome AS empresa,
    t.ativo,
    l.data_inicio,
    l.data_fim,
    l.ativa AS licenca_ativa,
    p.nome AS plano,
    (SELECT COUNT(*) FROM usuarios u WHERE u.tenant_id = t.id) AS total_usuarios
FROM tenants t
LEFT JOIN licencas l ON l.tenant_id = t.id AND l.ativa = 1
LEFT JOIN planos p ON p.id = l.plano_id
$condicoes
GROUP BY t.id
ORDER BY t.nome";

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

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Dashboard de Tenants</title>
    <style>
        body { font-family: Arial, sans-serif; background: #f7f7f7; padding: 20px; }
        .card { background: #fff; padding: 15px 25px; border-radius: 8px; box-shadow: 0 0 5px rgba(0,0,0,.1); margin-bottom: 20px; }
        .grid { display: flex; gap: 20px; flex-wrap: wrap; }
        .grid .card { flex: 1 1 200px; text-align: center; }
        h2 { margin-bottom: 10px; }
        table { width: 100%; border-collapse: collapse; background: #fff; margin-top: 20px; }
        th, td { padding: 10px; border: 1px solid #ddd; text-align: center; }
        th { background: #f0f0f0; }
        .ativo { color: green; font-weight: bold; }
        .inativo { color: red; font-weight: bold; }
        .filtros { margin: 20px 0; display: flex; gap: 10px; flex-wrap: wrap; }
        .filtros input, .filtros select { padding: 8px; }
    </style>
</head>
<body>
    <h1>Dashboard de Tenants e Licenças</h1>

    <div class="grid">
        <div class="card"><h2>Total de Tenants</h2><p><?= $totalTenants ?></p></div>
        <div class="card"><h2>Tenants Ativos</h2><p><?= $tenantsAtivos ?></p></div>
        <div class="card"><h2>Licenças Ativas</h2><p><?= $licencasAtivas ?></p></div>
        <div class="card"><h2>Licenças Expiradas</h2><p><?= $licencasExpiradas ?></p></div>
    </div>

    <form method="GET" class="filtros">
        <input type="text" name="pesquisa" placeholder="Buscar empresa..." value="<?= htmlspecialchars($pesquisa) ?>">
        <select name="filtro_plano">
            <option value="">Todos os Planos</option>
            <option value="Free" <?= $filtroPlano === 'Free' ? 'selected' : '' ?>>Free</option>
            <option value="Basic" <?= $filtroPlano === 'Basic' ? 'selected' : '' ?>>Basic</option>
            <option value="Pro" <?= $filtroPlano === 'Pro' ? 'selected' : '' ?>>Pro</option>
            <option value="Plus" <?= $filtroPlano === 'Plus' ? 'selected' : '' ?>>Plus</option>
        </select>
        <select name="filtro_status">
            <option value="">Todas as Licenças</option>
            <option value="ativa" <?= $filtroStatus === 'ativa' ? 'selected' : '' ?>>Ativa</option>
            <option value="inativa" <?= $filtroStatus === 'inativa' ? 'selected' : '' ?>>Inativa</option>
        </select>
        <button type="submit">Filtrar</button>
    </form>

    <h2>Detalhes por Tenant</h2>
    <table>
        <tr>
            <th>Empresa</th>
            <th>Plano</th>
            <th>Início</th>
            <th>Fim</th>
            <th>Status da Licença</th>
            <th>Usuários</th>
            <th>Tenant Ativo?</th>
        </tr>
        <?php while($row = $tenants->fetch_assoc()): ?>
            <tr>
                <td><?= htmlspecialchars($row['empresa']) ?></td>
                <td><?= $row['plano'] ?? '---' ?></td>
                <td><?= $row['data_inicio'] ?? '---' ?></td>
                <td><?= $row['data_fim'] ?? '---' ?></td>
                <td><?= ($row['licenca_ativa'] && $row['data_fim'] >= date('Y-m-d')) ? "<span class='ativo'>Ativa</span>" : "<span class='inativo'>Inativa</span>" ?></td>
                <td><?= $row['total_usuarios'] ?></td>
                <td><?= $row['ativo'] ? "<span class='ativo'>Sim</span>" : "<span class='inativo'>Não</span>" ?></td>
            </tr>
        <?php endwhile; ?>
    </table>
</body>
</html>
