<?php
session_start();
require "../db.php";
header("Allow: GET");
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 l.id, i.id AS itemId, i.owner, l.loanerId FROM loans l LEFT JOIN item i ON i.id=l.itemId WHERE l.id=?;");
$stmt->execute([$id]);
$loan = $stmt->fetch();

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

/* handle form */
if($_SERVER['REQUEST_METHOD'] === "GET"){
    $stmt = $pdo->prepare("UPDATE loans SET timeReturned = CURRENT_DATE() WHERE id=?");
    $stmt->execute([$id]);

    if($loan['owner'] == $_SESSION["personId"]){ 
	    header("Location: view.php?id=".$loan['itemId']);
    } else {
	    header("Location: ../");
    }
    exit;
} 
http_response_code(405);
