<?php

    #	SonicCampGuard
    #
    #	Copyright (c) 2024 Bundeswehr
    #	Diese Anwendung wurde von Cedric Prietz entwickelt.
    #	E-Mail: CedricPrietz@bundeswehr.org
    #	App: 90-8303-54618
	#
    #	Letzte Änderung: 11.10.2024

	// Funktionen Bereitstellen
	require_once 'function.inc.php';
	showSessionAlert();

	// Überprüfen, ob der Benutzer bereits eingeloggt ist
	if (isset($_SESSION['LoggedIn']) || $_SESSION['LoggedIn'] == true) {
		// Benutzer ist eingeloggt, Weiterleitung zum Dashboard
        header('location: dashboard');
        exit;
    }

	if (isset($_POST['login'])) {
		
		$username = $_POST['username'];
		$password = $_POST['password'];

		// Erlaubte Gruppe
		$allowed_group = 'CampGuard_Nutzer';

		// PDO-Verbindung zur MySQL-Datenbank herstellen
		try {
			initializeDatabaseConnection();
		} catch (PDOException $e) {
			die("Fehler bei der Verbindung zur Datenbank: " . $e->getMessage());
		}

		// Schritt 1: Versuche den Benutzer in der lokalen Datenbank zu finden
		$stmt = $pdo->prepare("SELECT * FROM Accounts WHERE Username = :username AND Type = 'local'");
		$stmt->bindParam(':username', $username);
		$stmt->execute();
		$user = $stmt->fetch(PDO::FETCH_ASSOC);

		if ($user) {
			// Benutzer wurde gefunden, Passwort prüfen
			if (password_verify($password, $user['Password'])) {
				// Passwort korrekt, erfolgreicher Login (lokal)
				$_SESSION['LoggedIn'] = true;
				$_SESSION['ID'] = $user['ID'];
				$_SESSION['DisplayName'] = $user['DisplayName'];
				$_SESSION['Username'] = $user['Username'];
				$_SESSION['Role'] = $user['Role'];
				$_SESSION['Type'] = $user['Type'];

				// LastLogin-Zeitstempel aktualisieren
				$lastLoginTime = date('Y-m-d H:i:s');
				$updateStmt = $pdo->prepare("UPDATE Accounts SET LastLogin = :lastLogin WHERE Username = :username");
				$updateStmt->bindParam(':lastLogin', $lastLoginTime);
				$updateStmt->bindParam(':username', $username);
				$updateStmt->execute();
				
				addAuditLog($_SESSION['Username'], 'Login', 'Erfolgreiche Anmeldung');
				header("location: dashboard");
			} else {
				addAuditLog($username, 'Login', 'Fehlgeschlagener Anmeldeversuch');
				$LoginMessage = "
				<script>
					Swal.fire({
						text: 'Die Zugangsdaten sind nicht korrekt!',
						icon: 'warning',
						confirmButtonText: 'OK'
					});
				</script>
				";
			}
		} else {

			// Schritt 2: Wenn kein lokaler Benutzer gefunden, versuche LDAP Login
			// LDAP-Verbindung herstellen
			
			// Connect to LDAP server
			$ldap_conn = ldap_connect($ldap_config['host'], $ldap_config['port']);
			if (!$ldap_conn) {
				createSessionAlert("","Es konnte keine Verbindung zum LDAP-Server hergestellt werden","error", "false", "2000");
				header('Location: login');
			}

			// Set LDAP options
			ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
			ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);

			// Bind to LDAP directory as an admin
			$bind = ldap_bind($ldap_conn, $ldap_config['bind_dn'], $ldap_config['bind_pass']);
			if (!$bind) {
				createSessionAlert("","Die LDAP-Bindung ist fehlgeschlagen","error", "false", "2000");
				header('Location: login');
			}

			// Search for the user in LDAP
			$search_filter = "(sAMAccountName=" . ldap_escape($username, "", LDAP_ESCAPE_FILTER) . ")";
			$search = ldap_search($ldap_conn, $ldap_config['base_dn'], $search_filter);

			if (!$search) {
				createSessionAlert("","Die LDAP-Suche ist fehlgeschlagen","error", "false", "2000");
				header('Location: login');
			}

			$entries = ldap_get_entries($ldap_conn, $search);

			if ($entries["count"] == 0) {
				createSessionAlert("","Benutzer nicht gefunden","warning", "false", "2000");
				header('Location: login');
			}

			$user_dn = $entries[0]["dn"];
			$displayname = $entries[0]['displayname'][0]; // Anzeigename aus LDAP

			// Attempt to bind as the user to verify the password
			$user_bind = ldap_bind($ldap_conn, $user_dn, $password);

			if ($user_bind) {
				// Check if the user is a member of the "CampGuard_Nutzer" group
				if (isset($entries[0]['memberof'])) {
					$memberof = $entries[0]['memberof'];

					$is_member = false;
					// Durchsuche die Gruppenmitgliedschaften
					foreach ($memberof as $group_dn) {
						if ($group_dn === $ldap_config['required_group']) {
							$is_member = true;
							break;
						}
					}

					if ($is_member) {
						// Schritt 4: Überprüfen, ob der Benutzer bereits in der Datenbank existiert (Type "ldap")
						$stmt = $pdo->prepare("SELECT * FROM Accounts WHERE Username = :username AND Type = 'ldap'");
						$stmt->bindParam(':username', $username);
						$stmt->execute();
						$ldap_user = $stmt->fetch(PDO::FETCH_ASSOC);

						if (!$ldap_user) {
							// Benutzer existiert noch nicht in der Datenbank, also einfügen
							$stmt = $pdo->prepare("INSERT INTO Accounts (Username, Password, Type, Role, DisplayName, LastLogin) VALUES (:username, '', 'ldap', 'Bediener', :displayname, CURRENT_TIMESTAMP)");
							$stmt->bindParam(':username', $username);
							$stmt->bindParam(':displayname', $displayname);
							$stmt->execute();

							// Setze die Session-Variablen
							$_SESSION['LoggedIn'] = true;
							$_SESSION['DisplayName'] = $displayname;
							$_SESSION['Username'] = $username;
							$_SESSION['Role'] = 'Bediener';
							$_SESSION['Type'] = 'ldap';
							
							// Protokolliere
							addAuditLog("System", 'Benutzerkonto', 'Der Benutzer '.$username.' wurde durch einen Domänenlogin hinzugefügt');
						} else {
							// Benutzer existiert, aktualisiere DisplayName und LastLogin
							$stmt = $pdo->prepare("UPDATE Accounts SET DisplayName = :displayname, LastLogin = CURRENT_TIMESTAMP WHERE Username = :username AND Type = 'ldap'");
							$stmt->bindParam(':displayname', $displayname);
							$stmt->bindParam(':username', $username);
							$stmt->execute();

							// Setze die Session-Variablen
							$_SESSION['LoggedIn'] = true;
							$_SESSION['ID'] = $ldap_user['ID'];
							$_SESSION['DisplayName'] = $displayname;
							$_SESSION['Username'] = $username;
							$_SESSION['Role'] = $ldap_user['Role'];
							$_SESSION['Type'] = $ldap_user['Type'];
							
							// Protokolliere
							addAuditLog($username, 'Login', 'Erfolgreiche Anmeldung');
						}

						// Login erfolgreich
						header("location: dashboard");
					} else {
						createSessionAlert("","Der Benutzer ist kein Mitglied der Berechtigungsgruppe","warning", "false", "2000");
						header('Location: login');
					}
				} else {
					createSessionAlert("","Benutzer hat keine Gruppen","warning", "false", "2000");
					header('Location: login');
				}
			} else {
				createSessionAlert("","Benutzername oder Passwort falsch","warning", "false", "2000");
				header('Location: login');
			}

			// Close LDAP connection
			ldap_unbind($ldap_conn);
		}
	}
?>

<!DOCTYPE html>
<html lang="de">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>SONICCG - Anmelden</title>

	<script src="/assets/vendors/sweetalert2/sweetalert2.min.js"></script>
	<link rel="stylesheet" href="/assets/vendors/sweetalert2/sweetalert2.min.css">

	<link rel="preconnect" href="https://fonts.googleapis.com/">
	<link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
	<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700;900&amp;display=swap" rel="stylesheet">

	<link rel="stylesheet" href="/assets/vendors/core/core.css">
	<link rel="stylesheet" href="/assets/fonts/feather-font/css/iconfont.css">
	<link rel="stylesheet" href="/assets/vendors/mdi/css/materialdesignicons.min.css">
	<link rel="stylesheet" href="/assets/css/style.css">
  	
	<link rel="shortcut icon" href="/assets/images/favicon.ico" />

</head>
<body class="navbar-dark login">
	<div class="main-wrapper">
		<div class="page-wrapper full-page">
			<div class="page-content d-flex align-items-center justify-content-center">

				<div class="row w-100 mx-0 auth-page">
					<div class="col-md-10 col-lg-8 col-xl-4 mx-auto">
					<?php echo $LoginMessage; ?>
						<div class="card">
							<div class="row">
                <div class="col-md-4 pe-md-0">
                  <div class="auth-side-wrapper">

                  </div>
                </div>
								<div class="col-md-8 ps-md-0">
								<div class="auth-form-wrapper px-4 py-4">
									<span class="nobleui-logo d-block mb-3">SONIC<span>CG</span></span>
									<form class="forms-sample" method="POST">
									<div class="mb-3">
										<label for="campguard_username" class="form-label">Benutzername</label>
										<input type="text" class="form-control" id="campguard_username" name="username" placeholder="Benutzername" value="<?php echo $_POST['username']; ?>" autofocus required>
									</div>
									<div class="mb-3">
										<label for="campguard_password" class="form-label">Passwort</label>
										<input type="password" class="form-control" id="campguard_password" name="password" autocomplete="current-password" placeholder="Passwort" required>
									</div>
									<div>
										<button type="submit" name="login" class="btn btn-primary btn-icon-text me-2 mb-2 mb-md-0 text-white">
											Anmelden
											<i class="btn-icon-append mdi mdi-login"></i>
										</button>
									</div>
									</form>
								</div>
								</div>
							</div>
						</div>
							<div class="text-center p-2">
								<span class="btn btn-link" data-bs-toggle="modal" data-bs-target="#modalImpressum">Impressum</span>
							</div>
					</div>
				</div>

			</div>
		</div>
	</div>

	<!-- core:js -->
	<script src="/assets/vendors/core/core.js"></script>
	<!-- endinject -->

	<!-- Plugin js for this page -->
	
	<!-- End plugin js for this page -->

	<!-- inject:js -->
	<script src="/assets/vendors/feather-icons/feather.min.js"></script>
	<script src="/assets/js/app.js"></script>
	<!-- endinject -->

</body>
</html>

<!-- Modal: Impressum -->
<div class="modal fade" id="modalImpressum" tabindex="-1" aria-labelledby="modalImpressumLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modalImpressumLabel">Impressum</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="btn-close"></button>
      </div>
      <div class="modal-body">
			<div class="text-center">
				<img width="250px" src="/assets/images/logo-bw.png">
			</div>
			<table class="table">
				<tr>
					<td>Entwickler</td>
					<td>Cedric Prietz</td>
				</tr>
				<tr>
					<td>E-Mail</td>
					<td>CedricPrietz@bundeswehr.org</td>
				</tr>
				<tr>
					<td>Telefon</td>
					<td>90-8303-54618</td>
				</tr>
				<tr>
					<td>App-Version</td>
					<td style="font-weight: bold;"><?php $app = json_decode(file_get_contents('app.json'), true); echo $app['version']; ?></td>
				</tr>
			</table>
      </div>
    </div>
  </div>
</div>