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

// --- INÍCIO: BUSCA DE PERSONALIZAÇÃO DINÂMICA ---
$nome_painel = 'TOP IPTV';
$logo_url = '';
$cor_primaria = '#007bff';
$cor_fundo_login = '#121519'; // Cor padrão caso não ache
$usar_logo = 1; 

try {
    $pdo = getConexaoAtiva();
    $tabela_existe = $pdo->query("SHOW TABLES LIKE 'painel_config'")->rowCount() > 0;
    if ($tabela_existe) {
        $config_painel = $pdo->query("SELECT * FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        if ($config_painel) {
            $nome_painel = !empty($config_painel['nome_painel']) ? $config_painel['nome_painel'] : $nome_painel;
            $logo_url = !empty($config_painel['logo_url']) ? $config_painel['logo_url'] : $logo_url;
            $cor_primaria = !empty($config_painel['cor_primaria']) ? $config_painel['cor_primaria'] : $cor_primaria;
            $cor_fundo_login = !empty($config_painel['cor_fundo_login']) ? $config_painel['cor_fundo_login'] : $cor_fundo_login;
            
            if (isset($config_painel['usar_logo'])) { $usar_logo = $config_painel['usar_logo']; }
        }
    }
} catch (Exception $e) { }

// --- LÓGICA DE TROCA DE IDIOMA ---
if (isset($_GET['lang'])) {
    $allowed_langs = ['pt', 'en', 'fr', 'de'];
    $lang_request = strtolower($_GET['lang']);
    if (in_array($lang_request, $allowed_langs)) {
        $_SESSION['lang'] = $lang_request;
        setcookie('lang', $lang_request, time() + (86400 * 30), "/"); 
    }
    header("Location: login.php"); exit;
}
$current_lang = $_SESSION['lang'] ?? ($_COOKIE['lang'] ?? 'pt');

$dict = [
    'pt' => [ 'welcome' => 'Bem-vindo de volta', 'subtitle' => 'Entre com as suas credenciais', 'user' => 'Utilizador', 'user_ph' => 'Digite o seu utilizador', 'pass' => 'Palavra-passe', 'pass_ph' => 'Digite a sua palavra-passe', 'remember' => 'Manter ligado', 'btn' => 'Entrar no Painel' ],
    'en' => [ 'welcome' => 'Welcome back', 'subtitle' => 'Enter your credentials', 'user' => 'Username', 'user_ph' => 'Enter your username', 'pass' => 'Password', 'pass_ph' => 'Enter your password', 'remember' => 'Remember me', 'btn' => 'Login to Panel' ],
    'fr' => [ 'welcome' => 'Bon retour', 'subtitle' => 'Entrez vos identifiants', 'user' => 'Nom d\'utilisateur', 'user_ph' => 'Entrez votre nom', 'pass' => 'Mot de passe', 'pass_ph' => 'Entrez votre mot de passe', 'remember' => 'Se souvenir', 'btn' => 'Connexion' ],
    'de' => [ 'welcome' => 'Willkommen zurück', 'subtitle' => 'Geben Sie Ihre Daten ein', 'user' => 'Benutzername', 'user_ph' => 'Benutzername eingeben', 'pass' => 'Passwort', 'pass_ph' => 'Passwort eingeben', 'remember' => 'Angemeldet bleiben', 'btn' => 'Anmelden' ]
];
$t = $dict[$current_lang] ?? $dict['pt'];

if (isset($_SESSION['user_id'])) { header("Location: dashboard.php"); exit; }
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="<?php echo (!empty($logo_url) && $usar_logo == 1) ? htmlspecialchars($logo_url) : 'https://vendedorp2p.com/views/_img/favicon.png'; ?>">
    <title>Login :: <?php echo htmlspecialchars($nome_painel); ?></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">
    
    <style>
        /* APLICA AS CORES DINÂMICAS SOMENTE ONDE IMPORTA */
        .btn-primary.btn-gradient, .login-button {
            background: <?php echo htmlspecialchars($cor_primaria); ?> !important;
            border-color: <?php echo htmlspecialchars($cor_primaria); ?> !important;
        }
        .signin-left-column {
            background-color: <?php echo htmlspecialchars($cor_fundo_login); ?> !important;
        }

        /* TRAVA A TELA PARA NÃO PULAR NO CELULAR (MANTENDO O DESIGN ORIGINAL) */
        html, body {
            overflow: hidden !important;
            overscroll-behavior: none !important;
            height: 100%;
            width: 100%;
            position: fixed; /* Crava a tela no lugar */
            top: 0;
            left: 0;
            margin: 0;
            padding: 0;
        }
        .container-fluid, .sisu, .row.mx-0 {
            height: 100% !important;
        }
        @media (max-width: 768px) {
            .signin-left-column {
                overflow-y: auto !important; /* Rola só o formulário caso o teclado abra */
            }
        }
    </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" href="#">
                            <?php if(!empty($logo_url) && file_exists($logo_url) && $usar_logo == 1): ?>
                                <img src="<?php echo htmlspecialchars($logo_url); ?>" width="200" alt="Logo">
                            <?php else: ?>
                                <h2 style="font-weight:bold; color:white; margin-top:20px;"><?php echo htmlspecialchars($nome_painel); ?></h2>
                            <?php endif; ?>
                        </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="#">
                            <?php if(!empty($logo_url) && file_exists($logo_url) && $usar_logo == 1): ?>
                                <img src="<?php echo htmlspecialchars($logo_url); ?>" style="max-height: 120px; object-fit: contain;">
                            <?php else: ?>
                                <h1 style="font-weight:bold; color:white;"><?php echo htmlspecialchars($nome_painel); ?></h1>
                            <?php endif; ?>
                        </a>

                        <?php if (isset($_SESSION['erro_login'])): ?>
                            <div class="alert alert-danger py-2 mb-4" style="font-size: 14px; background: rgba(220,53,69,0.1); border: 1px solid #dc3545; color: #ff5f6d;">
                                <i class="fa fa-exclamation-circle me-2"></i><?php echo htmlspecialchars($_SESSION['erro_login']); ?>
                            </div>
                            <?php unset($_SESSION['erro_login']); ?>
                        <?php endif; ?>

                        <form id="form-login" method="POST" action="auth.php">
                            <input type="hidden" name="try_login" value="1">
                            <input type="hidden" name="csrf_token" value="dea3d18d9eccba078608c5527b285558">
                            <div class="form-group">
                                <label for="username"><?php echo $t['user']; ?></label>
                                <input type="text" class="form-control" id="username" placeholder="<?php echo $t['user_ph']; ?>" name="username" required>
                            </div>
                            <div class="form-group">
                                <label for="password"><?php echo $t['pass']; ?></label>
                                <input type="password" class="form-control" id="password" placeholder="<?php echo $t['pass_ph']; ?>" name="password" 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 $t['remember']; ?></label>
                            </div>
                            <button type="submit" class="btn btn-primary btn-gradient btn-block font-weight-bold login-button">
                                <?php echo $t['btn']; ?>
                                <i class="fa fa-chevron-right" aria-hidden="true"></i>
                            </button>
                        </form>

                        <div class="mt-4 text-center">
                            <a href="?lang=pt" style="text-decoration: none; color: <?php echo $current_lang == 'pt' ? htmlspecialchars($cor_primaria) : '#8a94a1'; ?>; font-weight: <?php echo $current_lang == 'pt' ? 'bold' : 'normal'; ?>; margin: 0 10px; font-size: 14px; transition: 0.2s;">🇵🇹 PT</a>
                            <a href="?lang=en" style="text-decoration: none; color: <?php echo $current_lang == 'en' ? htmlspecialchars($cor_primaria) : '#8a94a1'; ?>; font-weight: <?php echo $current_lang == 'en' ? 'bold' : 'normal'; ?>; margin: 0 10px; font-size: 14px; transition: 0.2s;">🇬🇧 EN</a>
                            <a href="?lang=fr" style="text-decoration: none; color: <?php echo $current_lang == 'fr' ? htmlspecialchars($cor_primaria) : '#8a94a1'; ?>; font-weight: <?php echo $current_lang == 'fr' ? 'bold' : 'normal'; ?>; margin: 0 10px; font-size: 14px; transition: 0.2s;">🇫🇷 FR</a>
                            <a href="?lang=de" style="text-decoration: none; color: <?php echo $current_lang == 'de' ? htmlspecialchars($cor_primaria) : '#8a94a1'; ?>; font-weight: <?php echo $current_lang == 'de' ? 'bold' : 'normal'; ?>; margin: 0 10px; font-size: 14px; transition: 0.2s;">🇩🇪 DE</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <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://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">

    <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">
        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);
        }

        /* LOADING ICON */
        $("#form-login").submit(function(event) {
            $('.login-button').html('<span class="gradient">Conectando... <i class="fa fa-spinner fa-spin" aria-hidden="true"></i></span>');
        });

        /* CLOSE ALERTS */
        $(".alert").delay(3000).slideUp(200, function() {
            $(this).alert('close');
        });

        /* PRE-LOADER JS */
        $(function () {
            setTimeout(function(){
                $("#loader-wrapper").fadeOut(250);
            }, 100);
        });
    </script>
</body>
</html>
