<?php
// add_floor_process.php - Handles adding new floor data to the database

require_once 'config.php'; // Include DB config
header('Content-Type: application/json'); // Return JSON response

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

    // Sanitize and validate input
    $hostelId = filter_var($data['hostelId'] ?? null, FILTER_VALIDATE_INT);
    $floorNumber = filter_var($data['floorNumber'] ?? null, FILTER_VALIDATE_INT);
    $description = trim($data['description'] ?? '');
    $totalRooms = filter_var($data['totalRooms'] ?? 0, FILTER_VALIDATE_INT);

    // Check required fields
    if ($hostelId === false || $floorNumber === false) {
        echo json_encode([
            'success' => false,
            'message' => 'Hostel and Floor Number are required and must be valid integers.'
        ]);
        exit;
    }

    if ($totalRooms === false || $totalRooms < 0) {
        $totalRooms = 0;
    }

    $sql = "INSERT INTO floors (hostel_id, floor_number, description, total_rooms)
            VALUES (:hostel_id, :floor_number, :description, :total_rooms)";

    try {
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':hostel_id', $hostelId, PDO::PARAM_INT);
        $stmt->bindParam(':floor_number', $floorNumber, PDO::PARAM_INT);
        $stmt->bindParam(':description', $description);
        $stmt->bindParam(':total_rooms', $totalRooms, PDO::PARAM_INT);

        if ($stmt->execute()) {
            echo json_encode([
                'success' => true,
                'message' => 'Floor added successfully!'
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Failed to add floor.'
            ]);
        }
    } catch (PDOException $e) {
        if ($e->getCode() == 23000) {
            echo json_encode([
                'success' => false,
                'message' => 'This floor number already exists for the selected hostel.'
            ]);
        } else {
            error_log("Database error in add_floor_process.php: " . $e->getMessage());
            echo json_encode([
                'success' => false,
                'message' => 'A database error occurred. Please try again later.'
            ]);
        }
    }
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request method.'
    ]);
}
