<?php
// ==========================================
// LÓGICA DO SEU PAINEL (ZENPANEL)
// ==========================================
session_start();

// --- PROTEÇÃO EXTRA ---
require_once 'includes/db.php'; 
// ----------------------

// --- LÓGICA DE IDIOMA ---
$default_lang = 'pt';
$allowed_langs = ['pt', 'en', 'de', 'fr'];

if (isset($_GET['lang']) && in_array($_GET['lang'], $allowed_langs)) {
    $_SESSION['lang'] = $_GET['lang'];
    session_write_close(); // Salva a sessão antes de recarregar
    header('Location: index.php');
    exit;
}

$lang = $_SESSION['lang'] ?? $default_lang;
if (!in_array($lang, $allowed_langs)) {
    $lang = $default_lang;
}

$lang_file = __DIR__ . '/lang/lang_' . $lang . '.php';
if (!file_exists($lang_file)) {
    $lang_file = __DIR__ . '/lang/lang_' . $default_lang . '.php';
}
require_once($lang_file); 

// Verifica se já está logado
if (isset($_SESSION['logged_in_fxtream']) && $_SESSION['logged_in_fxtream'] === true) {
    header('Location: dashboard.php');
    exit;
}

// Carrega config
$config_file = 'config.json';
if (file_exists($config_file)) {
    $config = json_decode(file_get_contents($config_file), true);
} else {
    $config = ['title' => 'Painel', 'logo_path' => 'https://kofficepanel.tvsbr.top/img/logo.png'];
}
?>

<!DOCTYPE html>
<html lang="<?php echo htmlspecialchars($t['html_lang'] ?? 'pt-br'); ?>" class="notranslate">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="google" content="notranslate">
    
    <meta name="description" content="<?php echo htmlspecialchars($t['panel_description'] ?? ''); ?>">
    <meta name="author" content="">
    <link rel="icon" href="<?php echo htmlspecialchars($config['logo_path']); ?>">
    
    <title><?php echo htmlspecialchars($t['login_title']); ?> :: <?php echo htmlspecialchars($config['title']); ?></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:wght@400;700;900&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://cdnjs.cloudflare.com/ajax/libs/animate.css/4.0.0/animate.min.css"/>
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_fonts/font-awesome/css/all.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_demo/css/ui-icons-batch-icons.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_plugins/toastr/toastr.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/quillpro/quillpro.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/dark-theme.css">

    <style>
        .text-logo {
            font-family: 'Poppins', sans-serif;
            font-weight: 900; 
            text-transform: uppercase;
            letter-spacing: 2px;
            color: #fff; 
            text-shadow: 0 0 10px rgba(0,0,0,0.5); 
            margin-bottom: 0;
            line-height: 1.2;
        }
    </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="container-fluid">
        <div class="row">
            <div class="right-column sisu">
                <div class="row mx-0">
                    <div class="col-md-7 order-md-2 signin-right-column px-5 bg-dark" style="background-image: url('https://i.pinimg.com/originals/82/56/35/825635092261db5aacb5ee3615098407.gif')">
                        
                        <a class="signin-logo d-sm-block d-md-none text-center" href="#" style="text-decoration: none;">
                            <h1 class="text-logo" style="font-size: 2.5rem;">TOP IPTV</h1>
                        </a>

                        <p class="display-5 mb-5"></p>
                    </div>

                    <div class="col-md-5 order-md-1 signin-left-column px-5">
                        
                        <a class="signin-logo d-sm-none d-md-block text-center mb-4" href="#" style="text-decoration: none;">
                             <h1 class="text-logo" style="font-size: 4rem;">TOP IPTV</h1>
                        </a>
                        
                        <h3 class="mb-4"><?php echo htmlspecialchars($t['welcome_back'] ?? 'Bem-vindo'); ?></h3>
                        <p class="mb-5"><?php echo htmlspecialchars($t['login_prompt'] ?? 'Faça login para continuar.'); ?></p>

                        <form id="form-login" method="POST">
                            <input type="hidden" name="csrf_token" value="13d9258d3a3c0f41b7d7bb5e5fb7570e">
                            
                            <div class="form-group">
                                <label for="username"><?php echo htmlspecialchars($t['username']); ?></label>
                                <input type="text" class="form-control" id="username" name="username" aria-describedby="emailHelp" placeholder="<?php echo htmlspecialchars($t['username_placeholder'] ?? 'Usuário'); ?>" required>
                            </div>

                            <div class="form-group">
                                <label for="password"><?php echo htmlspecialchars($t['password']); ?></label>
                                <input type="password" class="form-control" id="password" name="password" placeholder="<?php echo htmlspecialchars($t['password_placeholder'] ?? 'Senha'); ?>" required>
                            </div>

                            <div class="custom-control custom-checkbox mb-3">
                                <input type="checkbox" class="custom-control-input" id="keep-signed-in">
                                <label class="custom-control-label" for="keep-signed-in"><?php echo htmlspecialchars($t['keep_signed_in'] ?? 'Manter conectado'); ?></label>
                            </div>

                            <button type="submit" class="btn btn-primary btn-gradient btn-block font-weight-bold login-button">
                                <?php echo htmlspecialchars($t['login_button'] ?? 'Logar'); ?>
                                <i class="fa fa-chevron-right" aria-hidden="true"></i>
                            </button>
                        </form>
                        
                        <div class="mt-4 text-center">
                            <small>
                                <a href="?lang=pt" style="<?php echo $lang=='pt' ? 'color:#fff; font-weight:bold;' : 'color:#888;'; ?>">PT</a> | 
                                <a href="?lang=en" style="<?php echo $lang=='en' ? 'color:#fff; font-weight:bold;' : 'color:#888;'; ?>">EN</a> | 
                                <a href="?lang=de" style="<?php echo $lang=='de' ? 'color:#fff; font-weight:bold;' : 'color:#888;'; ?>">DE</a> | 
                                <a href="?lang=fr" style="<?php echo $lang=='fr' ? 'color:#fff; font-weight:bold;' : 'color:#888;'; ?>">FR</a>
                            </small>
                        </div>

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

    <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>
    <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 type="text/javascript" src="https://vendedorp2p.com/views/_plugins/velocity/velocity.min.js"></script>
    <script type="text/javascript" src="https://vendedorp2p.com/views/_plugins/velocity/velocity.ui.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/_plugins/jquery_visible/jquery.visible.min.js"></script>
    <script type="text/javascript" src="https://vendedorp2p.com/views/_js/misc/ie10-viewport-bug-workaround.js"></script>
    <script type="text/javascript" src="https://vendedorp2p.com/views/_js/misc/holder.min.js"></script>
    <script type="text/javascript" src="https://vendedorp2p.com/views/_js/scripts.js"></script>
    <script type="text/javascript" src="https://vendedorp2p.com/views/_plugins/toastr/toastr.min.js"></script>

    <script type="text/javascript">
        // Configuração do Tema
        const available_themes = ["white_theme","dark_theme"];
        const allow_change_theme = 1;
        const default_theme = "dark_theme";
        loadCurrentTheme();

        function loadCurrentTheme() {
            var c_theme_name = '';
            if(allow_change_theme && available_themes.includes(Cookies.get('current_theme'))) {
                c_theme_name = Cookies.get('current_theme');
            } else {
                c_theme_name = default_theme;
            }
            $('body').addClass(c_theme_name);
        }

        // Pre-loader
        $(function () {
            setTimeout(function(){
                $("#loader-wrapper").fadeOut(250);
            }, 100);
        });

        // LÓGICA DE LOGIN
        $("#form-login").submit(function(event) {
            event.preventDefault(); 

            var btnOriginal = $('.login-button').html();
            $('.login-button').html('<span class="gradient">Conectando... <i class="fa fa-spinner fa-spin" aria-hidden="true"></i></span>');
            $('.login-button').prop('disabled', true);

            const formData = new FormData(this);

            fetch('api/login.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                toastr.options = {
                    "closeButton": true,
                    "progressBar": true,
                    "positionClass": "toast-top-right",
                    "timeOut": "2000"
                };

                if (data.icon === 'success' || data.status === true) {
                    toastr["success"](data.title || "Login realizado com sucesso!", "Sucesso!");
                    setTimeout(function() {
                        window.location.href = data.url || 'dashboard.php';
                    }, 1500);
                } else {
                    toastr["error"](data.title || "Usuário ou senha inválidos", "Erro!");
                    $('.login-button').html(btnOriginal);
                    $('.login-button').prop('disabled', false);
                }
            })
            .catch(error => {
                console.error('Erro:', error);
                toastr["error"]("Erro de conexão com o servidor.", "Falha!");
                $('.login-button').html(btnOriginal);
                $('.login-button').prop('disabled', false);
            });
        });
    </script>
</body>
</html>
