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

$room_id = intval($_GET['room_id'] ?? 0);

if(isset($_POST['update_status'])){
    $status = $conn->real_escape_string($_POST['status']);
    $hk_status = $conn->real_escape_string($_POST['housekeeping_status']);
    $housekeeper = $conn->real_escape_string($_POST['housekeeper']);

    // Update room
    $conn->query("UPDATE rooms SET status='$status' WHERE id=$room_id");

    // Update housekeeping
    $conn->query("
        INSERT INTO housekeeping_status (room_id, housekeeping_status, housekeeper, last_cleaned)
        VALUES($room_id,'$hk_status','$housekeeper', NOW())
        ON DUPLICATE KEY UPDATE housekeeping_status='$hk_status', housekeeper='$housekeeper', last_cleaned=NOW()
    ");

    // Log history
    $conn->query("
        INSERT INTO housekeeping_history (room_id, status, hk_status, housekeeper, updated_at)
        VALUES($room_id,'$status','$hk_status','$housekeeper', NOW())
    ");

    header("Location: rooms_status.php");
}
$room = $conn->query("SELECT * FROM rooms WHERE id=$room_id")->fetch_assoc();
?>
<div class="container mt-4">
     <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>
<button class="btn btn-secondary" onclick="history.back()"><i class="fa fa-arrow-left"></i> Back</button>
<h3>Update Room <?= $room['room_number'] ?></h3>
<form method="POST">
    <label>Status</label>
    <select name="status" class="form-control">
        <?php foreach(['Available','Occupied','Reserved','Maintenance','Dirty','Out of Order'] as $s): ?>
            <option value="<?= $s ?>" <?= $room['status']==$s?'selected':'' ?>><?= $s ?></option>
        <?php endforeach; ?>
    </select>

    <label>Housekeeping Status</label>
    <select name="housekeeping_status" class="form-control">
        <?php foreach(['Needs Cleaning','Cleaned','Maintenance Scheduled'] as $hk): ?>
            <option value="<?= $hk ?>"><?= $hk ?></option>
        <?php endforeach; ?>
    </select>

    <label>Assign Housekeeper</label>
    <input type="text" name="housekeeper" class="form-control">

    <button type="submit" name="update_status" class="btn btn-success mt-2">Update</button>
</form>
</div>