<?php
// dashboard.php - Responsivo PC e Mobile
session_start();
require_once 'includes/db.php';

// Verificação de segurança
if (!isset($_SESSION['logged_in_fxtream']) || $_SESSION['logged_in_fxtream'] !== true) {
    header('Location: index.php');
    exit;
}

$user_name = $_SESSION['username'] ?? 'Admin';
$current_role = $_SESSION['role'] ?? 'reseller';
$current_id = $_SESSION['user_id'] ?? 0;

// Filtro de revendedor
$where_revenda = ($current_role !== 'admin') ? "AND revendedor_id = $current_id" : "";

try {
    // === DADOS DO BANCO ===
    $total_iptv = $pdo->query("SELECT COUNT(*) FROM users WHERE is_p2p = 0 $where_revenda")->fetchColumn();
    $active_iptv = $pdo->query("SELECT COUNT(*) FROM users WHERE is_p2p = 0 AND active = 1 $where_revenda")->fetchColumn();
    $total_p2p = $pdo->query("SELECT COUNT(*) FROM users WHERE is_p2p = 1 AND is_trial = 0 $where_revenda")->fetchColumn();
    $test_p2p = $pdo->query("SELECT COUNT(*) FROM users WHERE is_p2p = 1 AND is_trial = 1 $where_revenda")->fetchColumn();

    $total_resellers = 0;
    if ($current_role === 'admin') {
        $total_resellers = $pdo->query("SELECT COUNT(*) FROM revendedores")->fetchColumn();
    }

    $sql_expire = "SELECT username, expire_date, is_p2p FROM users WHERE expire_date BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 5 DAY) $where_revenda ORDER BY expire_date ASC LIMIT 5";
    $expiring_clients = $pdo->query($sql_expire)->fetchAll(PDO::FETCH_ASSOC);

    // === LÓGICA DO INFINITO CORRIGIDA ===
    // Verifica se a role é admin OU se o nome de usuário é 'admin'
    if ($current_role === 'admin' || strtolower($user_name) === 'admin') {
        $user_credits = "8"; 
    } else {
        $stmt = $pdo->prepare("SELECT credits FROM revendedores WHERE id = ?");
        $stmt->execute([$current_id]);
        $user_credits = $stmt->fetchColumn();
        if($user_credits === false) $user_credits = 0;
    }

    try { 
        $total_live_channels = $pdo->query("SELECT COUNT(*) FROM channels WHERE running = 1")->fetchColumn(); 
    } catch(Exception $e) { $total_live_channels = 0; }

} catch (PDOException $e) {
    $total_iptv = 0; $active_iptv = 0; $total_p2p = 0; $test_p2p = 0;
    $total_resellers = 0; $expiring_clients = []; $user_credits = 0; $total_live_channels = 0;
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 
    <title>Dashboard :: Painel IPTV</title>
    
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/pre-loader.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/pre-loader-dark.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_fonts/batch-icons/css/batch-icons.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/bootstrap/bootstrap.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/bootstrap/mdb.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_plugins/custom-scrollbar/jquery.mCustomScrollbar.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/hamburgers/hamburgers.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/style.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_fonts/font-awesome/css/all.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/dark-theme.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_plugins/morris.js/morris.css">

    <script type="text/javascript" src="https://vendedorp2p.com/views/_js/jquery/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="https://vendedorp2p.com/views/_plugins/js-cookie/js.cookie.min.js"></script>

    <style> 
        .fa-spinner { display: none !important; } 
        .collapse.show { background: rgba(0,0,0,0.2); }
        .nav-sub-link { padding-left: 45px !important; font-size: 0.9em; }

        body { overflow-x: hidden; }
        
        /* CORREÇÃO DO MENU DUPLICADO - CSS */
        @media (min-width: 992px) {
            #sidebar { width: 240px; position: fixed; top: 0; left: 0; height: 100vh; z-index: 1000; overflow-y: auto; }
            .right-column { margin-left: 240px; width: calc(100% - 240px); transition: all 0.3s; }
            #btnToggleMenu { display: none !important; } /* Esconde o botão no PC */
        }
        
        @media (max-width: 991px) {
            #sidebar { position: fixed; top: 0; left: -260px; width: 250px; height: 100vh; z-index: 9999; transition: all 0.3s ease; box-shadow: 2px 0 10px rgba(0,0,0,0.5); }
            #sidebar.active { left: 0; }
            .right-column { margin-left: 0 !important; width: 100% !important; padding-top: 0px; }
            .navbar { padding: 10px; }
            
            /* AQUI ESTÁ A CORREÇÃO: Usa o ID específico */
            #btnToggleMenu { display: block !important; z-index: 10000; padding: 0; }
            
            /* Garante que qualquer outro botão "hamburger" ou "toggler" seja escondido */
            .navbar-toggler, .hamburger:not(#btnToggleMenu) { display: none !important; }

            .overlay-menu { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9998; }
            .overlay-menu.active { display: block; }
        }

        .card-tile { min-height: 120px; display: flex; align-items: center; }
        .card-body { width: 100%; }
        h3 { font-size: 1.5rem; margin-top: 10px; font-weight: 600; color: #ccc; }
    </style>
</head>

<body>
    <div id="loader-wrapper">
        <div class="lds-roller"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div>
    </div>

    <div class="overlay-menu" id="overlayMenu"></div>

    <div class="container-fluid p-0"> 
        <div class="row no-gutters"> 
            
            <?php include 'includes/sidebar.php'; ?>

            <div class="right-column">
                
                <nav class="navbar navbar-expand-lg navbar-light bg-white border-bottom">
                    <button class="hamburger hamburger--slider" type="button" id="btnToggleMenu">
                        <span class="hamburger-box"><span class="hamburger-inner"></span></span>
                    </button>

                    <div class="ml-auto d-flex align-items-center">
                        <div class="d-none d-md-block mr-3"><i class="fa fa-globe-americas"></i> PT-BR</div>
                        
                        <div class="mr-3">
                            <span class="badge badge-pill badge-danger py-2 px-3">
                                <?php if($user_credits === "8"): ?>
                                    <span style="font-size: 1.2em; line-height: 1;">&infin;</span> <?php else: ?>
                                    <?php echo $user_credits; ?> Creditos
                                <?php endif; ?>
                            </span>
                        </div>
                        
                        <div class="dropdown">
                            <a class="nav-link dropdown-toggle d-flex align-items-center" data-toggle="dropdown" href="#">
                                <div class="d-none d-md-block mr-2 font-weight-bold"><?php echo htmlspecialchars($user_name); ?></div>
                                <img src="https://vendedorp2p.com/views/_img/profile-pic.png" width="35" height="35" class="rounded-circle">
                            </a>
                            <div class="dropdown-menu dropdown-menu-right">
                                <?php if($current_role === 'admin'): ?>
                                <a class="dropdown-item" href="config_painel.php"><i class="fa fa-cogs mr-2"></i> Configuracoes</a>
                                <div class="dropdown-divider"></div>
                                <?php endif; ?>
                                <a class="dropdown-item" href="logout.php"><i class="fa fa-power-off mr-2"></i> Sair</a>
                            </div>
                        </div>
                    </div>
                </nav>

                <main class="main-content p-3 p-md-4" role="main">
                    
                    <div class="row">
                        <div class="col-12 mb-3"><h3><i class="fa fa-tv text-info"></i> IPTV</h3></div>

                        <div class="col-12 col-md-6 col-lg-4 col-xl-4 mb-4">
                            <div class="card card-tile card-xs text-center shadow-sm">
                                <div class="card-body p-3">
                                    <div class="row align-items-center">
                                        <div class="col-4"><i class="fal fa-users fa-3x text-info text-gradient"></i></div>
                                        <div class="col-8 text-right"><h3 class="font-weight-bold mb-0"><?php echo $total_iptv; ?></h3><small class="text-muted">CLIENTES IPTV</small></div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-12 col-md-6 col-lg-4 col-xl-4 mb-4">
                            <div class="card card-tile card-xs text-center shadow-sm">
                                <div class="card-body p-3">
                                    <div class="row align-items-center">
                                        <div class="col-4"><i class="fal fa-check-circle fa-3x text-success text-gradient"></i></div>
                                        <div class="col-8 text-right"><h3 class="font-weight-bold mb-0"><?php echo $active_iptv; ?></h3><small class="text-muted">IPTV ATIVOS</small></div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-12 col-md-6 col-lg-4 col-xl-4 mb-4">
                             <a href="clients.php?filter=trial" style="text-decoration:none;">
                                 <div class="card card-tile card-xs text-center bg-dark border-secondary shadow-sm">
                                    <div class="card-body p-3">
                                        <div class="d-flex justify-content-center align-items-center" style="height: 60px;">
                                            <i class="fal fa-plus-circle fa-2x text-primary mr-3"></i>
                                            <span class="text-white font-weight-bold text-uppercase">Novo Teste IPTV</span>
                                        </div>
                                    </div>
                                </div>
                            </a>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12 mb-3 mt-2"><h3><i class="fa fa-share-alt text-success"></i> P2P</h3></div>

                        <div class="col-12 col-md-6 col-lg-6 col-xl-6 mb-4">
                            <div class="card card-tile card-xs text-center shadow-sm" style="border-left: 4px solid #28a745;">
                                <div class="card-body p-3">
                                    <div class="row align-items-center">
                                        <div class="col-4"><i class="fal fa-users fa-3x text-success text-gradient"></i></div>
                                        <div class="col-8 text-right"><h3 class="font-weight-bold mb-0"><?php echo $total_p2p; ?></h3><small class="text-muted">CLIENTES P2P</small></div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-12 col-md-6 col-lg-6 col-xl-6 mb-4">
                            <div class="card card-tile card-xs text-center shadow-sm" style="border-left: 4px solid #ffc107;">
                                <div class="card-body p-3">
                                    <div class="row align-items-center">
                                        <div class="col-4"><i class="fal fa-clock fa-3x text-warning text-gradient"></i></div>
                                        <div class="col-8 text-right"><h3 class="font-weight-bold mb-0"><?php echo $test_p2p; ?></h3><small class="text-muted">TESTES P2P</small></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if($current_role === 'admin'): ?>
                    <div class="row">
                        <div class="col-12 mb-3 mt-2"><h3><i class="fa fa-cogs text-warning"></i> Sistema</h3></div>
                        
                        <div class="col-12 col-md-6 col-lg-6 col-xl-6 mb-4">
                             <div class="card card-tile card-xs text-center shadow-sm">
                                <div class="card-body p-3">
                                    <div class="row align-items-center">
                                        <div class="col-4"><i class="fal fa-user-tie fa-3x text-warning text-gradient"></i></div>
                                        <div class="col-8 text-right"><h3 class="font-weight-bold mb-0"><?php echo $total_resellers; ?></h3><small class="text-muted">REVENDA</small></div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-12 col-md-6 col-lg-6 col-xl-6 mb-4">
                             <div class="card card-tile card-xs text-center shadow-sm border border-secondary">
                                <div class="card-body p-3">
                                    <div class="row align-items-center">
                                        <div class="col-4"><i class="fal fa-signal fa-3x text-danger text-gradient"></i></div>
                                        <div class="col-8 text-right"><h3 class="font-weight-bold mb-0"><?php echo $total_live_channels; ?></h3><small class="text-muted">CANAIS LIVE (PROXY)</small></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-lg-6 mb-4">
                            <div class="card shadow-sm h-100">
                                <div class="card-body">
                                    <h4 class="card-title">Crescimento</h4>
                                    <div class="chart" id="revenue-chart" style="position: relative; height: 300px;"></div>
                                </div>
                            </div>
                        </div>

                        <div class="col-lg-6 mb-4">
                            <div class="card shadow-sm h-100">
                                <div class="card-body">
                                    <h4 class="card-title text-danger">Expiram em 5 dias</h4>
                                    <div class="table-responsive">
                                        <table class="table table-striped table-hover">
                                            <thead><tr><th>Login</th><th>Tipo</th><th>Vencimento</th><th></th></tr></thead>
                                            <tbody>
                                                <?php if (count($expiring_clients) > 0): ?>
                                                    <?php foreach ($expiring_clients as $client): 
                                                        $tipo = ($client['is_p2p'] == 1) ? '<span class="badge badge-success">P2P</span>' : '<span class="badge badge-info">IPTV</span>';
                                                    ?>
                                                    <tr>
                                                        <td><?php echo htmlspecialchars($client['username']); ?></td>
                                                        <td><?php echo $tipo; ?></td>
                                                        <td><?php echo date('d/m', strtotime($client['expire_date'])); ?></td>
                                                        <td><a href="<?php echo ($client['is_p2p']==1) ? 'p2p_manager.php' : 'clients.php'; ?>" class="btn btn-sm btn-info"><i class="fa fa-eye"></i></a></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                <?php else: ?>
                                                    <tr><td colspan="4" class="text-center">Nenhum.</td></tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row mb-4"><div class="text-center col-12 text-white small">Copyright &copy; 2025 Koffice Panel.</div></div>

                </main>
            </div>
        </div>
    </div>

    <script type="text/javascript" src="https://vendedorp2p.com/views/_js/bootstrap/popper.min.js"></script>
    <script type="text/javascript" src="https://vendedorp2p.com/views/_js/bootstrap/bootstrap.min.js"></script>
    <script type="text/javascript" src="https://vendedorp2p.com/views/_js/bootstrap/mdb.min.js"></script>
    <script src="https://vendedorp2p.com/views/_plugins/bootbox.min.js"></script>
    <script type="text/javascript" src="https://vendedorp2p.com/views/_plugins/custom-scrollbar/jquery.mCustomScrollbar.concat.min.js"></script>
    <script type="text/javascript" src="https://vendedorp2p.com/views/_js/scripts.js"></script>
    <script src="https://vendedorp2p.com/views/_plugins/raphael/raphael.min.js"></script>
    <script src="https://vendedorp2p.com/views/_plugins/morris.js/morris.min.js"></script>

    <script type="text/javascript">
        $(function () { setTimeout(function(){ $("#loader-wrapper").fadeOut(250); }, 100); });
        
        $('#btnToggleMenu, #overlayMenu').click(function() {
            $('#sidebar').toggleClass('active');
            $('#overlayMenu').toggleClass('active');
            $('#btnToggleMenu').toggleClass('is-active');
        });

        const default_theme = "dark_theme";
        var c_theme_name = Cookies.get('current_theme') || default_theme;
        $('body').addClass(c_theme_name);

        if($('#revenue-chart').length > 0){
            new Morris.Area({
                element: 'revenue-chart',
                resize: true,
                data: [{x: '2025-01-01', c: 2}, {x: '2025-01-02', c: 5}, {x: '2025-01-03', c: 3}],
                xkey: 'x', ykeys: ['c'], labels: ['Vendas'],
                lineColors: ['#5198c6'], hideHover: 'auto', xLabels: 'day'
            });
        }
    </script>
</body>
</html>