<?php
// delete_bed_process.php - Handles deleting a bed from the database

// Enable full error reporting for debugging. REMOVE IN PRODUCTION!
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once 'config.php'; // Include database configuration
header('Content-Type: application/json'); // Set header to return JSON response

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    $bedId = filter_var($data['bed_id'] ?? '', FILTER_SANITIZE_NUMBER_INT);

    if (empty($bedId)) {
        echo json_encode(['success' => false, 'message' => 'Bed ID is required for deletion.']);
        exit;
    }

    try {
        $pdo->beginTransaction(); // Start a transaction

        // Get room_id associated with the bed before deleting the bed
        $sqlGetRoomId = "SELECT room_id, is_occupied FROM beds WHERE bed_id = :bed_id FOR UPDATE"; // Lock the bed row
        $stmtGetRoomId = $pdo->prepare($sqlGetRoomId);
        $stmtGetRoomId->bindParam(':bed_id', $bedId, PDO::PARAM_INT);
        $stmtGetRoomId->execute();
        $bedInfo = $stmtGetRoomId->fetch(PDO::FETCH_ASSOC);

        if (!$bedInfo) {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => 'Bed not found.']);
            exit;
        }

        $roomId = $bedInfo['room_id'];
        $wasOccupied = $bedInfo['is_occupied'];

        // Delete the bed
        $sqlDeleteBed = "DELETE FROM beds WHERE bed_id = :bed_id";
        $stmtDeleteBed = $pdo->prepare($sqlDeleteBed);
        $stmtDeleteBed->bindParam(':bed_id', $bedId, PDO::PARAM_INT);

        if ($stmtDeleteBed->execute()) {
            if ($stmtDeleteBed->rowCount() > 0) {
                // If deletion was successful and the bed was occupied, decrement room's current_occupancy
                if ($wasOccupied == 1) {
                    $sqlUpdateRoomOccupancy = "UPDATE rooms SET current_occupancy = current_occupancy - 1 WHERE room_id = :room_id AND current_occupancy > 0";
                    $stmtUpdateRoomOccupancy = $pdo->prepare($sqlUpdateRoomOccupancy);
                    $stmtUpdateRoomOccupancy->bindParam(':room_id', $roomId, PDO::PARAM_INT);
                    $stmtUpdateRoomOccupancy->execute();
                }
                $pdo->commit(); // Commit the transaction
                echo json_encode(['success' => true, 'message' => 'Bed deleted successfully!']);
            } else {
                $pdo->rollBack();
                echo json_encode(['success' => false, 'message' => 'Bed not found or already deleted.']);
            }
        } else {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => 'Failed to delete bed. Please try again.']);
        }
    } catch (PDOException $e) {
        $pdo->rollBack(); // Ensure rollback on any exception
        error_log("Database error deleting bed: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'A database error occurred during deletion.']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}

