<?php
// admin/bootstrap.php
ob_start(); // fängt zufälligen Output ab, verhindert "headers already sent" Folgeschäden
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once(__DIR__ . "/../inc/config.inc.php");
require_once(__DIR__ . "/../inc/functions.inc.php");

$error_msg = "";

if (!empty($_POST['email']) && !empty($_POST['passwort'])) {
    $email = $_POST['email'];
    $passwort = $_POST['passwort'];

    $statement = $pdo->prepare("SELECT * FROM users WHERE email = :email LIMIT 1");
    $statement->execute(['email' => $email]);
    $user = $statement->fetch(PDO::FETCH_ASSOC);

    if ($user && password_verify($passwort, $user['passwort'])) {

        // Session IMMER setzen
        session_regenerate_id(true);
        $_SESSION['auth'] = [
            'type' => 'admin',
            'id'   => (int)$user['id'],
        ];

        // "Angemeldet bleiben" optional
        if (!empty($_POST['angemeldet_bleiben'])) {
            $identifier = bin2hex(random_bytes(16));
            $securitytoken = bin2hex(random_bytes(32)); // stärker als random_string()

            $hash = hash('sha256', $securitytoken);

            $insert = $pdo->prepare("
                INSERT INTO securitytokens (user_id, identifier, securitytoken, user_type)
                VALUES (:user_id, :identifier, :securitytoken, 'admin')
            ");
            $insert->execute([
                'user_id' => (int)$user['id'],
                'identifier' => $identifier,
                'securitytoken' => $hash
            ]);

            $cookieOpts = [
                'expires'  => time() + 365*24*3600,
                'path'     => '/',
                'secure'   => true,    // nur wenn HTTPS
                'httponly' => true,
                'samesite' => 'Lax',
            ];
            setcookie('identifier', $identifier, $cookieOpts);
            setcookie('securitytoken', $securitytoken, $cookieOpts);
        }

        header("Location: index.php");
        exit;
    } else {
        $error_msg = "E-Mail oder Passwort war ungültig<br><br>";
    }
}

$email_value = isset($_POST['email']) ? htmlentities($_POST['email']) : "";
include("templates/header.inc.php");
?>


 <div class="container small-container-330 form-signin">
  <form action="login.php" method="post">
	<h2 class="form-signin-heading">Login</h2>
	
<?php 
if(isset($error_msg) && !empty($error_msg)) {
	echo $error_msg;
}
?>
	<label for="inputEmail" class="sr-only">E-Mail</label>
	<input type="email" name="email" id="inputEmail" class="form-control" placeholder="E-Mail" value="<?php echo $email_value; ?>" required autofocus>
	<label for="inputPassword" class="sr-only">Passwort</label>
	<input type="password" name="passwort" id="inputPassword" class="form-control" placeholder="Passwort" required>
	<div class="checkbox">
	  <label>
		<input type="checkbox" value="remember-me" name="angemeldet_bleiben" value="1" checked> Angemeldet bleiben
	  </label>
	</div>
	<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
	<br>
	<a href="passwortvergessen.php">Passwort vergessen</a>
  </form>

</div> <!-- /container -->
 

<?php 
include("templates/footer.inc.php")
?>