<?php
$title = $title ?? 'Admin: Login';
ob_start();
?>
<div class="card" style="max-width: 420px; margin: 0 auto;">
    <h2 style="margin-bottom:1rem;">Acesso Administrativo</h2>
    <p style="color:#555; margin-bottom:1rem;">Área exclusiva dos administradores do SaaS</p>

    <div class="form-group">
        <label for="email">E-mail</label>
        <input type="email" id="email" placeholder="admin@empresa.com" required>
    </div>
    <div class="form-group">
        <label for="password">Senha</label>
        <input type="password" id="password" placeholder="Sua senha" required>
    </div>
    <button class="btn" id="loginBtn">Entrar</button>

    <div id="loginMsg" class="alert" style="display:none; margin-top:1rem;"></div>
    <div style="margin-top:0.75rem;">
        <a class="btn btn-secondary" href="/admin/recovery">Esqueceu a senha?</a>
    </div>
</div>

<script>
document.getElementById('loginBtn').addEventListener('click', async () => {
    const email = document.getElementById('email').value.trim();
    const password = document.getElementById('password').value;
    const msg = document.getElementById('loginMsg');
    msg.style.display = 'none';

    try {
        const res = await fetch('/api/admin/auth/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ email, password })
        });
        const data = await res.json();
        if (!res.ok) {
            msg.className = 'alert alert-error';
            msg.textContent = data.error || 'Falha no login';
            msg.style.display = 'block';
            return;
        }
        const token = data.token;
        // Guardar token admin em cookie e localStorage (resiliente a host)
        document.cookie = 'admin_token=' + encodeURIComponent(token) + '; Path=/;';
        try { localStorage.setItem('admin_token', token); } catch (e) {}
        // Navegar para painel
        window.location.href = '/admin/tenants';
    } catch (e) {
        msg.className = 'alert alert-error';
        msg.textContent = 'Erro de rede: ' + e.message;
        msg.style.display = 'block';
    }
});
</script>

<?php
$content = ob_get_clean();
echo $content;
?>