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

// --- INÍCIO: BUSCA DE PERSONALIZAÇÃO DINÂMICA ---
// Define as cores e nomes padrão
$nome_painel = 'TOP IPTV';
$logo_url = '';
$cor_primaria = '#007bff';
$usar_logo = 1; // Variável nova para a chave liga/desliga

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;
            if (isset($config_painel['usar_logo'])) { $usar_logo = $config_painel['usar_logo']; }
        }
    }
} catch (Exception $e) {
    // Ignora erros de BD silenciosamente na tela de login
}

// --- 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');

// Dicionário Interno
$dict = [
    'pt' => [
        'welcome' => 'Bem-vindo de volta',
        'subtitle' => 'Entre com as suas credenciais para aceder ao painel',
        '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 to access the panel',
        '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 pour accéder au panneau',
        'user' => 'Nom d\'utilisateur',
        'user_ph' => 'Entrez votre nom d\'utilisateur',
        'pass' => 'Mot de passe',
        'pass_ph' => 'Entrez votre mot de passe',
        'remember' => 'Se souvenir de moi',
        'btn' => 'Connexion au Panneau'
    ],
    'de' => [
        'welcome' => 'Willkommen zurück',
        'subtitle' => 'Geben Sie Ihre Anmeldedaten ein',
        'user' => 'Benutzername',
        'user_ph' => 'Benutzername eingeben',
        'pass' => 'Passwort',
        'pass_ph' => 'Passwort eingeben',
        'remember' => 'Angemeldet bleiben',
        'btn' => 'Im Panel 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">
</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'); background-size: cover; background-position: center;">
                        <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="<?php echo htmlspecialchars($nome_painel); ?>">
                            <?php else: ?>
                                <h2 style="color:white; font-weight:bold; 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" href="#">
                            <?php if(!empty($logo_url) && file_exists($logo_url) && $usar_logo == 1): ?>
                                <img src="<?php echo htmlspecialchars($logo_url); ?>" width="300" alt="<?php echo htmlspecialchars($nome_painel); ?>" style="max-height: 120px; object-fit: contain;">
                            <?php else: ?>
                                <h1 style="color:var(--primary); font-weight:bold; margin-bottom: 30px;"><?php echo htmlspecialchars($nome_painel); ?></h1>
                            <?php endif; ?>
                        </a>
                        
                        <?php if (isset($_SESSION['erro_login'])): ?>
                            <div class="alert alert-danger py-2" 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">
                            <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 autofocus>
                            </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' ? $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' ? $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' ? $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' ? $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/_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/_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) {
            if($('.h-captcha').length && $('[name=h-captcha-response]').val() === ""){
                event.preventDefault();
                toastr.options = {
                  "positionClass": "toast-top-center"
                }
                toastr["warning"]("Por favor complete o hCaptcha!", "Aviso!");
            } else {
                $('.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>