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

$id = (int)$_GET["id"];
$stmt = $pdo->prepare("SELECT item.*, states.name AS stateName, people.name AS ownerName, people.surname AS ownerSurname, shelf.name AS shelfName, warehouse.displayName AS warehouseName
    FROM item
    LEFT JOIN states ON item.state = states.id
    LEFT JOIN people ON item.owner = people.id
    LEFT JOIN shelf ON item.storageShelf = shelf.id
    LEFT JOIN warehouse ON shelf.warehouseId = warehouse.id
    WHERE item.id = ?;");
$stmt->execute([$id]);
$row = $stmt->fetch();

if(!$row) {
    echo "<div class='alert alert-danger'>Item not found.</div>";
    footer();
    exit;
}

$stmt=$pdo->prepare("SELECT l.id,CONCAT(p.name,' ',p.surname) AS person,l.timeLoaned FROM loans l LEFT JOIN people p ON p.id=l.loanerId WHERE timeReturned IS NULL AND itemId=?");
$stmt->execute([$id]);
$rowLoan=$stmt->fetch();
?>
<div>
<h1>Item details</h1>
<?php if(isset($rowLoan['person'])): ?>
	<span style="color: red;">Item loaned to <i style="color: red"><?= $rowLoan['person'] ?></i></span>
<?php endif; ?>
<table class="table table-striped table-sm">
    <thead>
        <tr>
            <td>Name</td>
            <td>State</td>
            <td>Shelf</td>
            <td>Owner</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><?= htmlspecialchars($row['name']) ?></td>
            <td><?= htmlspecialchars($row['stateName']) ?></td>
            <td>
                <?php if($row['shelfName']): ?>
                    <?= htmlspecialchars($row['warehouseName']) ?> / <?= htmlspecialchars($row['shelfName']) ?>
                <?php else: ?>
                    —
                <?php endif; ?>
            </td>
            <td><?= htmlspecialchars($row['ownerName'].' '.$row['ownerSurname']) ?></td>
        </tr>
    </tbody>
</table>
<div>
    <strong>Description</strong>
    <p><?= nl2br(htmlspecialchars($row['description'] ?? '')) ?: '—' ?></p>
</div>
<a class="btn btn-secondary" href="../">Back</a>
<a class="btn btn-primary" href="modify.php?id=<?= $row['id'] ?>">Modify</a>
<?php if(!isset($rowLoan['person'])): ?>
	<a class="btn btn-warning" href="lend.php?id=<?= $row['id'] ?>">Lend</a>
<?php else: ?>
	<a class="btn btn-warning" href="return.php?id=<?= $rowLoan['id'] ?>">Return</a>
<?php endif; ?>
<a class="btn btn-info" href="move.php?id=<?= $row['id'] ?>">Move</a>
<a class="btn btn-success" href="give.php?id=<?= $row['id'] ?>">Give</a>
<br>
<strong>History</strong>
<?php
$stmt=$pdo->prepare("
SELECT * FROM (
SELECT 
    e.id,
    CONCAT(p1.name, ' ', p1.surname) AS previous,
    CONCAT(p2.name, ' ', p2.surname) AS new,
    e.time,
    e.time AS sort_time,
    'exchange' AS type
FROM exchanges e
JOIN people p1 ON e.previousOwner = p1.id
JOIN people p2 ON e.newOwner = p2.id
WHERE itemId = ?

UNION ALL

SELECT 
    m.id,
    CONCAT(s1.name, ' - ', w1.displayName) AS previous,
    CONCAT(s2.name, ' - ', w2.displayName) AS new,
    m.time,
    m.time AS sort_time,
    'move' AS type
FROM moves m
JOIN shelf s1 ON m.previousLocation = s1.id
JOIN warehouse w1 ON s1.warehouseId = w1.id
JOIN shelf s2 ON m.newLocation = s2.id
JOIN warehouse w2 ON s2.warehouseId = w2.id
WHERE itemId = ?

UNION ALL

SELECT 
    l.id,
    CONCAT(p.name, ' ', p.surname) AS previous,
    NULL AS new,
    CONCAT(l.timeLoaned, ' - ', COALESCE(l.timeReturned,'now')) AS time,
    COALESCE(timeReturned,timeLoaned) AS sort_time,
    'loan' AS type
FROM loans l
JOIN people p ON l.loanerId = p.id
WHERE itemId = ?
) AS combined ORDER BY sort_time DESC
");
$stmt->execute([$id,$id,$id]);
if($stmt->rowCount()>0):
?>
<table class="table table-striped table-sm">
	<thead>
		<tr>
			<td>Type</td>
			<td>Previous state</td>
			<td>New state</td>
			<td>Date</td>
		</tr>
	</thead>
	<tbody>
		<?php while($row=$stmt->fetch()): ?>
		<tr>
			<td><?= $row['type'] ?></td>
			<td><?= $row['previous'] ?></td>
			<td><?= $row['new'] ?></td>
			<td><?= $row['time'] ?></td>
		</tr>
		<?php endwhile; ?>
	</tbody>
</table>
<?php
else:
	print("<p class=\"text-secondary\">This item has no history</p>");
endif;
?>
</div>
<?php
footer();
?>
