<?php
// Inclui funções e inicia a sessão
include "includes/functions.php";

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Verifica se o usuário está logado
$log_check = $db->select("users", "*", "id = :id", "", [":id" => 1]);
$loggedinuser = !empty($log_check) ? $log_check[0]["username"] : NULL;
if (!empty($loggedinuser) && isset($_SESSION["name"]) && $_SESSION["name"] === $loggedinuser) {
    header("Location: dns.php");
    exit;
}

// Insere o usuário admin se não existir
$data = ["id" => "1", "username" => "admin", "password" => "admin"];
$db->insertIfEmpty("users", $data);

// Processa o login
if (isset($_POST["login"])) {
    $username = $_POST["username"];
    $password = $_POST["password"];

    $userData = $db->select(
        "users",
        "*",
        "username = :username",
        "",
        [":username" => $username]
    );

    // Helper para enviar para a tela de erro
    $goErr = function (string $code) {
        header('Location: ./login_erro.php?err=' . urlencode($code) . '&back=' . urlencode('./login.php'));
        exit;
    };

    if ($userData) {
        $storedPassword = $userData[0]["password"] ?? '';

        if ($password === $storedPassword) { // mantém compatibilidade com senha em texto
            session_regenerate_id(true);
            $_SESSION["loggedin"] = true;
            $_SESSION["name"] = $username;

            header($username === "admin" ? "Location: dashboard.php" : "Location: dns.php");
            exit;
        } else {
            // senha incorreta
            $goErr('password'); // use 'auth' se quiser mensagem genérica
        }
    } else {
        // usuário não encontrado
        $goErr('user'); // use 'auth' se quiser mensagem genérica
    }

    $db->close();
}

$file_name = './codigo_json.json';
$json_data = file_get_contents($file_name);

if ($json_data === false) {
    die("Erro ao ler o arquivo JSON.");
}

$data = json_decode($json_data, true);
$codigo = $data['codigo'];
$ano    = date('Y');

// HTML da página
echo <<<HTML
<!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">
    <meta name="author" content="P2PLAY APPS">

    <!-- Title -->
    <title>IBO VS4 by P2PLAY</title>

    <!-- Favicons (coloque os arquivos em /img) -->
    <link rel="apple-touch-icon" sizes="180x180" href="img/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png">
    <link rel="manifest" href="img/site.webmanifest">
    <meta name="theme-color" content="#121212">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">

    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <style>
        :root {
            --primary-color: #8000FF;
            --primary-dark: #6200E6;
            --secondary-color: #FF9100;
            --dark-bg: #121212;
            --card-bg: rgba(30, 30, 40, 0.9);
            --text-color: #f8f9fa;
            --input-bg: rgba(255, 255, 255, 0.08);
            --input-border: rgba(255, 255, 255, 0.1);
        }

        body {
            font-family: 'Poppins', sans-serif;
            background-color: var(--dark-bg);
            background-image:
                radial-gradient(circle at 25% 25%, rgba(128, 0, 255, 0.2) 0%, transparent 50%),
                radial-gradient(circle at 75% 75%, rgba(255, 145, 0, 0.2) 0%, transparent 50%);
            color: var(--text-color);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0;
            padding: 1rem;
            position: relative;
            overflow-x: hidden;
        }

        #js-particles {
            position: fixed;
            top: 0; left: 0;
            width: 100%; height: 100%;
            z-index: -1;
        }

        .login-container {
            background-color: var(--card-bg);
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.08);
            padding: 2.5rem;
            width: 100%;
            max-width: 420px;
            transition: all 0.3s ease;
            margin: auto;
        }

        .logo-container { margin-bottom: 1rem; text-align: center; }
        .logo-container img {
            width: 100%;
            max-height: 150px;
            height: auto;
            transition: all 0.3s ease;
            object-fit: contain;
        }
        /* Subtítulo abaixo do logo (pedido: IBO VS4) */
        .app-subtitle{
            text-align:center;
            font-weight: 800;
            color:#cfe6ff;
            margin-bottom: 1.2rem;
            letter-spacing:.4px;
        }

        .form-group { margin-bottom: 1.5rem; position: relative; }
        .form-control {
            background-color: var(--input-bg);
            border: 1px solid var(--input-border);
            border-radius: 12px;
            color: var(--text-color);
            padding: 0.8rem 1rem 0.8rem 3rem;
            font-size: 1rem;
            transition: all 0.3s ease;
            height: auto; width: 100%;
        }
        .form-control:focus {
            background-color: rgba(255, 255, 255, 0.12);
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(128, 0, 255, 0.2);
            color: white;
        }
        .form-control::placeholder { color: rgba(255, 255, 255, 0.6); }

        .form-group i {
            position: absolute; left: 1rem; top: 50%;
            transform: translateY(-50%);
            color: rgba(255, 255, 255, 0.6);
            font-size: 1.2rem; transition: all 0.3s ease;
        }
        .form-control:focus + i { color: var(--primary-color); }

        .btn {
            border-radius: 12px; padding: 0.8rem 1.5rem;
            font-weight: 600; letter-spacing: .5px;
            transition: all 0.3s ease; text-transform: uppercase;
            font-size: .95rem; width: 100%; display: block;
        }
        .btn-primary {
            background-color: var(--primary-color); border-color: var(--primary-color);
            box-shadow: 0 4px 15px rgba(128, 0, 255, 0.3);
        }
        .btn-primary:hover, .btn-primary:focus {
            background-color: var(--primary-dark); border-color: var(--primary-dark);
            transform: translateY(-2px); box-shadow: 0 6px 20px rgba(128, 0, 255, 0.4);
        }
        .btn-warning {
            background-color: var(--secondary-color); border-color: var(--secondary-color); color: white;
            box-shadow: 0 4px 15px rgba(255, 145, 0, 0.3);
        }
        .btn-warning:hover, .btn-warning:focus {
            background-color: #E68200; border-color: #E68200; color: white;
            transform: translateY(-2px); box-shadow: 0 6px 20px rgba(255, 145, 0, 0.4);
        }
        .btn i { margin-right: .5rem; }

        .company-info {
            text-align: center; margin-top: 2rem; padding-top: 1.25rem;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
        }
        .company-name { font-size: .95rem; color: rgba(255,255,255,.8); line-height: 1.6; display:block; margin-bottom: .5rem; }

        /* WhatsApp */
        .zap-wrap{ display:flex; justify-content:center; margin-top:.75rem; }
        .zap-wrap a{
            display:inline-flex; align-items:center; justify-content:center;
            width:80px; height:80px; border-radius:50%;
            background:#0f172a; border:1px solid rgba(255,255,255,.08);
            box-shadow: 0 10px 25px rgba(16,185,129,.25);
        }
        .zap-wrap img{ width:80px; height:80px; display:block; }

        .login-container:hover { transform: translateY(-5px); box-shadow: 0 12px 40px rgba(0,0,0,.3); }

        /* Responsividade */
        @media (max-width: 768px) {
            body { padding: .5rem; display:flex; align-items:center; }
            .login-container { padding: 1.75rem; max-width: 95%; margin: 0 auto; }
            .logo-container img { max-height: 100px; }
            .zap-wrap a{ width:64px; height:64px; } .zap-wrap img{ width:64px; height:64px; }
        }
        @media (max-width: 480px) {
            .login-container { padding: 1.5rem; border-radius: 12px; }
            .logo-container { margin-bottom: 1rem; }
            .logo-container img { max-height: 80px; }
        }
    </style>
</head>
<body>
    <div id="js-particles"></div>

    <div class="container">
        <div class="login-container">
            <div class="logo-container">
                <img src="img/logo.png?v=2.0" alt="Logo P2PLAY">
            </div>
            <div class="app-subtitle">IBO VS4</div>

            <form method="post">
                <div class="form-group">
                    <input type="text" class="form-control" placeholder="Nome de usuário" name="username" required autofocus>
                    <i class="fas fa-user"></i>
                </div>

                <div class="form-group">
                    <input type="password" class="form-control" placeholder="Senha" name="password" required>
                    <i class="fas fa-lock"></i>
                </div>

                <button type="submit" class="btn btn-warning mb-3" name="login">
                    <i class="fas fa-sign-in-alt"></i> Entrar
                </button>
            </form>
            
            <a href="./index.php" class="btn btn-outline-light w-100">
    <i class="fas fa-arrow-left me-1"></i> Voltar
</a>

            <!-- REMOVIDO: botão 'Renove seu acesso aqui' -->

            <div class="company-info">
                <span class="company-name">P2PLAY APPS &copy; {$ano}</span>

                <!-- REMOVIDO: texto 'IBO P2P' -->

                <!-- Substitui 'Suporte Técnico' por ícone WhatsApp -->
                <div class="zap-wrap">
                    <a href="https://wa.me/5595984209043" target="_blank" title="Suporte — P2PLAY">
                        <img src="https://i.postimg.cc/Gmhx1TX1/whatsapp.png" alt="Suporte WhatsApp">
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>
    <script>
        // Configuração do particles.js (mantida)
        document.addEventListener('DOMContentLoaded', function() {
            if (typeof particlesJS !== 'undefined') {
                particlesJS('js-particles', {
                    "particles": {
                        "number": { "value": 60, "density": { "enable": true, "value_area": 800 } },
                        "color": { "value": "#8000FF" },
                        "shape": { "type": "circle", "stroke": { "width": 0, "color": "#000000" } },
                        "opacity": { "value": 0.5, "random": false },
                        "size": { "value": 3, "random": true },
                        "line_linked": { "enable": true, "distance": 120, "color": "#8000FF", "opacity": 0.3, "width": 1 },
                        "move": { "enable": true, "speed": 1.5, "direction": "none", "random": false, "straight": false, "out_mode": "out" }
                    },
                    "interactivity": {
                        "detect_on": "canvas",
                        "events": {
                            "onhover": { "enable": true, "mode": "grab" },
                            "onclick": { "enable": true, "mode": "push" },
                            "resize": true
                        },
                        "modes": {
                            "grab": { "distance": 120, "line_linked": { "opacity": 0.8 } },
                            "push": { "particles_nb": 3 }
                        }
                    },
                    "retina_detect": true
                });
            }

            // Ajusta canvas em mobile
            function resizeParticles() {
                const canvas = document.querySelector('#js-particles canvas');
                if (canvas) { canvas.style.width='100%'; canvas.style.height='100%'; }
            }
            window.addEventListener('resize', resizeParticles);
            resizeParticles();
        });
    </script>
</body>
</html>
HTML;
?>

