<?php
// Include config file
$config = parse_ini_file("/var/www/config/veroConfig.ini", true);
$sessionSavePath = $config['session']['sessionPath'];
$baseURL = $config['base']['URL']; 

// Initialize the session
session_start();

require_once "sanitize.php";
include "config.php"; 

// ========== HONEYPOT CONFIGURATION ==========
$HONEYPOT_FIELD = 'hp_field';
$TIME_FIELD = 'hp_time';
$MIN_SUBMISSION_TIME = 3; // Mindestzeit in Sekunden
$MAX_SUBMISSION_TIME = 3600; // Maximalzeit in Sekunden (1 Stunde)
$LOG_FILE = 'honeypot_log.txt';

/**
 * Generiert versteckte Honeypot-Felder für Formulare
 */
function honeypot_generate_fields($honeypot_field, $time_field) {
    $timestamp = time();
    $html = '';
    
    // Verstecktes Feld für Bots (sollte leer bleiben)
    $html .= '<div style="position: absolute; left: -9999px; top: -9999px;">';
    $html .= '<input type="text" name="' . htmlspecialchars($honeypot_field) . '" value="" tabindex="-1" autocomplete="off">';
    $html .= '</div>';
    
    // Zeitstempel-Feld
    $html .= '<input type="hidden" name="' . htmlspecialchars($time_field) . '" value="' . $timestamp . '">';
    
    return $html;
}

/**
 * Überprüft, ob die Submission ein Bot ist
 */
function honeypot_is_bot($honeypot_field, $time_field, $min_time, $max_time) {
    $reasons = array();
    
    // 1. Honeypot-Feld-Check
    if (!empty($_POST[$honeypot_field])) {
        $reasons[] = 'Honeypot field filled';
    }
    
    // 2. Zeitbasierte Überprüfung
    if (isset($_POST[$time_field])) {
        $submission_time = time() - (int)$_POST[$time_field];
        
        if ($submission_time < $min_time) {
            $reasons[] = 'Submission too fast (' . $submission_time . 's)';
        }
        
        if ($submission_time > $max_time) {
            $reasons[] = 'Submission too slow (' . $submission_time . 's)';
        }
    } else {
        $reasons[] = 'Missing timestamp';
    }
    
    // 3. User-Agent-Check
    if (empty($_SERVER['HTTP_USER_AGENT'])) {
        $reasons[] = 'Missing User-Agent';
    }
    
    // 4. Referer-Check (optional)
    if (empty($_SERVER['HTTP_REFERER']) && isset($_POST['submit'])) {
        $reasons[] = 'Missing Referer';
    }
    
    // 5. Verdächtige User-Agents
    $suspicious_agents = array('bot', 'crawler', 'spider', 'scraper', 'curl', 'wget');
    $user_agent = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');
    
    foreach ($suspicious_agents as $agent) {
        if (strpos($user_agent, $agent) !== false) {
            $reasons[] = 'Suspicious User-Agent: ' . $agent;
            break;
        }
    }
    
    if (!empty($reasons)) {
        honeypot_log_bot($reasons);
        return true;
    }
    
    return false;
}

/**
 * Protokolliert Bot-Versuche
 */
function honeypot_log_bot($reasons) {
    global $LOG_FILE;
    
    $log_entry = array(
        'timestamp' => date('Y-m-d H:i:s'),
        'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
        'reasons' => $reasons,
        'post_data' => $_POST
    );
    
    $log_line = json_encode($log_entry) . "\n";
    file_put_contents($LOG_FILE, $log_line, FILE_APPEND | LOCK_EX);
}

/**
 * Blockiert Bot-Anfragen
 */
function honeypot_block_bot() {
    http_response_code(403);
    die('Access Denied');
}

/**
 * Erweiterte Bot-Erkennung basierend auf Verhalten
 */
function honeypot_advanced_detection() {
    $score = 0;
    
    // JavaScript-Check
    if (!isset($_POST['js_enabled']) || $_POST['js_enabled'] !== '1') {
        $score += 2;
    }
    
    // Formular-Interaktion-Check
    if (!isset($_POST['form_interactions']) || (int)$_POST['form_interactions'] < 1) {
        $score += 1;
    }
    
    // Maus-Bewegung-Check
    if (!isset($_POST['mouse_moved']) || $_POST['mouse_moved'] !== '1') {
        $score += 1;
    }
    
    // Rate Limiting Check
    $ip = $_SERVER['REMOTE_ADDR'] ?? '';
    $rate_limit_file = 'rate_limit_' . md5($ip) . '.txt';
    
    if (file_exists($rate_limit_file)) {
        $last_submission = (int)file_get_contents($rate_limit_file);
        if (time() - $last_submission < 10) { // 10 Sekunden zwischen Submissions
            $score += 3;
        }
    }
    
    file_put_contents($rate_limit_file, time());
    
    return $score >= 3; // Threshold für Bot-Erkennung
}

/**
 * Validiert alle Honeypot-Checks
 */
function honeypot_validate($honeypot_field, $time_field, $min_time, $max_time) {
    return honeypot_is_bot($honeypot_field, $time_field, $min_time, $max_time) || 
           honeypot_advanced_detection();
}

// ========== FORM PROCESSING ==========

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){

    // ========== HONEYPOT VALIDATION FIRST ==========
    if (honeypot_validate($HONEYPOT_FIELD, $TIME_FIELD, $MIN_SUBMISSION_TIME, $MAX_SUBMISSION_TIME)) {
        honeypot_block_bot();
    }

    $email_err = '';
    if (!empty(trim($_POST["email"])))  {
	    include ("checkDisposableMails.php");
    }

    // Validate email
    if (empty(trim($_POST["email"])))  {
        $email_err = "Bitte E-Mail-Adresse eingeben.";
    }
    
    if (!empty(trim($_POST["email"])))  {
	if (validate_email_form(trim($_POST["email"])) === false) {
		$email_err = "Domain der E-Mail-Adresse wird als nicht vertrauenswürdig eingestuft";
		// echo $email_err ."\n"; exit;
	}
	if (empty($email_err)) {
        	if (!preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['email'])){
        		$email_err .= "E-Mail-Adresse enthält ungültige Zeichen";
		}
	}

	if (empty($email_err)) {
        	// Prepare a select statement
        	$sql = "SELECT userId FROM User WHERE userEmail = ?";
        	if($stmt = mysqli_prepare($link, $sql)){
        		// Bind variables to the prepared statement as parameters
        		mysqli_stmt_bind_param($stmt, "s", $email);
        		// Set parameters
        		$email = trim($_POST["email"]);
        		// Attempt to execute the prepared statement
        		if(mysqli_stmt_execute($stmt)){
        			/* store result */
        			mysqli_stmt_store_result($stmt);
        			if (mysqli_stmt_num_rows($stmt) >= 1){
               				$email_err .= 'Ein Publikationskonto für diese E-Mail-Adresse existiert bereits.<p><a href="forgotten.php">Passwort zurücksetzen</a>.</p>';
               			} else {
               				$email = trim($_POST["email"]);
               				$email_err = '';			    			
               			}
       			} else {
               			echo "Oops! Da ist etwas schief gegangen. Bitte versuchen Sie es später noch einmal.";
            		}
		}
	
            	// Close statement
            	mysqli_stmt_close($stmt);
        }
    }
    
    // Validate password 		
    if(empty(trim($_POST["password"]))){
        $password_err = "Bitte Passwort eingeben.";
    } else {
        $password_err = ''; 
        $password = trim($_POST["password"]);
    }

    if (empty($password_err)) {
        $pattern = '~^(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+\-=\[\]{}|;\':\\",./<>?])(?=.*\S).{8,}$~u';
        if  (!preg_match($pattern, trim($_POST["password"]))) {
            $password_err = "Passwort muss mindestens acht Zeichen lang sein, wenigstens aus einem Groß- und Kleinbuchstaben sowie einem Sonderzeichen bestehen.";
        }
    }

    // Validate confirm password
    if(empty(trim($_POST["confirm_password"]))){
        $confirm_password_err = "Bitte Passwort bestätigen.";
    } else {
        $confirm_password = trim($_POST["confirm_password"]);
        if(empty($password_err) && strcmp($password, $confirm_password) !=0) {
            $confirm_password_err = "Passworte stimmen nicht überein.";
        } else {
            $confirm_password = trim($_POST["confirm_password"]); 
            $confirm_password_err = ''; 
        }
    }

    // Check illegal characters in lastname and firstname
    if (empty(trim($_POST["lastname"])))  {
        $lastname_err = "Bitte Nachname eingeben.";
    } elseif (! mb_check_encoding($_POST['lastname'], 'UTF-8')) {
        $lastname_err = "Name enthält ungültige Zeichen";
    } else {
        $lastname = trim($_POST["lastname"]);
        $lastname_err = ''; 	
    } 

    if (empty(trim($_POST["firstname"])))  {
        $firstname_err = "Bitte Vorname eingeben.";
    } elseif (! mb_check_encoding($_POST['firstname'], 'UTF-8')) {
        $firstname_err = "Vorname enthält ungültige Zeichen";
    } else {
        $firstname = trim($_POST["firstname"]);
        $firstname_err = '';         	
    }
        
    if(empty($email_err) &&  empty($password_err) && empty($confirm_password_err) && empty($lastname_err) && empty($firstname_err) && isset($_POST['confirmation'])){
        $showRegisterButton=''; 
    } else {
        $showRegisterButton='disabled';
    }
    
    if(empty($email_err) &&  empty($password_err) && empty($confirm_password_err) && empty($lastname_err) && empty($firstname_err)){

        $timestamp = time(); 
        $timestamp = date("Y-m-d H:i:s", $timestamp);
        $passwordEncrypted = password_hash($password, PASSWORD_DEFAULT);   
        $userToken = bin2hex(random_bytes(32)); 
        $query  = "INSERT INTO User (userId, userPassword, userTitle, userLastName, userFirstName, userEmail, userStatus, userLastActivity, userToken) ";
        $query .= "VALUES (NULL, '" .$passwordEncrypted ."', '" .$title ."', '" .$lastname ."', '" .$firstname ."', '" .$email ."',99, " ."'" .$timestamp  ."', '" .$userToken ."')" ;
        if (mysqli_query($link, $query)) {
            // store variables in Session
            $_SESSION["loggedin"] 	= false;
            $_SESSION["title"] 	= $title;
            $_SESSION["firstname"]  = $firstname;
            $_SESSION["lastname"]   = $lastname;
            $_SESSION["email"]      = $email;
            $_SESSION["userToken"]   = $userToken; 
            header("location: sendconfirmationmail.php");
            exit;
        } else {
            die ("Error: " . $query . "-" . mysqli_error($link));
        }
        header("location: sendconfirmationmail.php");
        exit;
    } 
    // Close connection
    mysqli_close($link);
}
?>
 
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Registrierung</title>

    <!-- Bootstrap 5 CSS && Bootstrap Icons -->
    <?php include "include/includeJSandCSS.php" ?> 

    <!-- Custom CSS -->
    <link href="css/bibb.css" media="all" rel="stylesheet" type="text/css">

    <style>
        html, body {
            height: 100%;
        }

        .stickywrapper {
            min-height: 60vh;
            display: flex;
            flex-direction: column;
        }

        .content {
            flex: 1;
        }

        .togglePassword {
	    background-color: white;
            border-top-right-radius: 0.375rem !important;
            border-bottom-right-radius: 0.375rem !important;
        }
    </style>

</head>

<body>
    
<?php include "templates/headerLogin.php"; ?>
<div class="stickywrapper">
    <!-- Hauptinhalt der Seite -->
    <div class="content">
        <div class="container my-5">
            <div id="registrationScreen" class="wrapper pb-3 shadow p-3 ms-5 bg-light rounded align-items-center bg-box">
                <h4>Registrierung</h4>
                <div class="row">Bitte ausfüllen, um ein Publikationskonto für das VET Repository anzulegen.</div>
                <div class="pb-3">Konto bereits vorhanden? Zum <a href="login.php" style="color:#14416b;">Login</a>.</div>
                <div class="row"></div>

                <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" novalidate>
                    
                    <!-- ========== HONEYPOT FIELDS ========== -->
                    <?php echo honeypot_generate_fields($HONEYPOT_FIELD, $TIME_FIELD); ?>
                    
                    <!-- Hidden fields for advanced bot detection -->
                    <input type="hidden" name="js_enabled" id="js_enabled" value="0">
                    <input type="hidden" name="form_interactions" id="form_interactions" value="0">
                    <input type="hidden" name="mouse_moved" id="mouse_moved" value="0">
                    
                    <div class="mb-3">
                        <label for="email" class="form-label">E-Mail</label>
                        <input type="email" name="email" id="email" class="form-control <?php echo (!empty($email_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $email; ?>">
                        <div class="invalid-feedback"><?php echo $email_err; ?></div>
                    </div>

                    <div class="mb-3">
                        <label for="password" class="form-label">Passwort</label>
			<div class="input-group">
                        	<input type="password" name="password" id="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $password; ?>">
                        	<button class="btn btn-outline-secondary togglePassword" type="button" id="togglePassword">
                                       	<i class="bi bi-eye" id="eyeIcon"></i>
                        	</button>
                        	<div class="invalid-feedback"><?php echo $password_err; ?></div>
			</div>
                    </div>

                    <div class="mb-3">
                        <label for="confirm_password" class="form-label">Passwort bestätigen</label>
			<div class="input-group">
                        	<input type="password" name="confirm_password" id="confirm_password" class="form-control <?php echo (!empty($confirm_password_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $confirm_password; ?>">
				<button class="btn btn-outline-secondary togglePassword" type="button" id="toggleConfirmPassword">
                                        <i class="bi bi-eye" id="eyeConfirmIcon"></i>
                                </button>
                        <div class="invalid-feedback"><?php echo $confirm_password_err; ?></div>
                    </div>

                    <div class="mb-3">
                        <label for="firstname" class="form-label">Vorname</label>
                        <input type="text" name="firstname" id="firstname" class="form-control <?php echo (!empty($firstname_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $firstname; ?>">
                        <div class="invalid-feedback"><?php echo $firstname_err; ?></div>
                    </div>

                    <div class="mb-3">
                        <label for="lastname" class="form-label">Name</label>
                        <input type="text" name="lastname" id="lastname" class="form-control <?php echo (!empty($lastname_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $lastname; ?>">
                        <div class="invalid-feedback"><?php echo $lastname_err; ?></div>
                    </div>

                    <div class="row">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="confirm" name="confirmation" onclick="check_submitbox()">
                            <label class="form-check-label" for="confirm">
                                <span style="font-weight:bold">Datenschutz Publikationskonto: </span>
                            </label>
                            <p class="mt-2">Ich willige ein, dass meine hier erhobenen personenbezogenen Daten für das Anlegen eines Publikationskontos für das VET Repository verarbeitet und gespeichert werden dürfen. Die Einwilligung kann jederzeit ohne Angabe von Gründen von mir widerrufen werden. Das Publikationskonto wird dann vom BIBB gelöscht. Das <a href="https://www.bibb.de/dokumente/pdf/DSGVO_Informationsschreiben_VET_Repository.pdf" target="_blank" rel="noopener noreferrer"><span style="font-weight:bold">DSGVO-Informationsschreiben</span></a> habe ich zur Kenntnis genommen.</p>
                        </div>
                    </div>

                    <div class="row"></div>
                    <div class="mb-3">
                        <input type="submit" id="submitregister" class="btn btn-success" disabled value="Registrieren">
                    </div>
                </form>
            </div>
        </div>    
    </div>
</div>

<?php include "templates/stickyfooter.php" ?>

<script>
// ========== HONEYPOT JAVASCRIPT ==========
let formInteractions = 0;
let mouseMoved = false;

// JavaScript aktiviert setzen
document.getElementById('js_enabled').value = '1';

// Formular-Interaktionen zählen
document.querySelectorAll('input, select, textarea').forEach(element => {
    element.addEventListener('focus', function() {
        formInteractions++;
        document.getElementById('form_interactions').value = formInteractions;
    });
    
    element.addEventListener('change', function() {
        formInteractions++;
        document.getElementById('form_interactions').value = formInteractions;
    });
});

// Mausbewegungen verfolgen
document.addEventListener('mousemove', function() {
    if (!mouseMoved) {
        mouseMoved = true;
        document.getElementById('mouse_moved').value = '1';
    }
});

// Ursprüngliche Funktion
function check_submitbox() {
    if (document.getElementById("confirm").checked == true) {
        document.getElementById("submitregister").disabled = false;
    } else {
        document.getElementById("submitregister").disabled = true; 
    }
}
</script>

<script>
        const togglePassword = document.getElementById('togglePassword');
        const password = document.getElementById('password');
        const eyeIcon = document.getElementById('eyeIcon');

        togglePassword.addEventListener('click', function() {
            // Typ des Passwortfeldes umschalten
            const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
            password.setAttribute('type', type);
            
            // Icon umschalten
            if (type === 'password') {
                eyeIcon.classList.remove('bi-eye-slash');
                eyeIcon.classList.add('bi-eye');
            } else {
                eyeIcon.classList.remove('bi-eye');
                eyeIcon.classList.add('bi-eye-slash');
            }
        });
</script>

<script>
        const toggleConfirmPassword = document.getElementById('toggleConfirmPassword');
        const confirm_password = document.getElementById('confirm_password');
        const eyeConfirmIcon = document.getElementById('eyeConfirmIcon');

        toggleConfirmPassword.addEventListener('click', function() {
            // Typ des Passwortfeldes umschalten
            const typeConfirm = confirm_password.getAttribute('type') === 'password' ? 'text' : 'password';
            confirm_password.setAttribute('type', typeConfirm);

            // Icon umschalten
            if (type === 'password') {
                eyeConfirmIcon.classList.remove('bi-eye-slash');
                eyeConfirmIcon.classList.add('bi-eye');
            } else {
                eyeConfirmIcon.classList.remove('bi-eye');
                eyeConfirmIcon.classList.add('bi-eye-slash');
            }
        });
</script>



</body>
</html>
