<?php
require_once "../base.php";
session_start();
if(!isset($_SESSION["userId"]))header("Location: /storage/login.php");
if(!isAdmin($_SESSION["userId"])){
    http_response_code(403);
    print("Forbidden, you don't have access to this resource.");
    exit;
}
$id = htmlspecialchars($_GET['id']);
require "../db.php";
if($_SERVER["REQUEST_METHOD"]==="POST"){
    $name = htmlspecialchars($_POST['name']);
    $warehouseId = htmlspecialchars($_POST['warehouseId']);
    $stmt=$pdo->prepare("UPDATE shelf SET name=?,warehouseId=? WHERE id=?");
    $stmt->execute([$name,$warehouseId,$id]);
    header("Location: list.php");
} else {
    $stmt=$pdo->prepare("SELECT * FROM shelf WHERE id=?");
    $stmt->execute([$id]);
    if($data=$stmt->fetch()):
    head("Edit shelf");
    nav();
?>
<div>
<h1>Edit shelf</h1>
<form method="POST">
<table class="table table-striped table-sm">
    <thead>
        <tr>
            <td>name</td>
            <td>warehouse</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="text" name="name" value="<?= $data["name"] ?>"></td>
            <td>
                <select name="warehouseId">
                    <?php
                        $stmt2=$pdo->prepare("SELECT id,displayName FROM warehouse");
                        $stmt2->execute([]);
                        while($row2=$stmt2->fetch()): ?>
                            <option value="<?= $row2['id'] ?>" <?= $row2['id']==$data["warehouseId"]?"selected":"" ?>><?= $row2['displayName'] ?></option>
                        <?php endwhile; ?>
                </select>
            </td>
        </tr>
    </tbody>
</table>
<input type="submit" value="Save" class="btn btn-success">
</form>
</div>
<?php
    footer();
    endif;
}
?>