<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';

session_start();

// Se já estiver logado, redireciona direto
if (isset($_SESSION['username'])) {
    header('Location: dashboard.php');
    exit;
}

// Resposta AJAX de login
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax'])) {
    header('Content-Type: application/json');
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');

    if (!$username || !$password) {
        echo json_encode(['success' => false, 'message' => 'Preencha todos os campos.']);
        exit;
    }

    try {
        $db_file = __DIR__ . "/ibo_panel.db";
        $conn = new PDO("sqlite:$db_file");
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $conn->prepare("SELECT * FROM users WHERE username = ? LIMIT 1");
        $stmt->execute([$username]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        $valid = false;
        if ($user) {
            // Tenta password_hash primeiro, depois md5, depois texto puro
            if (password_verify($password, $user['password'])) {
                $valid = true;
            } elseif (md5($password) === $user['password']) {
                $valid = true;
            } elseif ($password === $user['password']) {
                $valid = true;
            }
        }

        if ($valid) {
            $_SESSION['username'] = $user['username'];
            $_SESSION['admin']    = $user['admin']    ?? 0;
            $_SESSION['dealer']   = $user['dealer']   ?? 0;
            $_SESSION['balance']  = $user['balance']  ?? 0;
            echo json_encode(['success' => true, 'redirect' => 'dashboard.php']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Usuário ou senha inválidos.']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Erro ao conectar ao banco de dados.']);
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <title><?php echo isset($page_title) ? $page_title : "PlayPlus"; ?></title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="shortcut icon" href="<?php echo $static_url; ?>media/logos/logo.png" />
    <link href="<?php echo $static_url; ?>plugins/global/plugins.bundle.css" rel="stylesheet" />
    <link href="<?php echo $static_url; ?>css/style.bundle.css" rel="stylesheet" />
    <link href="<?php echo $static_url; ?>css/custom_style.css" rel="stylesheet" />

    <style>
        *, *::before, *::after { box-sizing: border-box; }
        html, body { height: 100%; margin: 0; overflow: hidden; }
        body { background: #0d1117; font-family: 'Segoe UI', system-ui, sans-serif; }

        /* ══════════════════════════════
           LAYOUT SPLIT
        ══════════════════════════════ */
        .auth-wrap {
            display: flex;
            height: 100vh;
            width: 100vw;
        }

        /* ══════════════════════════════
           LADO ESQUERDO — azul
        ══════════════════════════════ */
        .auth-left {
            flex: 0 0 50%;
            position: relative;
            overflow: hidden;
            background: linear-gradient(160deg, #0a2540 0%, #0d3b6e 35%, #1251a3 65%, #1a6fd4 100%);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        /* Orbs decorativos */
        .auth-left .orb {
            position: absolute;
            border-radius: 50%;
            pointer-events: none;
        }
        .orb-1 {
            width: 700px; height: 700px;
            top: -200px; left: -200px;
            background: radial-gradient(circle, rgba(255,255,255,0.06) 0%, transparent 65%);
        }
        .orb-2 {
            width: 500px; height: 500px;
            bottom: -150px; right: -150px;
            background: radial-gradient(circle, rgba(99,179,237,0.15) 0%, transparent 65%);
        }
        .orb-3 {
            width: 300px; height: 300px;
            top: 40%; left: 60%;
            background: radial-gradient(circle, rgba(255,255,255,0.04) 0%, transparent 65%);
        }

        /* Grid de pontos */
        .auth-left-dots {
            position: absolute; inset: 0;
            background-image: radial-gradient(rgba(255,255,255,0.08) 1px, transparent 1px);
            background-size: 32px 32px;
            pointer-events: none;
        }

        /* Conteúdo da esquerda */
        .auth-left-body {
            position: relative; z-index: 2;
            display: flex; flex-direction: column;
            align-items: center; justify-content: center;
            text-align: center;
            padding: 48px;
        }

        /* Logo SEM borda, grande */
        .brand-logo {
            width: 180px; height: 180px;
            object-fit: contain;
            filter: drop-shadow(0 8px 40px rgba(0,0,0,0.35));
            animation: logoFloat 5s ease-in-out infinite;
            margin-bottom: 36px;
        }
        @keyframes logoFloat {
            0%,100% { transform: translateY(0); }
            50%      { transform: translateY(-12px); }
        }

        .brand-title {
            font-size: 28px; font-weight: 800;
            color: #fff; margin: 0 0 10px;
            letter-spacing: -0.02em;
            text-shadow: 0 2px 20px rgba(0,0,0,0.3);
            animation: fadeUp 0.7s 0.3s ease both;
        }
        .brand-sub {
            color: rgba(255,255,255,0.55);
            font-size: 14px; line-height: 1.6;
            max-width: 280px;
            animation: fadeUp 0.7s 0.4s ease both;
        }

        .brand-divider {
            width: 40px; height: 3px;
            border-radius: 2px;
            background: rgba(255,255,255,0.25);
            margin: 24px auto;
            animation: fadeUp 0.7s 0.45s ease both;
        }

        .brand-badges {
            display: flex; gap: 10px; flex-wrap: wrap;
            justify-content: center;
            animation: fadeUp 0.7s 0.5s ease both;
        }
        .brand-badge {
            background: rgba(255,255,255,0.1);
            border: 1px solid rgba(255,255,255,0.18);
            backdrop-filter: blur(8px);
            border-radius: 50px; padding: 6px 16px;
            font-size: 11px; font-weight: 600;
            color: rgba(255,255,255,0.8);
            display: flex; align-items: center; gap: 6px;
        }

        /* Versão bottom-left */
        .auth-left-version {
            position: absolute; bottom: 20px; left: 0; right: 0;
            text-align: center; z-index: 2;
            color: rgba(255,255,255,0.2);
            font-size: 11px;
        }

        /* ══════════════════════════════
           LADO DIREITO — dark
        ══════════════════════════════ */
        .auth-right {
            flex: 0 0 50%;
            background: #0d1117;
            position: relative; overflow: hidden;
            display: flex; align-items: center; justify-content: center;
        }
        .auth-right::before {
            content: ''; position: absolute;
            width: 400px; height: 400px; bottom: -100px; right: -100px;
            background: radial-gradient(circle, rgba(139,92,246,0.06) 0%, transparent 65%);
            pointer-events: none;
        }
        .auth-right::after {
            content: ''; position: absolute;
            width: 300px; height: 300px; top: -80px; left: -80px;
            background: radial-gradient(circle, rgba(99,179,237,0.04) 0%, transparent 65%);
            pointer-events: none;
        }

        /* Card */
        .login-card {
            width: 100%; max-width: 400px;
            background: rgba(22,27,34,0.95);
            border: 1px solid rgba(99,179,237,0.1);
            border-radius: 20px;
            padding: 44px 40px 36px;
            box-shadow: 0 32px 80px rgba(0,0,0,0.5), inset 0 1px 0 rgba(255,255,255,0.04);
            position: relative; z-index: 1;
            animation: cardReveal 0.7s cubic-bezier(0.16,1,0.3,1) both;
        }
        @keyframes cardReveal {
            from { opacity: 0; transform: translateY(24px); }
            to   { opacity: 1; transform: translateY(0); }
        }

        .card-header-block { margin-bottom: 30px; animation: fadeUp 0.5s 0.15s ease both; }
        .card-header-block h2 {
            color: #e2e8f0; font-size: 22px; font-weight: 700;
            margin: 0 0 6px; letter-spacing: -0.01em;
        }
        .card-header-block p { color: rgba(148,163,184,0.4); font-size: 13px; margin: 0; }

        /* Campos */
        .field-wrap { position: relative; margin-bottom: 16px; }
        .field-wrap:nth-child(1) { animation: fadeUp 0.5s 0.22s ease both; }
        .field-wrap:nth-child(2) { animation: fadeUp 0.5s 0.30s ease both; }

        .field-label {
            display: block;
            color: rgba(148,163,184,0.5); font-size: 10px;
            font-weight: 700; text-transform: uppercase;
            letter-spacing: 0.09em; margin-bottom: 7px;
        }
        .field-inner { position: relative; }
        .field-inner i {
            position: absolute; left: 14px; top: 50%;
            transform: translateY(-50%);
            color: rgba(99,179,237,0.3); font-size: 13px;
            pointer-events: none; transition: color 0.2s ease;
        }
        .field-inner:focus-within i { color: #63b3ed; }
        .field-inner input {
            width: 100%;
            background: rgba(13,17,23,0.8);
            border: 1px solid rgba(99,179,237,0.1);
            border-radius: 12px;
            color: #e2e8f0; font-size: 14px; font-weight: 500;
            padding: 12px 14px 12px 42px;
            outline: none; transition: all 0.2s ease;
        }
        .field-inner input::placeholder { color: rgba(148,163,184,0.25); }
        .field-inner input:focus {
            border-color: rgba(99,179,237,0.4);
            background: rgba(13,17,23,0.95);
            box-shadow: 0 0 0 3px rgba(99,179,237,0.07);
        }

        /* Alerta de erro */
        .login-error {
            display: none;
            background: rgba(248,113,113,0.08);
            border: 1px solid rgba(248,113,113,0.2);
            border-radius: 10px;
            padding: 10px 14px;
            margin-bottom: 16px;
            align-items: center; gap: 8px;
            animation: shake 0.4s ease;
        }
        .login-error.show { display: flex; }
        .login-error i    { color: #f87171; font-size: 13px; flex-shrink: 0; }
        .login-error span { color: #f87171; font-size: 13px; font-weight: 600; }
        @keyframes shake {
            0%,100% { transform: translateX(0); }
            20%      { transform: translateX(-5px); }
            40%      { transform: translateX(5px); }
            60%      { transform: translateX(-3px); }
            80%      { transform: translateX(3px); }
        }

        /* Botão */
        .btn-submit {
            width: 100%; padding: 13px;
            background: linear-gradient(135deg, #1d4ed8, #3b82f6, #60a5fa);
            border: none; border-radius: 12px;
            color: #fff; font-size: 14px; font-weight: 700;
            letter-spacing: 0.05em; cursor: pointer;
            box-shadow: 0 4px 20px rgba(37,99,235,0.35);
            transition: all 0.25s ease;
            position: relative; overflow: hidden;
            display: flex; align-items: center; justify-content: center; gap: 8px;
            margin-top: 8px;
            animation: fadeUp 0.5s 0.38s ease both;
        }
        .btn-submit::before {
            content: ''; position: absolute; inset: 0;
            background: linear-gradient(135deg, rgba(255,255,255,0.12), transparent);
            opacity: 0; transition: opacity 0.2s ease;
        }
        .btn-submit:hover { transform: translateY(-2px); box-shadow: 0 8px 28px rgba(37,99,235,0.5); }
        .btn-submit:hover::before { opacity: 1; }
        .btn-submit:active { transform: translateY(0); }
        .btn-submit:disabled { opacity: 0.7; cursor: not-allowed; transform: none; }

        .btn-label   { display: flex; align-items: center; gap: 8px; }
        .btn-loading { display: none; align-items: center; gap: 8px; }
        .btn-submit.loading .btn-label   { display: none; }
        .btn-submit.loading .btn-loading { display: flex; }

        .dots span {
            display: inline-block; width: 6px; height: 6px;
            border-radius: 50%; background: #fff;
            animation: dotBounce 1.1s ease-in-out infinite;
        }
        .dots span:nth-child(2) { animation-delay: .18s; }
        .dots span:nth-child(3) { animation-delay: .36s; }
        @keyframes dotBounce {
            0%,80%,100% { transform: scale(0.5); opacity: 0.4; }
            40%          { transform: scale(1);   opacity: 1; }
        }

        /* Sucesso */
        .login-success {
            display: none;
            background: rgba(52,211,153,0.08);
            border: 1px solid rgba(52,211,153,0.2);
            border-radius: 10px;
            padding: 10px 14px;
            margin-bottom: 16px;
            align-items: center; gap: 8px;
        }
        .login-success.show { display: flex; }
        .login-success i    { color: #34d399; font-size: 13px; }
        .login-success span { color: #34d399; font-size: 13px; font-weight: 600; }

        /* Footer */
        .card-footer-text {
            margin-top: 24px; text-align: center;
            color: rgba(148,163,184,0.2); font-size: 11px;
            display: flex; align-items: center; justify-content: center; gap: 6px;
            animation: fadeUp 0.5s 0.48s ease both;
        }
        .card-footer-text i { color: #3b82f6; }

        @keyframes fadeUp {
            from { opacity: 0; transform: translateY(10px); }
            to   { opacity: 1; transform: translateY(0); }
        }

        /* Mobile */
        @media (max-width: 991px) {
            .auth-left  { display: none; }
            .auth-right { flex: 1; }
            .login-card { padding: 36px 24px 28px; }
        }
    </style>
</head>
<body>

<div class="auth-wrap">

    <!-- ══ ESQUERDA — azul ══ -->
    <div class="auth-left">
        <div class="orb orb-1"></div>
        <div class="orb orb-2"></div>
        <div class="orb orb-3"></div>
        <div class="auth-left-dots"></div>

        <div class="auth-left-body">
            <!-- Logo grande, sem borda, sem ring -->
            <img
                class="brand-logo"
                src="<?php echo $static_url; ?>media/logos/logo.png"
                alt="Logo"
            />

            <h1 class="brand-title">Bem-vindo ao PlayPlus</h1>
            <p class="brand-sub">Gerencie DNS, usuários, chatbots e muito mais em um só painel.</p>

            <div class="brand-divider"></div>

            <div class="brand-badges">
                <span class="brand-badge"><i class="fa-solid fa-globe"></i> DNS</span>
                <span class="brand-badge"><i class="fa-solid fa-users"></i> Usuários</span>
                <span class="brand-badge"><i class="fa-solid fa-robot"></i> Chatbots</span>
            </div>
        </div>

        <div class="auth-left-version">PlayPlus &copy; <?php echo date('Y'); ?></div>
    </div>

    <!-- ══ DIREITA — dark ══ -->
    <div class="auth-right">
        <div class="login-card">

            <div class="card-header-block">
                <h2>Entrar na conta</h2>
                <p>Insira suas credenciais para continuar</p>
            </div>

            <!-- Erro -->
            <div class="login-error" id="loginError">
                <i class="fa-solid fa-circle-exclamation"></i>
                <span id="loginErrorMsg">Usuário ou senha inválidos.</span>
            </div>

            <!-- Sucesso -->
            <div class="login-success" id="loginSuccess">
                <i class="fa-solid fa-circle-check"></i>
                <span>Login realizado! Redirecionando…</span>
            </div>

            <div class="field-wrap">
                <label class="field-label">Usuário</label>
                <div class="field-inner">
                    <i class="fa-solid fa-user"></i>
                    <input type="text" id="loginUser" placeholder="Digite seu usuário" autocomplete="off" />
                </div>
            </div>

            <div class="field-wrap">
                <label class="field-label">Senha</label>
                <div class="field-inner">
                    <i class="fa-solid fa-lock"></i>
                    <input type="password" id="loginPass" placeholder="Digite sua senha" />
                </div>
            </div>

            <button class="btn-submit" id="loginBtn" type="button">
                <span class="btn-label">
                    <i class="fa-solid fa-right-to-bracket"></i>ENTRAR
                </span>
                <span class="btn-loading">
                    <div class="dots"><span></span><span></span><span></span></div>
                    Verificando...
                </span>
            </button>

            <div class="card-footer-text">
                <i class="fa-solid fa-circle-play"></i>
                PlayPlus &copy; <?php echo date('Y'); ?>
            </div>

        </div>
    </div>

</div>

<!-- Carrega os bundles do template (não usa users.js para login) -->
<script src="<?php echo $static_url; ?>plugins/global/plugins.bundle.js"></script>
<script src="<?php echo $static_url; ?>js/scripts.bundle.js"></script>

<script>
(function () {
    var btn       = document.getElementById('loginBtn');
    var userInput = document.getElementById('loginUser');
    var passInput = document.getElementById('loginPass');
    var errorBox  = document.getElementById('loginError');
    var errorMsg  = document.getElementById('loginErrorMsg');
    var successBox= document.getElementById('loginSuccess');

    function showError(msg) {
        errorMsg.textContent = msg;
        errorBox.classList.add('show');
        successBox.classList.remove('show');
        // reinicia animação de shake
        errorBox.style.animation = 'none';
        errorBox.offsetHeight;
        errorBox.style.animation = '';
        btn.classList.remove('loading');
        btn.disabled = false;
    }

    function doLogin() {
        var username = userInput.value.trim();
        var password = passInput.value.trim();

        errorBox.classList.remove('show');
        successBox.classList.remove('show');

        if (!username || !password) {
            showError('Preencha todos os campos.');
            return;
        }

        btn.classList.add('loading');
        btn.disabled = true;

        var body = new URLSearchParams({
            ajax: '1',
            username: username,
            password: password
        });

        fetch(window.location.href, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: body.toString()
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.success) {
                // Mostra sucesso por 800ms e redireciona — sem nenhum botão OK
                successBox.classList.add('show');
                btn.classList.remove('loading');
                setTimeout(function() {
                    window.location.href = data.redirect || 'dashboard.php';
                }, 800);
            } else {
                showError(data.message || 'Usuário ou senha inválidos.');
            }
        })
        .catch(function() {
            showError('Erro de conexão. Tente novamente.');
        });
    }

    // Clique no botão
    btn.addEventListener('click', doLogin);

    // Enter nos campos
    userInput.addEventListener('keydown', function(e) { if (e.key === 'Enter') passInput.focus(); });
    passInput.addEventListener('keydown', function(e) { if (e.key === 'Enter') doLogin(); });
})();
</script>

</body>
</html>