<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_storage'])) {
    $test_id = $_POST['test_id'];
    $location = $_POST['location'];

    // Fetch existing notes to append
    $curr = $conn->query("SELECT clinical_notes FROM lab_orders WHERE order_id = (SELECT order_id FROM lab_order_tests WHERE order_test_id = $test_id)")->fetch_assoc();
    $new_notes = $curr['clinical_notes'] . " | Storage: " . $location;

    // Update lab_orders clinical_notes (best approximate fit for schema)
    $stmt = $conn->prepare("UPDATE lab_orders SET clinical_notes = ? WHERE order_id = (SELECT order_id FROM lab_order_tests WHERE order_test_id = ?)");
    $stmt->bind_param("si", $new_notes, $test_id);
    if ($stmt->execute()) {
        $msg = "Storage location updated.";
    } else {
        $msg = "Error updating storage.";
    }
}

// Samples Collected
$sql = "SELECT t.*, tt.test_name, p.patient_number, u.first_name, u.last_name, o.clinical_notes
        FROM lab_order_tests t
        JOIN lab_orders o ON t.order_id = o.order_id
        JOIN patients p ON o.patient_id = p.patient_id
        JOIN users u ON p.user_id = u.user_id
        LEFT JOIN test_types tt ON t.test_type_id = tt.test_type_id
        WHERE t.status = 'SAMPLE_COLLECTED'
        ORDER BY t.created_at DESC";
$result = $conn->query($sql);
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Sample Storage')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-12">
                            <h4 class="mb-sm-0">Sample Storage</h4>
                        </div>
                    </div>
                    <?php if ($msg): ?>
                        <div class="alert alert-success"><?php echo $msg; ?></div><?php endif; ?>
                    <div class="card">
                        <div class="card-body">
                            <table id="storageTable" class="table table-bordered dt-responsive nowrap">
                                <thead>
                                    <tr>
                                        <th>Order ID</th>
                                        <th>Patient</th>
                                        <th>Test</th>
                                        <th>Notes (Location)</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($row = $result->fetch_assoc()): ?>
                                        <tr>
                                            <td><?php echo $row['order_id']; ?></td>
                                            <td><?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?>
                                            </td>
                                            <td><?php echo htmlspecialchars($row['test_name']); ?></td>
                                            <td><?php echo htmlspecialchars($row['clinical_notes'] ?? ''); ?></td>
                                            <td>
                                                <form method="POST" class="d-flex">
                                                    <input type="hidden" name="test_id"
                                                        value="<?php echo $row['order_test_id']; ?>">
                                                    <input type="text" name="location"
                                                        class="form-control form-control-sm me-2"
                                                        placeholder="Loc (e.g. Fridge A)" required>
                                                    <button type="submit" name="update_storage"
                                                        class="btn btn-sm btn-primary">Save</button>
                                                </form>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables.net-bs5/js/dataTables.bootstrap5.min.js"></script>
    <script>$('#storageTable').DataTable();</script>
</body>

</html>