<?php
// OneLauncher - login.php
session_start();
require_once 'db.php';

$error = '';

if (isset($_POST['login'])) {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';

    $stmt = $conn->prepare("SELECT id, password FROM admins WHERE username = ?");

    if ($stmt === false) {
        // Fallback: tabela admins pode não existir ainda, tenta recriar
        $conn->query("CREATE TABLE IF NOT EXISTS admins (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username varchar(50) NOT NULL,
            password varchar(255) NOT NULL,
            role varchar(20) DEFAULT 'master',
            app_token varchar(64) DEFAULT NULL
        )");
        $passHash = password_hash('admin123', PASSWORD_DEFAULT);
        $conn->query("INSERT OR IGNORE INTO admins (username, password, role) VALUES ('admin', '$passHash', 'superadmin')");
        $stmt = $conn->prepare("SELECT id, password FROM admins WHERE username = ?");
    }

    if ($stmt === false) {
        $error = 'Erro interno no banco de dados. Contate o administrador.';
    } else {
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($row = $result->fetch_assoc()) {
            if (password_verify($password, $row['password'])) {
                $_SESSION['admin_id'] = $row['id'];
                $_SESSION['admin_username'] = $username;
                header('Location: dashboard.php');
                exit;
            } else {
                $error = 'Senha incorreta!';
            }
        } else {
            $error = 'Usuário não encontrado!';
        }
    }
}
$logo_url = 'assets/upload/logo.png';
$panel_title = 'Painel Admin';
$resConfig = $conn->query("SELECT app_logo, panel_title FROM config WHERE theme_id = 1 LIMIT 1");
if ($resConfig && $rowConfig = $resConfig->fetch_assoc()) {
    if (!empty($rowConfig['app_logo'])) {
        $logo_url = $rowConfig['app_logo'];
    }
    if (!empty($rowConfig['panel_title'])) {
        $panel_title = $rowConfig['panel_title'];
    }
}
$logo_cache_bust = file_exists(__DIR__ . '/assets/upload/logo.png') ? filemtime(__DIR__ . '/assets/upload/logo.png') : time();
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - <?php echo htmlspecialchars($panel_title); ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&family=Fira+Sans:wght@400;500&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <style>
        :root {
            --bg-dark: #0B1121;
            --accent-blue: #3B82F6;
            --accent-cyan: #06B6D4;
        }
        body { 
            background: var(--bg-dark); 
            color: #fff; 
            font-family: 'Fira Sans', sans-serif;
            display: flex; 
            align-items: center; 
            justify-content: center; 
            min-height: 100vh;
            margin: 0;
            overflow: hidden;
        }
        .bg-glow {
            position: absolute;
            width: 100%;
            height: 100%;
            background: 
                radial-gradient(circle at 20% 20%, rgba(59, 130, 246, 0.15), transparent 40%),
                radial-gradient(circle at 80% 80%, rgba(6, 182, 212, 0.15), transparent 40%);
            z-index: -1;
        }
        .login-card { 
            background: rgba(255, 255, 255, 0.03); 
            backdrop-filter: blur(20px); 
            padding: 40px; 
            border-radius: 24px; 
            width: 100%; 
            max-width: 420px; 
            border: 1px solid rgba(255,255,255,0.08); 
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
        }
        .login-logo-img {
            max-height: 90px;
            max-width: 260px;
            height: auto;
            width: auto;
            object-fit: contain;
            filter: drop-shadow(0 4px 12px rgba(0, 0, 0, 0.4));
            transition: all 0.3s ease;
        }
        h2 { font-family: 'Poppins', sans-serif; font-weight: 700; letter-spacing: -0.5px; }
        .form-label { font-size: 0.85rem; font-weight: 600; color: rgba(255,255,255,0.6); margin-bottom: 8px; }
        .form-control { 
            background: rgba(255,255,255,0.05); 
            border: 1px solid rgba(255,255,255,0.1); 
            color: #fff; 
            border-radius: 12px;
            padding: 12px 16px;
            transition: all 0.3s;
        }
        .form-control:focus { 
            background: rgba(255,255,255,0.08); 
            border-color: var(--accent-blue); 
            box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.15);
            color: #fff;
        }
        .btn-primary { 
            background: linear-gradient(135deg, var(--accent-blue), var(--accent-cyan)); 
            border: none; 
            border-radius: 12px;
            padding: 12px;
            font-weight: 700;
            font-size: 0.95rem;
            margin-top: 10px;
            transition: all 0.3s;
        }
        .btn-primary:hover { 
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(59, 130, 246, 0.3);
        }
        .input-group-text {
            background: rgba(255,255,255,0.05);
            border: 1px solid rgba(255,255,255,0.1);
            color: rgba(255,255,255,0.5);
            border-radius: 12px 0 0 12px;
        }
        .form-control { border-radius: 0 12px 12px 0; }
    </style>
</head>
<body>
    <div class="bg-glow"></div>
    <div class="login-card">
        <div class="text-center mb-3">
            <img src="assets/upload/logo.png?v=<?php echo $logo_cache_bust; ?>" alt="Logo" class="login-logo-img">
        </div>
        <p class="text-center text-white-50 mb-4 small">Entre com suas credenciais</p>
        
        <?php if ($error): ?>
            <div class="alert alert-danger border-0 bg-danger bg-opacity-25 text-danger small py-2 px-3 rounded-3 mb-4">
                <i class="bi bi-exclamation-triangle-fill me-2"></i><?php echo $error; ?>
            </div>
        <?php endif; ?>

        <form method="POST">
            <div class="mb-3">
                <label class="form-label">Usuário</label>
                <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-person"></i></span>
                    <input type="text" name="username" class="form-control" placeholder="Seu usuário" required>
                </div>
            </div>
            <div class="mb-4">
                <label class="form-label">Senha</label>
                <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-lock"></i></span>
                    <input type="password" name="password" class="form-control" placeholder="••••••••" required>
                </div>
            </div>
            <button type="submit" name="login" class="btn btn-primary w-100">ACESSAR PAINEL</button>
        </form>
        
        <p class="text-center mt-4 mb-0" style="font-size: 0.75rem; color: rgba(255,255,255,0.3);">
            &copy; <?php echo date('Y'); ?> <?php echo htmlspecialchars($panel_title); ?>
        </p>
    </div>
</body>
</html>
