<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

$stay_id = intval($_GET['stay_id'] ?? 0);
if(!$stay_id){
    echo "<script>alert('Invalid stay ID');window.location='checkin.php';</script>";
    exit;
}

// Fetch stay info
$stay = $conn->query("
    SELECT s.id AS stay_id, s.room_id, g.name AS guest_name
    FROM stays s
    JOIN guests g ON s.guest_id=g.id
    WHERE s.id=$stay_id
")->fetch_assoc();

if(!$stay){
    echo "<script>alert('Stay not found');window.location='checkin.php';</script>";
    exit;
}

// Handle form submission
if(isset($_POST['transfer_room'])){
    $new_room_id = intval($_POST['new_room_id']);
    $old_room_id = $stay['room_id'];

    $conn->begin_transaction();
    try {
        // 1. Mark old room as Available
        $conn->query("UPDATE rooms SET status='Available' WHERE id=$old_room_id");

        // 2. Mark new room as Occupied
        $conn->query("UPDATE rooms SET status='Occupied' WHERE id=$new_room_id");

        // 3. Update stay
        $stmt = $conn->prepare("UPDATE stays SET room_id=? WHERE id=?");
        $stmt->bind_param("ii",$new_room_id,$stay_id);
        $stmt->execute();

        $conn->commit();
        echo "<script>alert('Guest successfully transferred to new room');window.location='checkin.php';</script>";
        exit;

    } catch(Exception $e){
        $conn->rollback();
        echo "<script>alert('Error transferring room. Please try again.');window.location='checkin.php';</script>";
        exit;
    }
}

// Fetch available rooms
$rooms_res = $conn->query("SELECT * FROM rooms ORDER BY status, room_number");
?>

<div class="container mt-4">
    <h4 class="mb-3"><i class="fa fa-exchange-alt"></i> Transfer Room</h4>
    <form method="POST" class="col-md-4">
        <div class="mb-3">
            <label>Guest</label>
            <input type="text" class="form-control" value="<?= htmlspecialchars($stay['guest_name']) ?>" readonly>
        </div>
        <div class="mb-3">
            <label>New Room</label>
            <select name="new_room_id" class="form-control" required>
                <option value="">Select Room</option>
                <?php while($r=$rooms_res->fetch_assoc()): 
                    $disabled = ($r['status']=='Occupied' || $r['id']==$stay['room_id']) ? 'disabled' : '';
                ?>
                    <option value="<?= $r['id'] ?>" <?= $disabled ?>>
                        Room <?= $r['room_number'] ?> (<?= $r['room_type'] ?>)
                        <?= $disabled ? '- Occupied' : '' ?>
                    </option>
                <?php endwhile; ?>
            </select>
        </div>
        <button type="submit" name="transfer_room" class="btn btn-warning">
            <i class="fa fa-exchange-alt"></i> Transfer
        </button>
        <a href="checkin.php" class="btn btn-secondary">Cancel</a>
    </form>
</div>

<?php include 'includes/footer.php'; ?>