<?php
session_start();

$config_file = 'config.json';
if (file_exists($config_file)) {
    $config = json_decode(file_get_contents($config_file), true);
} else {
    $config = [
        'title' => 'TOP IPTV',
        'logo_path' => './img/logo_tranparente2.png'
    ];
}

require_once('./api/controles/checkLogout.php');

checkLogout();

if (isset($_GET['sair'])) {
    $_SESSION = array();
    session_unset();
    session_destroy();

    if (isset($_COOKIE[session_name()])) {
        setcookie(session_name(), '', time() - 3600, '/');
    }
    header('Location: ./index.php');
    exit();
}
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo htmlspecialchars($config['title']); ?></title>
    <link rel="shortcut icon" href="<?php echo htmlspecialchars($config['logo_path']); ?>">
    <link rel="stylesheet" type="text/css" href="css/menu.css">
    <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/2.0.7/css/dataTables.dataTables.css">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    <link href="//cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <script src="//cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="//cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
        
    <style>
        :root {
            --bg-main: #f0f2f5; --bg-sidebar: #1B1E26; --bg-header: #ffffff; --bg-card: #ffffff;
            --text-primary: #212529; --text-secondary: #6c757d; --border-color: #e9ecef;
            --sidebar-text: #EEF5FD; --sidebar-active-bg: #0d6efd; --sidebar-active-text: #ffffff;
            --header-shadow: rgba(0,0,0,0.1);
        }
        [data-theme="dark"] {
            --bg-main: #16191c; --bg-sidebar: #212529; --bg-header: #212529; --bg-card: #2a2e33;
            --text-primary: #e4e6eb; --text-secondary: #b0b3b8; --border-color: #3a3f44;
            --sidebar-text: #e4e6eb; --header-shadow: rgba(0,0,0,0.4);
        }
        body, .page-content { background-color: var(--bg-main) !important; color: var(--text-primary); transition: background-color 0.3s ease, color 0.3s ease; }
        .navigation { background: var(--bg-sidebar); border-right: 1px solid var(--border-color); }
        header.navbar { background: var(--bg-header) !important; box-shadow: 0 2px 4px var(--header-shadow) !important; }
        .card, .table-card, .modal-content { background-color: var(--bg-card); color: var(--text-primary); border: 1px solid var(--border-color); }
        h4, h5, .text-secondary, .card-label, .text-muted, .section-title { color: var(--text-secondary) !important; }
        .card-value, .card-text, .text-end, .nav-link, .dropdown-item, .modal-title { color: var(--text-primary) !important; }
        .navigation .list a .text.color, .navigation .list a .icon { color: var(--sidebar-text); }
        .dropdown-menu { background-color: var(--bg-card); border: 1px solid var(--border-color); }
        .dropdown-item:hover { background-color: var(--sidebar-active-bg); color: var(--sidebar-active-text) !important; }
        .navigation .list.active { background: var(--sidebar-active-bg) !important; }
        .navigation .list.active a .icon, .navigation .list.active a .text.color { color: var(--sidebar-active-text) !important; }
        #theme-toggle .fa-sun { display: none; } #theme-toggle .fa-moon { display: block; }
        [data-theme="dark"] #theme-toggle .fa-sun { display: block; } [data-theme="dark"] #theme-toggle .fa-moon { display: none; }
        [data-theme="dark"] #theme-toggle { color: var(--sidebar-active-bg) !important; }
        [data-theme="light"] header.navbar, [data-theme="light"] .dropdown-toggle { color: #333 !important; }
        [data-theme="dark"] header.navbar, [data-theme="dark"] .dropdown-toggle { color: #fff !important; }
    </style>
</head>
<body>
<header class="fixed-top navbar navbar-expand-lg" style="transition: 0.5s; padding: 0;">
    <div class="container-fluid" style="height: 3em;display: flex;align-items: center;">
        <div class="align-items-center d-flex left-side-content">
            <div class="pl-2 pr-2">
                <div class="m-0 navbar-brand w-100" style="display: flex; align-items: flex-end;">
                    <img alt="lightning logo" src="<?php echo htmlspecialchars($config['logo_path']); ?>" width="35px" height="35px" class="logo">
                    <span class="ml-1 text-logo"><?php echo htmlspecialchars($config['title']); ?></span>
                </div>
            </div>
            <div class="col-md-auto menuToggle btn1" style="width: 40px;height: 40px;">
                <i class="fa fa-bars"></i>
            </div>
        </div>
        <div class="align-items-center d-flex right-side-content">
            <button id="theme-toggle" class="btn btn-sm" style="font-size: 1.2rem; margin-right: 10px;">
                <i class="fas fa-moon"></i>
                <i class="fas fa-sun"></i>
            </button>
            <div class="badge bg-success">
                <span class="j_credits" style="margin-right: 5px; opacity: 1;" id="creditos"> </span> Créditos
            </div>
            <div class="dropdown ms-2">
                <button class="btn header-item waves-effect dropdown-toggle" type="button" id="dropdownUser" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    <img class="rounded-circle header-profile-user" src="//fxtream.xyz/dashboard/img/user.png" alt="<?php echo isset($_SESSION['username']) ? htmlspecialchars($_SESSION['username']) : ''; ?>" style="width: 25px; height: 23px;">
                    <span class="d-none d-xl-inline-block ms-1"> <?php echo isset($_SESSION['username']) ? htmlspecialchars($_SESSION['username']) : ''; ?> </span>
                    <i class="mdi mdi-chevron-down d-none d-xl-inline-block"></i>
                </button>
                <ul class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownUser">
                    <li>
                        <?php if (isset($_SESSION['nivel_admin']) && $_SESSION['nivel_admin'] == 1): ?>
                            <a class="dropdown-item" onclick='modal_master("api/revendedores.php", "edite_admin", "edite")'>Editar Admin</a>
                        <?php endif ?>
                        <?php if (isset($_SESSION['nivel_admin']) && $_SESSION['nivel_admin'] == 0): ?>
                            <a class="dropdown-item" onclick='modal_master("api/revendedores.php", "edite_admin_revenda", "edite")'>Editar Senha</a>
                        <?php endif ?>
                        <a class="dropdown-item" href="?sair">Sair</a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</header>
<div class="navigation">
    <div class="container-fluid mb-3 menu-perfil p-0">
        <div class="align-items-center d-flex justify-content-center mb-1 menu-perfil1 p-2 pb-3 pt-4">
            <div class="justify-content-center align-items-center menu-perfil1">
                <div class="mb-4 perfil-foto">
                    <div class="m-auto mb-1 rounded-circle overflow-hidden">
                        <img class="img-fluid" src="//fxtream.xyz/dashboard/img/user.png" alt="">
                    </div>
                </div>
                <div class="text-center perfil-info" style="border-bottom: 1px solid var(--border-color);">
                    <p class="mb-0 text-uppercase" style="font-size: .9rem; font-weight: 800;"> <?php echo isset($_SESSION['username']) ? htmlspecialchars($_SESSION['username']) : ''; ?> </p>
                    <small class="text-uppercase role" style="font-size: .7rem; letter-spacing: 1px; font-weight: 500;" id="tipo_admin"> </small>
                    <br/>
                </div>
                <div class="perfil-info text-center">
                    <div class="mb-0 text-uppercase d-flex justify-content-between align-items-center" style="font-size: .9rem;font-weight: bolder;font-family: monospace;"> Creditos <span class="badge bg-success">
                            <i class="fa-solid fa-cent-sign pr-1">:</i> <span id="creditos2"> </span> </span>
                    </div>
                    <div class="mb-0 text-uppercase d-flex justify-content-between align-items-center" style="font-size: .9rem;font-weight: bolder;font-family: monospace;" id="vencimento">
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="menuToggle2"></div>
    <ul class="p-0">
        <li class="list" id="dashboard">
            <a href="dashboard.php" class="clr">
                <span class="icon"><i class="fa-solid fa-chart-line"></i></span>
                <span class="text color">Dashboard</span>
            </a>
        </li>
        <?php if (isset($_SESSION['nivel_admin']) && $_SESSION['nivel_admin'] == 1) { ?>
            <li class="list sub" id="Conteudos">
                <a class="clr">
                    <span class="icon"><i class="fa-solid fa-gear fa-spin"></i></span>
                    <span class="text color">Conteudos</span>
                    <i class="fa-solid fa-caret-right"></i>
                </a>
                <div class="sidebar-submenu">
                    <ul class="ps-2">
                        <li><a href="gerenciar_categorias.php"><i class="fas fa-table-list"></i><span class="text color">Categorias</span></a></li>
                        <li><a href="canais.php"><i class="fas fa-tv"></i><span class="text color">Canais</span></a></li>
                        <li><a href="filmes.php"><i class="fas fa-clapperboard"></i><span class="text color">Filmes</span></a></li>
                        <li><a href="serie.php"><i class="fas fa-film"></i><span class="text color">Series</span></a></li>
                        <li><a href="uploud.php"><i class="fa-solid fa-arrow-up-from-bracket"></i><span class="text color">Uploud</span></a></li>
                    </ul>
                </div>
            </li>
            <li class="list sub" id="ferramentas">
                <a class="clr">
                    <span class="icon"><i class="fa-solid fa-cogs fa-spin"></i></span>
                    <span class="text color">Ferramentas</span>
                    <i class="fa-solid fa-caret-right"></i>
                </a>
                <div class="sidebar-submenu">
                    <ul class="ps-2 text-nowrap">
                        <li><a onclick="confirmarDelecaoEmMassa('delete_all', 'CONTEÚDO INTEIRO')"><i class="fa-trash fas text-danger"></i><span class="text color">Deletar tudo</span></a></li>
                        <li><a onclick="confirmarDelecaoEmMassa('delete_streams', 'Canais')"><i class="fa-trash fas text-danger"></i><span class="text color">Deletar canais</span></a></li>
                        <li><a onclick="confirmarDelecaoEmMassa('delete_movies', 'Filmes')"><i class="fa-trash fas text-danger"></i><span class="text color">Deletar Filmes</span></a></li>
                        <li><a onclick="confirmarDelecaoEmMassa('delete_series', 'Séries')"><i class="fa-trash fas text-danger"></i><span class="text color">Deletar series</span></a></li>
                    </ul>
                </div>
            </li>
        <?php } ?>
        <li class="list sub" id="clientes">
            <a class="clr">
                <span class="icon"><i class="fa-solid fa-user-group hydrated md"></i></span>
                <span class="text color">Clientes</span>
                <i class="fa-solid fa-caret-right"></i>
            </a>
            <div class="sidebar-submenu">
                <ul class="ps-2">
                    <li><a href="clientes.php"><i class="fa-solid fa-user"></i><span class="text color">Clientes</span></a></li>
                    <li><a href="testes.php"><i class="fa-solid fa-user"></i><span class="text color">Testes</span></a></li>
                    <?php if (isset($_SESSION['plano_admin']) && $_SESSION['plano_admin'] != 1): ?>
                    <li><a href="revendedores.php"><i class="fa-solid fa-users-gear"></i><span class="text color">Revendedores</span></a></li>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['nivel_admin']) && $_SESSION['nivel_admin'] == 1): ?>
                    <li>
                        <a href="migrar_clientes.php">
                            <i class="fa-solid fa-people-arrows text-primary"></i>
                            <span class="text color">Migrar Clientes</span>
                        </a>
                    </li>
                    <?php endif; ?>

                </ul>
            </div>
        </li>
        <li class="list sub" id="aplicacoes">
            <a class="clr">
                <span class="icon"><i class="fa-solid fa-rocket"></i></span>
                <span class="text color">Aplicações</span>
                <i class="fa-solid fa-caret-right"></i>
            </a>
            <div class="sidebar-submenu">
                <ul class="ps-2">
                    <?php if (isset($_SESSION['nivel_admin']) && $_SESSION['nivel_admin'] == 1): ?>
                    <li><a href="admin_loja.php"><i class="fas fa-store-alt"></i><span class="text color">Gerenciar Loja</span></a></li>
                    <?php else: ?>
                    <li><a href="loja.php"><i class="fas fa-store"></i><span class="text color">Loja de Aplicativos</span></a></li>
                    <?php endif; ?>
                    <?php if (isset($_SESSION['nivel_admin']) && $_SESSION['nivel_admin'] != 1): ?>
                    <li><a href="pedidos.php"><i class="fas fa-plus-square"></i><span class="text color">Pedido de VODs</span></a></li>
                    <?php endif; ?>
                    <?php if (isset($_SESSION['nivel_admin']) && $_SESSION['nivel_admin'] == 1): ?>
                    <li><a href="admin_pedidos.php"><i class="fas fa-tasks"></i><span class="text color">Gerenciar Pedidos</span></a></li>
                    <?php endif; ?>
                </ul>
            </div>
        </li>
        <li class='list sub' id='configuracoes'>
            <a class='clr'>
                <span class='icon'><i class="fa-solid fa-gear fa-spin"></i></span>
                <span class='text color'>Settings</span>
                <i class="fa-solid fa-caret-right"></i>
            </a>
            <div class='sidebar-submenu'>
                <ul class="ps-2 text-nowrap">
                    <li><a href='planos.php'><i class='fa-solid fa-server'></i><span class='text color'>Planos</span></a></li>
                    <?php if (isset($_SESSION['nivel_admin']) && $_SESSION['nivel_admin'] == 1): ?>
                    <li>
                        <a href="atualizar_epg.php">
                            <i class="fa-solid fa-calendar-days text-info"></i>
                            <span class="text color">Atualizar EPG</span>
                        </a>
                    </li>
                    <li>
                        <a href="alterar_links.php">
                            <i class="fa-solid fa-link text-warning"></i>
                            <span class="text color">Alterar Links em Massa</span>
                        </a>
                    </li>
                    <li>
                        <a href="gerenciador_db.php"> <i class="fa-solid fa-database text-success"></i>
                            <span class="text color">Backup do Sistema</span>
                        </a>
                    </li>
                    <?php endif; ?>
                </ul>
            </div>
        </li>
        <?php if (isset($_SESSION['nivel_admin']) && $_SESSION['nivel_admin'] == 1) { ?>
              <li class='list sub' id='painel'>
            <a class='clr'>
                <span class='icon'><i class="fa-solid fa-sliders"></i></span>
                <span class='text color'>Painel</span>
                <i class="fa-solid fa-caret-right"></i>
            </a>
            <div class='sidebar-submenu'>
                <ul class="ps-2">
                    <li>
                        <a href="personalizar.php">
                            <i class="fa-solid fa-paint-roller"></i>
                            <span class="text color">Personalizar</span>
                        </a>
                    </li>
                    
                    <li>
                        <a href="editar_template.php">
                            <i class="fas fa-file-alt text-primary"></i>
                            <span class="text color">Editar Template</span>
                        </a>
                    </li>

                </ul>
            </div>
        </li>        
        </li>
        <?php } ?>
        <div class="indicator"></div>
    </ul>
</div>

<script>
    (function() {
        const themeToggle = document.getElementById('theme-toggle');
        const htmlElement = document.documentElement;
        function applyTheme(theme) {
            htmlElement.setAttribute('data-theme', theme);
            localStorage.setItem('theme', theme);
        }
        themeToggle.addEventListener('click', () => {
            const currentTheme = htmlElement.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            applyTheme(newTheme);
        });
        const savedTheme = localStorage.getItem('theme') || 'light';
        applyTheme(savedTheme);
    })();

    $(document).ready(function () {
        var currentURL = window.location.pathname.split('/').pop();
        currentURL = currentURL.replace('.php', '').replace('.html', '');
        
        // ========================================================================
        // JAVASCRIPT CORRIGIDO - VOLTANDO À SUA LÓGICA ORIGINAL E ADICIONANDO O NECESSÁRIO
        // ========================================================================
        if (currentURL === 'pedidos' || currentURL === 'admin_pedidos' || currentURL === 'loja' || currentURL === 'admin_loja') {
            $('#aplicacoes').addClass('active');
        } else if (currentURL === 'planos' || currentURL === 'atualizar_epg' || currentURL === 'alterar_links' || currentURL.startsWith('gerenciador_db')) {
            $('#configuracoes').addClass('active');
        } else if (currentURL === 'personalizar') {
            $('#painel').addClass('active');
        } else if (currentURL === 'categorias' || currentURL === 'canais' || currentURL === 'filmes' || currentURL === 'serie' || currentURL === 'uploud' || currentURL === 'divisor-m3u' || currentURL === 'alterar_links' || currentURL === 'gerenciar_categorias') {
            $('#Conteudos').addClass('active');
        } else if (currentURL === 'live' || currentURL === 'vod' || currentURL === 'series') {
            $('#vereditarpagar').addClass('active');
        } else if (currentURL === 'importar-live' || currentURL === 'importar-vod' || currentURL === 'importar-series') {
            $('#importar').addClass('active');
        } else if (currentURL === 'clientes' || currentURL === 'testes' || currentURL === 'revendedores' || currentURL === 'sub-revenda') {
            $('#clientes').addClass('active');
        } else if (currentURL === 'add_serie') {
            $('#Adicionar').addClass('active');
        } else {
            $('li').each(function () {
                if ($(this).attr('id') === currentURL) {
                    $(this).addClass('active');
                }
            });
        }
        
        $('.menuToggle, .menuToggle2').click(function () {
            $('.navigation').toggleClass('active');
            $('.page-content').toggleClass('active');
            $('.navbar').toggleClass('active');
        });

        $('.list').click(function () {
            $('.list').removeClass('active');
            $(this).addClass('active');
        });
        $('.list.sub').click(function () {
            $('.navigation').addClass('active');
            $('.page-content').addClass('active');
            $('.navbar').addClass('active');
        });
    });

    function addActiveClassOnLargeScreen() {
        const screenWidth = window.innerWidth;
        const elements = $('.navigation, .page-content, .navbar, .text-logo'); 
        if (screenWidth >= 768) { elements.addClass('active');
        } else { elements.removeClass('active'); }
    }
    $(document).ready(function () { addActiveClassOnLargeScreen(); });
    window.addEventListener('resize', () => { addActiveClassOnLargeScreen(); });
</script>
<script src="./js/sweetalert2.js"></script>
<script src="./js/custom.js?v=1"></script>

<script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script>
<script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script>
<main class="active overflow-auto page-content w-100" style="position: absolute; height: 100%;">
    <div class="container-fluid">