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

if(!isset($_GET['id']) || !is_numeric($_GET['id'])){
    die("Invalid request ID.");
}

$request_id = intval($_GET['id']);

// Fetch request
$stmt = $conn->prepare("SELECT * FROM maintenance_requests WHERE id=? LIMIT 1");
$stmt->bind_param("i", $request_id);
$stmt->execute();
$result = $stmt->get_result();
$request = $result->fetch_assoc();
$stmt->close();

if(!$request){
    die("Request not found.");
}

// Handle form submission
if(isset($_POST['update_request'])){
    $room_id = intval($_POST['room_id']);
    $issue_description = $_POST['issue_description'];
    $status = $_POST['status'];

    $stmt = $conn->prepare("UPDATE maintenance_requests SET room_id=?, issue_description=?, status=? WHERE id=?");
    $stmt->bind_param("issi", $room_id, $issue_description, $status, $request_id);
    $stmt->execute();
    $stmt->close();

    header("Location: maintenance_requests.php");
    exit;
}

// Fetch rooms
$rooms_result = $conn->query("SELECT id, room_number FROM rooms ORDER BY room_number ASC");
$rooms = [];
while($r = $rooms_result->fetch_assoc()){
    $rooms[] = $r;
}
?>

<div class="container mt-4">
     <button class="btn btn-secondary" onclick="history.back()">
            <i class="fa fa-arrow-left"></i> Back
        </button>
    <h3>Edit Maintenance Request</h3>
    <form method="post">
        <div class="mb-3">
            <label>Room</label>
            <select name="room_id" class="form-control" required>
                <?php foreach($rooms as $r): ?>
                    <option value="<?= $r['id'] ?>" <?= ($r['id']==$request['room_id'])?'selected':'' ?>>
                        <?= htmlspecialchars($r['room_number']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="mb-3">
            <label>Request Detail</label>
            <textarea name="issue_description" class="form-control" required><?= htmlspecialchars($request['issue_description']) ?></textarea>
        </div>
        <div class="mb-3">
            <label>Status</label>
            <select name="status" class="form-control" required>
                <option value="Pending" <?= ($request['status']=='Pending')?'selected':'' ?>>Pending</option>
                <option value="Approved" <?= ($request['status']=='Approved')?'selected':'' ?>>Approved</option>
                <option value="Completed" <?= ($request['status']=='Completed')?'selected':'' ?>>Completed</option>
            </select>
        </div>
        <button type="submit" name="update_request" class="btn btn-success">Update Request</button>
        <a href="maintenance_requests.php" class="btn btn-secondary">Cancel</a>
    </form>
</div>

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