<?php
require_once __DIR__ . '/../config.php';

if (session_status() === PHP_SESSION_NONE) {
    session_set_cookie_params([
        'lifetime' => 7200,
        'path'     => '/',
        'secure'   => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
        'httponly' => true,
        'samesite' => 'Strict',
    ]);
    session_start();
}

if (!empty($_SESSION['admin_id'])) {
    header('Location: index.php'); exit;
}

function db(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        $pdo = new PDO(
            'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4',
            DB_USER, DB_PASS,
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
        );
    }
    return $pdo;
}

// ── Rate limiting por IP (máx 10 tentativas em 15 min) ──────
function login_rate_limit(): bool {
    $ip      = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $key     = 'login_fail_' . md5($ip);
    $file    = sys_get_temp_dir() . '/' . $key . '.json';
    $window  = 900;   // 15 minutos
    $max     = 10;

    $data = ['count' => 0, 'first' => time()];
    if (file_exists($file)) {
        $data = json_decode(file_get_contents($file), true) ?? $data;
    }

    if ((time() - $data['first']) > $window) {
        $data = ['count' => 0, 'first' => time()];
    }

    if ($data['count'] >= $max) return false;

    $data['count']++;
    file_put_contents($file, json_encode($data), LOCK_EX);
    return true;
}

function login_clear_limit(): void {
    $ip   = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $file = sys_get_temp_dir() . '/login_fail_' . md5($ip) . '.json';
    @unlink($file);
}

$error   = '';
$timeout = isset($_GET['reason']) && $_GET['reason'] === 'timeout';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $pass  = $_POST['pass'] ?? '';

    // Delay mínimo para dificultar timing attacks
    usleep(random_int(100000, 300000));

    if (!login_rate_limit()) {
        $error = 'Muitas tentativas. Aguarde 15 minutos.';
    } else {
        try {
            $stmt = db()->prepare("SELECT * FROM admins WHERE email = ? LIMIT 1");
            $stmt->execute([$email]);
            $admin = $stmt->fetch();

            if ($admin && password_verify($pass, $admin['password_hash'])) {
                login_clear_limit();
                session_regenerate_id(true);
                $_SESSION['admin_id']            = $admin['id'];
                $_SESSION['admin_name']          = $admin['name'];
                $_SESSION['admin_last_activity'] = time();
                $_SESSION['csrf_token']          = bin2hex(random_bytes(32));
                header('Location: index.php');
                exit;
            }
            // Mensagem genérica — não revela se e-mail existe
            $error = 'Credenciais inválidas.';
        } catch (Throwable $e) {
            $error = 'Erro de conexão com o banco.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<title>MonitorPing — Painel de Licenças</title>
<style>
  body { font-family:sans-serif; background:#0f172a; display:flex; align-items:center; justify-content:center; height:100vh; margin:0; }
  .box { background:#1e293b; padding:2rem; border-radius:8px; width:320px; color:#e2e8f0; }
  h2 { margin:0 0 1.5rem; text-align:center; color:#38bdf8; }
  label { display:block; font-size:.85rem; color:#94a3b8; margin-bottom:.3rem; }
  input { width:100%; padding:.6rem; margin-bottom:1rem; border-radius:4px; border:1px solid #334155; background:#0f172a; color:#e2e8f0; box-sizing:border-box; }
  button { width:100%; padding:.7rem; background:#0ea5e9; border:none; border-radius:4px; color:#fff; font-size:1rem; cursor:pointer; }
  .alert-err  { background:#7f1d1d; color:#fecaca; padding:.5rem; border-radius:4px; margin-bottom:1rem; font-size:.9rem; }
  .alert-warn { background:#92400e; color:#fde68a; padding:.5rem; border-radius:4px; margin-bottom:1rem; font-size:.9rem; }
  .setup-link { text-align:center; margin-top:1rem; font-size:.8rem; color:#475569; }
  .setup-link a { color:#38bdf8; }
</style>
</head>
<body>
<div class="box">
  <h2>Licenças Admin</h2>
  <?php if ($timeout): ?>
    <div class="alert-warn">Sessão encerrada por inatividade.</div>
  <?php endif; ?>
  <?php if ($error): ?><div class="alert-err"><?= htmlspecialchars($error) ?></div><?php endif; ?>
  <form method="post" autocomplete="off">
    <label>E-mail</label>
    <input type="email" name="email" required autofocus autocomplete="username">
    <label>Senha</label>
    <input type="password" name="pass" required autocomplete="current-password">
    <button type="submit">Entrar</button>
  </form>
  <div class="setup-link">Primeiro acesso? <a href="setup.php">Criar admin</a></div>
</div>
</body>
</html>
