<?php
// =============================================
// CONFIGURAÇÃO INICIAL
// =============================================
session_start();

// Carrega informações do JSON
$jsondata111 = file_get_contents('./includes/boxbr.json');
$json111 = json_decode($jsondata111, true);
$col1 = $json111['info'];
$col2 = $col1['aa'];

// Conexão com o banco de dados
$db = new SQLite3('./api/.boxbrpanels.db');

// =============================================
// CRIAÇÃO DAS TABELAS
// =============================================
$db->exec("CREATE TABLE IF NOT EXISTS USERS(
    ID INTEGER PRIMARY KEY,
    NAME TEXT,
    USERNAME TEXT,
    PASSWORD TEXT,
    LOGO TEXT
)");

$db->exec("CREATE TABLE IF NOT EXISTS LOGS(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER,
    username TEXT,
    ip TEXT,
    data_acesso TEXT
)");

// =============================================
// INSERÇÃO DE USUÁRIOS PADRÃO (CASO NÃO EXISTAM)
// =============================================
$rows = $db->query("SELECT COUNT(*) as count FROM USERS");
$row = $rows->fetchArray();
$numRows = $row['count'];

if ($numRows == 0) {
    $db->exec("INSERT INTO USERS(ID, NAME, USERNAME, PASSWORD, LOGO) VALUES
        (1, 'Your Name', 'admin', 'admin', 'img/logo.png'),
        (2, 'MASTER ADMIN', 'MASTERN3', 'MASTERN3', 'img/admin.png')
    ");
}

// =============================================
// FUNÇÃO PARA REGISTRAR ACESSO NO LOG
// =============================================
function registrarLog(SQLite3 $db, $user_id, $username) {
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'desconhecido';
    $data = date('Y-m-d H:i:s');

    $stmt = $db->prepare("INSERT INTO LOGS (user_id, username, ip, data_acesso) 
                          VALUES (:user_id, :username, :ip, :data)");
    $stmt->bindValue(':user_id', $user_id, SQLITE3_INTEGER);
    $stmt->bindValue(':username', $username, SQLITE3_TEXT);
    $stmt->bindValue(':ip', $ip, SQLITE3_TEXT);
    $stmt->bindValue(':data', $data, SQLITE3_TEXT);
    $stmt->execute();
}

// =============================================
// LOGIN
// =============================================
if (isset($_POST['login'])) {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);

    $stmt = $db->prepare("SELECT * FROM USERS WHERE USERNAME = :username");
    $stmt->bindValue(':username', $username, SQLITE3_TEXT);
    $result = $stmt->execute();
    $user = $result->fetchArray(SQLITE3_ASSOC);

    if ($user && $user['PASSWORD'] === $password) {
        $_SESSION['loggedin'] = true;
        $_SESSION['N'] = $username;

        // Salva log do acesso
        registrarLog($db, $user['ID'], $username);

        header("Location: dns.php");
        exit;
    } else {
        $error_message = '<div class="alert alert-danger">Usuário ou senha incorretos!</div>';
    }
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>UniTV BR</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet">
    <style>
        /* ======= VARIÁVEIS E RESET ======= */
        :root {
            --primary: #4361ee;
            --secondary: #3f37c9;
            --white: #ffffff;
            --transition: all 0.3s ease;
        }
        * {margin:0; padding:0; box-sizing:border-box;}
        body, html {
            width:100%; height:100%;
            font-family:'Poppins',sans-serif;
            background:linear-gradient(135deg,#0f2027,#203a43,#2c5364);
            color:var(--white);
            overflow:hidden;
        }

        /* ======= CONTAINERS ======= */
        #particles-js {
            position:fixed; width:100%; height:100%; top:0; left:0; z-index:0;
        }
        .main-container {
            position:relative; width:100%; height:100vh;
            display:flex; justify-content:center; align-items:center; z-index:1;
        }
        .panels-container {
            width:100%; max-width:800px; height:500px;
            display:flex; justify-content:center; align-items:center; position:relative;
        }
        .panel {
            position:absolute; width:100%; height:100%; padding:2rem;
            display:flex; flex-direction:column; justify-content:center; align-items:center;
            background:rgba(255,255,255,0.1); backdrop-filter:blur(10px);
            border-radius:20px; border:1px solid rgba(255,255,255,0.1);
            box-shadow:0 15px 35px rgba(0,0,0,0.2);
            transition:var(--transition); overflow:hidden;
        }

        /* ======= WELCOME PANEL ======= */
        .welcome-panel {z-index:2; opacity:1;}
        .welcome-panel.hidden {transform:translateX(-100%); opacity:0; pointer-events:none;}
        .login-panel {z-index:1; transform:translateX(100%); opacity:0;}
        .login-panel.active {transform:translateX(0); opacity:1; pointer-events:all;}

        /* ======= LOGO E TEXTOS ======= */
        .logo {width:150px; height:150px; margin-bottom:1.5rem; border-radius:50%; object-fit:contain;}
        .title {font-size:2.2rem; font-weight:700; margin-bottom:.5rem; text-align:center;}
        .subtitle {font-size:1rem; color:rgba(255,255,255,.7); margin-bottom:2rem; text-align:center; max-width:400px;}

        /* ======= BOTÕES E FORM ======= */
        .btn {padding:15px 40px; border:none; border-radius:50px; cursor:pointer; transition:var(--transition);}
        .btn-primary {background:linear-gradient(45deg,var(--primary),var(--secondary)); color:#fff;}
        .btn-primary:hover {transform:translateY(-3px);}
        .login-form {width:100%; max-width:350px;}
        .login-title {font-size:1.8rem; font-weight:600; margin-bottom:1.5rem; text-align:center;}
        .input-group {position:relative; margin-bottom:1.5rem;}
        .input-group i {position:absolute; left:15px; top:50%; transform:translateY(-50%); color:rgba(255,255,255,0.7);}
        .form-input {
            width:100%; padding:15px 15px 15px 45px; border-radius:50px; border:1px solid rgba(255,255,255,.2);
            background:rgba(255,255,255,.1); color:#fff; font-size:1rem;
        }
        .alert {padding:15px; border-radius:5px; margin-bottom:15px; text-align:center;}
        .alert-danger {background:#f8d7da; color:#721c24;}
    </style>
</head>
<body>
    <!-- Partículas -->
    <div id="particles-js"></div>
    
    <div class="main-container">
        <div class="panels-container">
            <!-- Painel de Boas-Vindas -->
            <div class="panel welcome-panel" id="welcomePanel">
                <img src="img/logo.png" alt="Logo" class="logo">
                <h1 class="title">UniTV BR</h1>
                <p class="subtitle">Sistema de gerenciamento avançado</p>
                <button class="btn btn-primary" id="startBtn">INICIAR SESSÃO</button>
            </div>
            
            <!-- Painel de Login -->
            <div class="panel login-panel" id="loginPanel">
                <div class="login-form">
                    <h2 class="login-title">Acesso Restrito</h2>
                    <p class="login-subtitle">Insira suas credenciais para continuar</p>
                    
                    <?php if (isset($error_message)) echo $error_message; ?>
                    
                    <form method="post" action="">
                        <div class="input-group">
                            <i class="fas fa-user"></i>
                            <input type="text" name="username" class="form-input" placeholder="Usuário" required>
                        </div>
                        <div class="input-group">
                            <i class="fas fa-lock"></i>
                            <input type="password" name="password" class="form-input" placeholder="Senha" required>
                        </div>
                        <button type="submit" name="login" class="btn btn-primary" style="width:100%;">ENTRAR</button>
                    </form>
                    <button class="btn back-btn" id="backBtn"><i class="fas fa-arrow-left"></i> Voltar</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/particles.js@2.0.0/particles.min.js"></script>
    <script>
        particlesJS("particles-js", {
            particles: {number:{value:80}, color:{value:"#fff"}, size:{value:3,random:true},
                        line_linked:{enable:true, color:"#fff"}, move:{enable:true,speed:2}},
            interactivity:{events:{onhover:{enable:true,mode:"repulse"}}}
        });
        document.getElementById('startBtn').onclick = () => {
            document.getElementById('welcomePanel').classList.add('hidden');
            document.getElementById('loginPanel').classList.add('active');
        };
        document.getElementById('backBtn').onclick = () => {
            document.getElementById('welcomePanel').classList.remove('hidden');
            document.getElementById('loginPanel').classList.remove('active');
        };
    </script>
</body>
</html>
