<?php
require_once "../base.php";
session_start();
if(!isset($_SESSION["bootstrapAdmin"])){
    if(!isset($_SESSION["userId"]))header("Location: ../login.php");
    if(!isAdmin($_SESSION["userId"])){
        http_response_code(403);
        print("Forbidden, you don't have access to this resource.");
        exit;
    }
}
head("Add user");
nav();
?>
<div>
<h1>Users</h1>
<?php if(!isset($_SESSION["bootstrapAdmin"])): ?>
<p>Creating your user. This will be used to log in into the system. Your first user must be an admin user.</p>
<?php endif;
require "../db.php";
if($_SERVER["REQUEST_METHOD"]==="POST"){
    $username    = $_POST['username'];
    $displayName = $_POST['displayName'];
    $password    = password_hash($_POST['password'], PASSWORD_BCRYPT);
    $person      = $_POST['person'];
    $isAdmin     = isset($_POST['isAdmin']) ? 1 : 0;

    if(isset($_SESSION["bootstrapAdmin"])){
	    $isAdmin=1;
    }

    $stmt=$pdo->prepare("INSERT INTO users (username, displayName, password, person, isAdmin) VALUES (?,?,?,?,?)");
    $stmt->execute([$username, $displayName, $password, $person, $isAdmin]);
    if(!isset($_SESSION["bootstrapAdmin"])){
        header("Location: ./");
    } else {
	    $_SESSION["personId"]=$person;
        $stmt=$pdo->prepare("SELECT id FROM warehouse LIMIT 1");
        $stmt->execute();
        if($stmt->rowCount()==0){
            header("Location: /storage/warehouse/add.php");
        } else {
            header("Location: /storage/logout.php");
        }
    }
    exit;
}
?>
<form method="POST">
<table class="table table-striped table-sm">
    <thead>
        <tr>
            <td>username</td>
            <td>display name</td>
            <td>password</td>
            <td>person</td>
            <td>admin</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="text" name="username"></td>
            <td><input type="text" name="displayName"></td>
            <td><input type="password" name="password"></td>
            <td>
                <select name="person">
                    <?php
                        $stmt=$pdo->prepare("SELECT id, name, surname FROM people");
                        $stmt->execute([]);
                        while($row=$stmt->fetch()): ?>
                            <option value="<?= $row['id'] ?>"><?= $row['name'].' '.$row['surname'] ?></option>
                        <?php endwhile; ?>
                </select>
            </td>
	    <td><input type="checkbox" name="isAdmin" <?= isset($_SESSION["bootstrapAdmin"])?"checked disabled":"" ?>></td>
        </tr>
    </tbody>
</table>
<input type="submit" value="Add" class="btn btn-success">
</form>
</div>
<?php
footer();
?>
