<?php
require __DIR__ . '/auth.php';

$config = require __DIR__ . '/config.php';

$error = '';

// 🔁 Redirect bestimmen
$redirect = $_GET['redirect'] ?? $_POST['redirect'] ?? ($config['BASE_URL'] . '/admin/dashboard.php');

// Sicherheit: nur interne URLs erlauben
if (!str_starts_with($redirect, '/')) {
    $redirect = $config['BASE_URL'] . '/admin/dashboard.php';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $user = trim($_POST['username'] ?? '');
    $pass = $_POST['password'] ?? '';

    $st = db()->prepare("SELECT * FROM users WHERE username = ?");
    $st->execute([$user]);
    $row = $st->fetch(PDO::FETCH_ASSOC);

    if ($row && password_verify($pass, $row['password'])) {

        $_SESSION['admin'] = true;

        // ✅ ABSOLUTER REDIRECT
        header('Location: ' . $redirect);
        exit;
    }

    $error = 'Login fehlgeschlagen';
}
?>
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CMS Login</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">

<div class="container d-flex justify-content-center align-items-center" style="min-height:100vh">
  <form method="post" class="card p-4 shadow" style="max-width:360px;width:100%">

    <h4 class="mb-3 text-center">🔐 CMS Login</h4>

    <?php if ($error): ?>
      <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <!-- 🔁 Redirect sichern -->
    <input type="hidden" name="redirect" value="<?= htmlspecialchars($redirect) ?>">

    <div class="mb-3">
      <label class="form-label">Benutzer</label>
      <input name="username" class="form-control" required autofocus>
    </div>

    <div class="mb-3">
      <label class="form-label">Passwort</label>
      <input type="password" name="password" class="form-control" required>
    </div>

    <button class="btn btn-primary w-100">Login</button>
  </form>
</div>

</body>
</html>
