<?php
session_start();
require "../db.php";

if(!isset($_SESSION["personId"])) {
    header("Location: /storage/login.php");
    exit;
}

$id = $_GET['id'] ?? null;
if(!$id){
    header("Location: ../");
    exit;
}

/* check ownership */
$stmt = $pdo->prepare("SELECT * FROM item WHERE id=?;");
$stmt->execute([$id]);
$item = $stmt->fetch();

if(!$item || $item['owner'] != $_SESSION["personId"]){
    die("You are not allowed to lend this item.");
}

/* handle form */
if($_SERVER['REQUEST_METHOD'] === "POST"){
    $loanerId = $_POST["loaner"];

    $stmt = $pdo->prepare("
        INSERT INTO loans (itemId, loanerId, timeLoaned)
        VALUES (?, ?, CURRENT_DATE())
    ");
    $stmt->execute([$id, $loanerId]);

    header("Location: view.php?id=".$id);
    exit;
}

require_once "../base.php";
head("Lend item");
nav();
?>

<div>
<h1>Lend item: <?= htmlspecialchars($item['name']) ?></h1>

<form method="POST">
    <table class="table table-striped table-sm">
        <thead>
            <tr>
                <td>Loan to</td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>
                    <select name="loaner" required>
                        <?php 
                        $stmt2=$pdo->prepare("SELECT * FROM people WHERE id != ?");
                        $stmt2->execute([$_SESSION['personId']]);
                        while($row2=$stmt2->fetch()): ?>
                            <option value="<?= $row2['id'] ?>"><?= $row2['name'].' '.$row2['surname'] ?></option>
                        <?php endwhile; ?>
                    </select>
                </td>
            </tr>
        </tbody>
    </table>

    <a class="btn btn-danger" href="view.php?id=<?= $id ?>">Cancel</a>
    <input type="submit" class="btn btn-success" value="Lend">
</form>

<?php
footer();
?>
