<?php
require_once "../base.php";
session_start();
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;
}
$id = $_GET['id'];
require "../db.php";
if($_SERVER["REQUEST_METHOD"]==="POST"){
    $username    = $_POST['username'];
    $displayName = $_POST['displayName'];
    $person      = $_POST['person'];
    $isAdmin     = isset($_POST['isAdmin']) ? 1 : 0;

    if(!empty($_POST['password'])){
        $password = password_hash($_POST['password'], PASSWORD_BCRYPT);
        $stmt=$pdo->prepare("UPDATE users SET username=?, displayName=?, password=?, person=?, isAdmin=? WHERE id=?");
        $stmt->execute([$username, $displayName, $password, $person, $isAdmin, $id]);
    } else {
        $stmt=$pdo->prepare("UPDATE users SET username=?, displayName=?, person=?, isAdmin=? WHERE id=?");
        $stmt->execute([$username, $displayName, $person, $isAdmin, $id]);
    }
    header("Location: ./");
    exit;
} else {
    $stmt=$pdo->prepare("SELECT * FROM users WHERE id=?");
    $stmt->execute([$id]);
    if($data=$stmt->fetch()):
    head("Edit user");
    nav();
?>
<div>
<h1>Edit user</h1>
<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" value="<?= $data['username'] ?>"></td>
            <td><input type="text" name="displayName" value="<?= $data['displayName'] ?>"></td>
            <td><input type="password" name="password" placeholder="Leave blank to keep current"></td>
            <td>
                <select name="person">
                    <?php
                        $stmt2=$pdo->prepare("SELECT id, name, surname FROM people");
                        $stmt2->execute([]);
                        while($row=$stmt2->fetch()): ?>
                            <option value="<?= $row['id'] ?>" <?= $row['id']==$data['person'] ? 'selected' : '' ?>><?= $row['name'].' '.$row['surname'] ?></option>
                        <?php endwhile; ?>
                </select>
            </td>
            <td><input type="checkbox" name="isAdmin" <?= $data['isAdmin'] ? 'checked' : '' ?>></td>
        </tr>
    </tbody>
</table>
<input type="submit" value="Save" class="btn btn-success">
</form>
</div>
<?php
    footer();
    endif;
}
?>