<?php 
#error_reporting(E_ALL);
#ini_set('display_errors', 1);
#ini_set('log_errors', 1);
// optional: ini_set('error_log', __DIR__.'/php-error.log');

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

ini_set('session.gc_maxlifetime', 30*24*60*60); //  30 Tage
ini_set('session.cookie_lifetime', 30*24*60*60); // 30 Tage
include(__DIR__ . "/../inc/password.inc.php");

$error_msg = "";

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

    $stmt = $pdo->prepare("SELECT id, passwort, email FROM intern_users WHERE email = :email LIMIT 1");
    $stmt->execute(['email' => $_POST['email']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

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

        session_regenerate_id(true);

        $_SESSION['2fa_userid'] = (int)$user['id'];

        // Alten Code löschen
        $pdo->prepare("DELETE FROM intern_2fa_codes WHERE user_id = :uid")
            ->execute(['uid' => $user['id']]);

        // 2FA-Code
        $code      = random_int(100000, 999999);
        $codeHash = hash('sha256', $code);
        $expires  = date('Y-m-d H:i:s', time() + 300);

        $pdo->prepare("
            INSERT INTO intern_2fa_codes (user_id, code, expires_at)
            VALUES (:uid, :code, :expires)
        ")->execute([
            'uid'     => $user['id'],
            'code'    => $codeHash,
            'expires' => $expires
        ]);

        SendMailMessageSilent(
            $con,
            $user['email'],
            'Ihr Login-Code für Praxis-Creutzburg.de',
            "Ihr 2FA-Code lautet: <b>$code</b><br><br>
             Geben Sie diesen Code niemals weiter."
        );

        header('Location: verify_2fa.php');
        exit;
    }

    $error_msg = "E-Mail oder Passwort war ungültig";
}


$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(!empty($error_msg)) echo $error_msg; ?>
		<label for="inputEmail">E-Mail</label>
		<input type="email" name="email" class="form-control" placeholder="E-Mail" value="<?php echo $email_value; ?>" required>
		<label for="inputPassword">Passwort</label>
		<input type="password" name="passwort" class="form-control" placeholder="Passwort" required>
		<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
	</form>
</div>

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