<?php
require_once __DIR__ . '/lib/auth.php';

if (is_logged_in()) {
    header('Location: pages/dashboard.php');
    exit;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    if ($username !== '' && $password !== '') {
        $result = omsorgcore_login(_omsorgcore_config(), $username, $password);

        if ($result['ok']) {
            session_regenerate_id(true);
            _apply_token_pair($result['data']);
            _refresh_profile();

            header('Location: ' . (must_change_password() ? 'pages/change-password.php' : 'pages/dashboard.php'));
            exit;
        }

        if ($result['status'] === 429) {
            $error = 'Zu viele Fehlversuche. Bitte warte ca. 10 Minuten.';
        } elseif ($result['status'] === 0) {
            $error = 'Server nicht erreichbar. Bitte später erneut versuchen.';
        } else {
            $error = 'Benutzername oder Passwort falsch.';
        }
    } else {
        $error = 'Benutzername oder Passwort falsch.';
    }
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>OMSORG Felix – Login</title>
<link rel="stylesheet" href="app.css">
<link rel="manifest" href="manifest.webmanifest">
<meta name="theme-color" content="#1a3a5c">
</head>
<body>

<div class="login-page">
  <div class="login-card glass">
    <div class="brand" style="text-align:center">
      <img src="assets/omsorg-wordmark-new.png" alt="OMSORG" style="width:210px;margin:0 auto 22px">
    </div>

    <h2 style="font-family:'KindelSerif',Georgia,serif;font-size:1.7rem;margin:0 0 6px">Mitarbeiter-App</h2>
    <p class="hint" style="margin:0 0 22px">Melde dich mit deinem Benutzerkonto an.</p>

    <?php if ($error): ?>
      <div class="error" style="margin-bottom:16px"><?= e($error) ?></div>
    <?php elseif (isset($_GET['pwchanged'])): ?>
      <div class="success" style="margin-bottom:16px">Passwort geändert. Bitte melde dich mit deinem neuen Passwort an.</div>
    <?php endif; ?>

    <form method="post">
      <?= csrf_field() ?>
      <label>
        Benutzername
        <input type="text" name="username" autocomplete="username" required autofocus
               value="<?= e($_POST['username'] ?? '') ?>">
      </label>
      <label>
        Passwort
        <input type="password" name="password" autocomplete="current-password" required>
      </label>
      <button type="submit" class="btn" style="width:100%;margin-top:6px">Anmelden</button>
    </form>

    <p class="hint" style="text-align:center;margin-top:14px">
      <a href="pages/forgot-password.php">Passwort vergessen?</a>
    </p>
  </div>
</div>

<script>
if ('serviceWorker' in navigator) navigator.serviceWorker.register('service-worker.js');
</script>
</body>
</html>
