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

// --- 1. TRAVA DE SEGURAN脟A TOTAL (KILL SWITCH) ---
if (!isset($_SESSION['logado'])) { header("Location: login.php"); exit; }

$isAdmin = (strtolower($_SESSION['nivel']) === 'admin');
$usuarioLogado = $_SESSION['usuario'];

if (!$isAdmin) {
    $stmtCheck = $connUser->prepare("SELECT bloqueado, data_premio FROM rev WHERE usuario = ? LIMIT 1");
    $stmtCheck->execute([$usuarioLogado]);
    $me = $stmtCheck->fetch(PDO::FETCH_ASSOC);
    if ($me) {
        $isBloq = ($me['bloqueado'] == 'sim');
        $isVenc = ((int)$me['data_premio'] > 0 && (int)$me['data_premio'] < time());
        if ($isBloq || $isVenc) {
            $motivo = $isBloq ? "BLOQUEADO PELO ADMINISTRADOR" : "PLANO VENCIDO";
            die("<!DOCTYPE html><html lang='pt-br'><head><meta charset='UTF-8'><title>Acesso Negado</title><link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'><style>body{background:#151521;color:#fff;display:flex;align-items:center;justify-content:center;height:100vh;text-align:center;}</style></head><body><div><h1 class='text-danger fw-bold' style='font-size: 4rem;'>馃毇</h1><h2 class='fw-bold text-uppercase'>ACESSO SUSPENSO</h2><p class='lead text-muted'>$motivo</p><a href='sair.php' class='btn btn-outline-light mt-4 px-5'>Sair do Painel</a></div></body></html>");
        }
    }
}

// --- 2. CONFIGURA脟脮ES VISUAIS ---
$nomePainel = "IPTV PANEL"; $corPrimaria = "#7367f0"; 
try {
    $conf = $connGeral->query("SELECT NomePainel, TemaPainel FROM site_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($conf) {
        if (!empty($conf['NomePainel'])) $nomePainel = $conf['NomePainel'];
        if (!empty($conf['TemaPainel'])) $corPrimaria = $conf['TemaPainel'];
    }
} catch (Exception $e) { }


// --- FUN脟脙O PARA PEGAR TODA A REDE (REVS E SUB-REVS) ---
if (!function_exists('obterTodaRede')) {
    function obterTodaRede($conn, $dono) {
        $rede = [$dono];
        $buscar = [$dono];
        while (!empty($buscar)) {
            $atual = array_shift($buscar);
            $st = $conn->prepare("SELECT usuario FROM rev WHERE CadUser = ?");
            $st->execute([$atual]);
            $subs = $st->fetchAll(PDO::FETCH_COLUMN);
            foreach ($subs as $sub) {
                if (!in_array($sub, $rede)) {
                    $rede[] = $sub;
                    $buscar[] = $sub;
                }
            }
        }
        return $rede;
    }
}
// --------------------------------------------------------


// --- 3. L脫GICA DO RELAT脫RIO DE FATURA ---
$revendedor_alvo = $usuarioLogado;
$lista_revendedores = [];

// Se for Admin, permite escolher o revendedor
if ($isAdmin) {
    $lista_revendedores = $connUser->query("SELECT usuario FROM rev ORDER BY usuario ASC")->fetchAll(PDO::FETCH_ASSOC);
    if (isset($_GET['revendedor']) && !empty($_GET['revendedor'])) {
        $revendedor_alvo = trim($_GET['revendedor']);
    }
}

// Busca os valores cadastrados para o revendedor alvo
$valor_claro = 0;
$valor_net = 0;
try {
    $stmtRev = $connUser->prepare("SELECT valor_claro, valor_net FROM rev WHERE usuario = ? LIMIT 1");
    $stmtRev->execute([$revendedor_alvo]);
    $dadosRev = $stmtRev->fetch(PDO::FETCH_ASSOC);
    if ($dadosRev) {
        $valor_claro = (float)$dadosRev['valor_claro'];
        $valor_net = (float)$dadosRev['valor_net'];
    }
} catch (Exception $e) {}

// Busca o mapa de perfis (para saber se 茅 claro ou net)
$mapa_perfis = [];
try {
    $perfis = $connGeral->query("SELECT id, nome FROM perfil")->fetchAll(PDO::FETCH_ASSOC);
    foreach($perfis as $p) {
        $mapa_perfis[$p['id']] = $p['nome'];
    }
} catch (Exception $e) {}

// Busca clientes ATIVOS de TODA A 脕RVORE do revendedor alvo
$agora = time();
$rede_completa = obterTodaRede($connUser, $revendedor_alvo);
$placeholders = implode(',', array_fill(0, count($rede_completa), '?'));

$sql_usuarios = "SELECT * FROM usuario WHERE CadUser IN ($placeholders) AND bloqueado != 'sim' AND IF(data_premio REGEXP '^[0-9]+$', CAST(data_premio AS UNSIGNED), UNIX_TIMESTAMP(STR_TO_DATE(data_premio, '%Y-%m-%d'))) > ?";
$stmtUsr = $connUser->prepare($sql_usuarios);

// Prepara os par芒metros para a execu莽茫o segura
$params = $rede_completa;
$params[] = $agora;

$stmtUsr->execute($params);
$usuarios_ativos = $stmtUsr->fetchAll(PDO::FETCH_ASSOC);

$qtd_claro = 0;
$qtd_net = 0;
$total_pagar_claro = 0;
$total_pagar_net = 0;
$lista_detalhada = [];

foreach($usuarios_ativos as $u) {
    // Se o cliente tem mais de 1 tela (conex茫o), cobra por tela
    $conexoes = (isset($u['conexao']) && (int)$u['conexao'] > 0) ? (int)$u['conexao'] : 1;
    
    $id_perfil = $u['perfil'];
    $nome_perfil = isset($mapa_perfis[$id_perfil]) ? $mapa_perfis[$id_perfil] : 'Desconhecido';
    $nome_low = strtolower($nome_perfil);

    // Define se 茅 Claro ou Net
    $tipo = 'claro'; // Padr茫o cai como claro se n茫o especificar
    if (strpos($nome_low, 'net') !== false) {
        $tipo = 'net';
    }

    $valor_cobrado = 0;
    if ($tipo == 'net') {
        $qtd_net += $conexoes;
        $valor_cobrado = $conexoes * $valor_net;
        $total_pagar_net += $valor_cobrado;
    } else {
        $qtd_claro += $conexoes;
        $valor_cobrado = $conexoes * $valor_claro;
        $total_pagar_claro += $valor_cobrado;
    }

    $venc_ts = is_numeric($u['data_premio']) ? (int)$u['data_premio'] : strtotime(str_replace('/', '-', $u['data_premio']));

    $lista_detalhada[] = [
        'nome' => $u['nome'],
        'usuario' => $u['usuario'],
        'perfil_nome' => $nome_perfil,
        'vencimento' => date('d/m/Y', $venc_ts),
        'conexoes' => $conexoes,
        'valor' => $valor_cobrado,
        'tipo' => $tipo
    ];
}

$total_conexoes = $qtd_claro + $qtd_net;
$total_geral = $total_pagar_claro + $total_pagar_net;

?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Relat贸rio de Fatura | <?= htmlspecialchars($nomePainel) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root { --primary: <?= $corPrimaria ?>; --bg-body: #151521; --bg-card: #1e1e2d; --text-color: #d0d2d6; --border-color: #2b2b40; }
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; padding: 0; }
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid #333; z-index: 1050; padding: 20px; overflow-y: auto; transition: 0.3s; }
        .nav-link { color: #a6a6b7; padding: 12px 15px; border-radius: 8px; display: flex; align-items: center; gap: 12px; text-decoration: none; margin-bottom: 5px; font-weight: 500; }
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 25px 0 10px 12px; letter-spacing: 1px; }
        .main-content { margin-left: 260px; transition: 0.3s; min-height: 100vh; }
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--primary) 100%); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; }

        .card-custom { background: var(--bg-card) !important; border: 1px solid var(--border-color); border-radius: 12px; }
        .form-control, .form-select { background: #151521 !important; border: 1px solid #444 !important; color: #fff !important; }
        .table-responsive { background: var(--bg-card) !important; -webkit-overflow-scrolling: touch; }
        .table-video { width: 100%; border-collapse: collapse; white-space: nowrap; }
        .table-video thead th { background: rgba(0,0,0,0.2) !important; color: #ffffff; text-transform: uppercase; font-weight: 700; font-size: 0.75rem; padding: 15px 12px; border-bottom: 1px solid var(--border-color); }
        .table-video td { padding: 12px !important; border-bottom: 1px solid var(--border-color) !important; background: var(--bg-card) !important; color: #fff !important; vertical-align: middle !important; }
        
        .label-visivel { color: #ffffff !important; font-weight: 700; text-transform: uppercase; font-size: 0.75rem; }
        
        .box-valor { background: rgba(115, 103, 240, 0.1); border: 1px solid rgba(115, 103, 240, 0.3); border-radius: 10px; padding: 20px; text-align: center; }
        .box-valor h2 { font-weight: 800; margin: 10px 0 0 0; color: #fff; }
        .box-valor p { color: #a6a6b7; font-size: 0.85rem; font-weight: 600; text-transform: uppercase; margin: 0; }

        @media (max-width: 992px) { .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); } .main-content { margin-left: 0; } .mobile-toggle { display: block !important; margin-right: 15px; } }
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1040; }
        .overlay.show { display: block; }
    </style>
</head>
<body>

<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<nav class="sidebar" id="sidebar">
    <div class="text-center mb-4"><h4 class="fw-bold text-white"><?= htmlspecialchars($nomePainel) ?></h4></div>
    <div class="nav flex-column">
        <a href="index.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
        <?php if ($isAdmin): ?>
            <div class="nav-group-title">ADMINISTRATIVO</div>
            <a href="gerenciar_perfis.php" class="nav-link"><i class="fas fa-layer-group"></i> Perfis</a>
            <a href="gerenciar_dns.php" class="nav-link"><i class="fas fa-network-wired"></i> Servidores DNS</a>
            <a href="gerenciar_admins.php" class="nav-link"><i class="fas fa-user-shield"></i> Equipe Admins</a>
            <a href="personalizar_painel.php" class="nav-link"><i class="fas fa-paint-brush"></i> Personalizar</a>
            <a href="config_geral.php" class="nav-link"><i class="fas fa-cogs"></i> Configura莽玫es</a>
            <a href="gerenciar_ips.php" class="nav-link"><i class="fas fa-shield-halved"></i> Firewall IPs</a>
            <a href="gerenciar_backups.php" class="nav-link"><i class="fas fa-database"></i> Backup</a>
            <a href="ferramentas_migracao.php" class="nav-link"><i class="fas fa-exchange-alt"></i> Exportar/Importar</a>
        <?php endif; ?>
        <div class="nav-group-title">MENU</div>
        <a href="revendedores.php" class="nav-link"><i class="fas fa-store"></i> Revendedores</a>
        <a href="clientes.php" class="nav-link"><i class="fas fa-users"></i> Clientes</a>
        <a href="testes.php" class="nav-link"><i class="fas fa-stopwatch"></i> Testes</a>
        <a href="monitor.php" class="nav-link"><i class="fas fa-wifi"></i> Monitor Online</a>
        
        <a href="relatorio.php" class="nav-link active"><i class="fas fa-file-invoice-dollar"></i> Relat贸rio de Faturas</a>
        
        <a href="config_mp_revenda.php" class="nav-link"><i class="fas fa-wallet"></i> Pagamento</a>
        <a href="gerenciar_planos.php" class="nav-link"><i class="fas fa-tags"></i> Planos</a>
        <a href="gerenciar_email.php" class="nav-link"><i class="fas fa-envelope"></i> SMTP Email</a>
        <a href="suporte.php" class="nav-link"><i class="fas fa-headset"></i> Suporte / Mensagens</a>
        <a href="enviar_circular.php" class="nav-link"><i class="fas fa-paper-plane"></i> Enviar Circular</a>
        <a href="gerador_robo.php" class="nav-link"><i class="fas fa-robot"></i> WhatsAuto</a>
        <a href="sair.php" class="nav-link text-danger mt-4"><i class="fas fa-sign-out-alt"></i> Sair</a>
    </div>
</nav>

<main class="main-content">
    <div class="top-header">
        <div class="d-flex align-items-center">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title">Relat贸rio de Fatura</div>
        </div>
    </div>

    <div class="container-fluid p-2 p-md-4">
        
        <?php if ($isAdmin): ?>
        <div class="card card-custom mb-4 p-3 shadow-lg">
            <form method="GET" class="row g-2 align-items-end">
                <div class="col-md-5">
                    <label class="label-visivel mb-1 text-warning"><i class="fas fa-crown"></i> SELECIONAR REVENDEDOR</label>
                    <select name="revendedor" class="form-select">
                        <option value="<?= htmlspecialchars($_SESSION['usuario']) ?>">Visualizar minha rede (Admin)</option>
                        <?php foreach($lista_revendedores as $rev): ?>
                            <option value="<?= htmlspecialchars($rev['usuario']) ?>" <?= ($revendedor_alvo == $rev['usuario']) ? 'selected' : '' ?>><?= htmlspecialchars($rev['usuario']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-warning w-100 fw-bold py-2 shadow text-dark"><i class="fas fa-search me-1"></i> EXIBIR</button>
                </div>
            </form>
        </div>
        <?php endif; ?>

        <h5 class="text-white fw-bold mb-3"><i class="fas fa-chart-pie me-2"></i> Faturamento de: <span class="text-primary"><?= htmlspecialchars($revendedor_alvo) ?></span></h5>
        <div class="row mb-4">
            
            <div class="col-12 col-md-4 mb-3">
                <div class="box-valor border-primary" style="background: rgba(115, 103, 240, 0.15);">
                    <p class="text-primary">Total Geral a Pagar</p>
                    <h2>R$ <?= number_format($total_geral, 2, ',', '.') ?></h2>
                    <span class="badge bg-primary mt-2"><i class="fas fa-users me-1"></i> <?= $total_conexoes ?> Logins Ativos</span>
                </div>
            </div>

            <div class="col-12 col-md-4 mb-3">
                <div class="box-valor border-info" style="background: rgba(0, 207, 232, 0.1);">
                    <p class="text-info">Servidor Claro</p>
                    <h2 class="text-info">R$ <?= number_format($total_pagar_claro, 2, ',', '.') ?></h2>
                    <div class="mt-2 text-white-50 small">
                        <?= $qtd_claro ?> logins ativos x R$ <?= number_format($valor_claro, 2, ',', '.') ?>
                    </div>
                </div>
            </div>

            <div class="col-12 col-md-4 mb-3">
                <div class="box-valor border-danger" style="background: rgba(234, 84, 85, 0.1);">
                    <p class="text-danger">Servidor Net</p>
                    <h2 class="text-danger">R$ <?= number_format($total_pagar_net, 2, ',', '.') ?></h2>
                    <div class="mt-2 text-white-50 small">
                        <?= $qtd_net ?> logins ativos x R$ <?= number_format($valor_net, 2, ',', '.') ?>
                    </div>
                </div>
            </div>

        </div>

        <div class="card card-custom shadow-lg overflow-hidden">
            <div class="p-3 border-bottom border-secondary d-flex justify-content-between align-items-center">
                <h6 class="mb-0 fw-bold text-white"><i class="fas fa-list me-2"></i> Detalhamento por Cliente</h6>
            </div>
            <div class="table-responsive">
                <table class="table table-video mb-0">
                    <thead>
                        <tr>
                            <th>Nome</th>
                            <th class="text-center">Usu谩rio</th>
                            <th class="text-center">Operadora (Perfil)</th>
                            <th class="text-center">Telas (Conex茫o)</th>
                            <th class="text-center">Vencimento</th>
                            <th class="text-end pe-4">Custo Fatura</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($lista_detalhada) == 0): ?>
                            <tr><td colspan="6" class="text-center py-4 text-white-50">Nenhum cliente ativo para faturamento no momento.</td></tr>
                        <?php else: ?>
                            <?php foreach ($lista_detalhada as $cli): ?>
                                <tr>
                                    <td class="fw-bold text-white"><?= htmlspecialchars($cli['nome']) ?></td>
                                    <td class="text-center text-info small"><?= htmlspecialchars($cli['usuario']) ?></td>
                                    <td class="text-center text-white-50 small">
                                        <?php if ($cli['tipo'] == 'claro'): ?>
                                            <span class="badge bg-info text-dark">CLARO</span>
                                        <?php else: ?>
                                            <span class="badge bg-danger">NET</span>
                                        <?php endif; ?>
                                        <br><small><?= htmlspecialchars($cli['perfil_nome']) ?></small>
                                    </td>
                                    <td class="text-center"><span class="badge bg-secondary"><?= $cli['conexoes'] ?> Tela(s)</span></td>
                                    <td class="text-center"><span class="badge bg-success p-2"><?= $cli['vencimento'] ?></span></td>
                                    <td class="text-end pe-4 fw-bold text-warning">R$ <?= number_format($cli['valor'], 2, ',', '.') ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleMenu() { document.getElementById('sidebar').classList.toggle('show'); document.getElementById('overlay').classList.toggle('show'); }
</script>
</body>
</html>