<?php
    session_start();
    include("../scripts/connection.php");
    include("../scripts/functions.php");
    $user_data = check_admin($con);
    $error = null;

    if($_SERVER['REQUEST_METHOD'] == "POST") {
        $user_name = sanitize_input($_POST['user_name']);
        $password = sanitize_input($_POST['password']);
        $user_group = sanitize_input($_POST['user_group']);
        $bind_station = sanitize_input($_POST['bind_station']);
        if(!empty($user_name) && !empty($password)) {
            $salt = generate_salt();
            $user_id = generate_user_id($user_name, $salt);
            $phash = generate_password_hash($password, $salt);
            if($user_group == "station") {
                write_user($con, $user_name, $user_id, $phash, $salt, $user_group, $bind_station);
            } else {
                write_user($con, $user_name, $user_id, $phash, $salt, $user_group, NULL);
            }
            header("Location: manage_user.php");
            die;
        } else {
            $error = "Bitte Benutzername und Passwort eintragen!";
        }
    }

    include("header_footer/header.php");
?>

<body>
    <div class="center">
        <div class="headline">
            <h2>Benutzer hinzufügen</h2>
        </div>
        <div class="form_div">
            <form method="post" class="form_class">
                <label><?php echo $error ?></label><br>
                <div class="txt_field">
                    <input type="text" name="user_name" required>
                    <span></span>
                    <label>Benutzername</label>
                </div>
                <div class="txt_field">
                    <input type="password" name="password" required>
                    <span></span>
                    <label>Passwort</label>
                </div>
                <div class="dropdown">
                    <label for="user_group">Benutzergruppe</label>
                    <select name="user_group" id="user_group">
                        <option value="station">Station</option>
                        <option value="statistics">Statistik</option>
                        <option value="admin">Administrator</option>
                    </select>
                </div>
                <div class="dropdown">
                    <label for="bind_station">Gebunden an Station (Nur für Gruppe Station)</label>
                    <select name="bind_station" id="bind_station">
                        <?php
                            load_options_stations($con, "", false);
                        ?>
                    </select> 
                </div>
                <input type="submit" value="Hinzufügen" class="btn-confirm"/>
                <a href="manage_user.php">Schließen</a>
            </form>
        </div>
    </div>
</body>

<?php
    $con = null;
    echo file_get_contents("header_footer/footer.html");
?>