<?php
if ($_SERVER['REQUEST_METHOD'] === "POST") {
    require "../db.php";
    $itemId   = (int)$_POST['itemId'];
    $newOwner = (int)$_POST['newOwner'];

    // Fetch current owner to log as previousOwner
    $stmt = $pdo->prepare("SELECT owner FROM item WHERE id = ?;");
    $stmt->execute([$itemId]);
    $item = $stmt->fetch();

    if (!$item) {
        die("Item not found.");
    }

    $previousOwner = $item['owner'];

    // Update item: change owner and clear shelf location
    $stmt = $pdo->prepare("UPDATE item SET owner = ?, storageShelf = NULL WHERE id = ?;");
    $stmt->execute([$newOwner, $itemId]);

    // Log the exchange
    $stmt = $pdo->prepare("INSERT INTO exchanges (itemId, previousOwner, newOwner) VALUES (?, ?, ?);");
    $stmt->execute([$itemId, $previousOwner, $newOwner]);

    header("Location: ../");
    exit;
}

require_once "../base.php";
session_start();
if (!isset($_SESSION["userId"])) header("Location: /storage/login.php");
head("Give item");
nav();
require "../db.php";

$itemId = (int)($_GET['id'] ?? 0);
if (!$itemId) die("No item specified.");

$stmt = $pdo->prepare("SELECT item.*, people.name AS ownerName, people.surname AS ownerSurname
                        FROM item
                        LEFT JOIN people ON item.owner = people.id
                        WHERE item.id = ?;");
$stmt->execute([$itemId]);
$item = $stmt->fetch();

if (!$item) die("Item not found.");
?>
<div>
    <h1>Give item</h1>
    <p>
        Giving: <strong><?= htmlspecialchars($item['name']) ?></strong><br>
    </p>
    <form method="POST">
        <input type="hidden" name="itemId" value="<?= $itemId ?>">
        <table class="table table-striped table-sm">
            <thead>
                <tr>
                    <td>New owner</td>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>
                        <select name="newOwner" required>
                            <?php
                            $stmt = $pdo->prepare("SELECT * FROM people WHERE id != ?;");
                            $stmt->execute([$_SESSION['personId']]);
                            while ($row = $stmt->fetch()): ?>
                                <option value="<?= $row['id'] ?>"
                                    <?= $row['id'] == $item['owner'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($row['name'] . ' ' . $row['surname']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </td>
                </tr>
            </tbody>
        </table>
        <p class="text-muted"><small>Note: giving away an item will remove it from its current shelf.</small></p>
        <a class="btn btn-danger" href="view.php?id=<?= $itemId ?>">Cancel</a>
        <input type="submit" class="btn btn-success" value="Give">
    </form>
</div>
<?php
footer();
?>
