DELIMITER //

CREATE PROCEDURE UpdateUserComplaintCategory (
    IN mobileNumber VARCHAR(20), 
    IN categoryId INT, 
    IN subcategoryId INT
)   
BEGIN
    DECLARE sessionExists BOOLEAN DEFAULT FALSE;
    
    -- Get sessionId, categoryId, and subcategoryId for the provided mobile number
    SELECT SessionId, CategoryId, SubcategoryId INTO @sessionId, @currentCategoryId, @currentSubcategoryId FROM UserComplaintSessions 
    	WHERE Mobile = mobileNumber;
    
    -- Check if sessionId exists
    IF @sessionId IS NOT NULL THEN
        -- If categoryId is supplied, update categoryId and set complaintStatus to 2
        IF categoryId IS NOT NULL THEN
            UPDATE UserComplaintSessions SET CategoryId = categoryId
            	WHERE SessionId = @sessionId;
        END IF;
        
        -- If subcategoryId is supplied and categoryId is present, update subcategoryId
        IF subcategoryId IS NOT NULL AND @currentCategoryId IS NOT NULL THEN
            UPDATE UserComplaintSessions SET SubcategoryId = subcategoryId
            	WHERE SessionId = @sessionId AND CategoryId = @currentCategoryId;
        END IF;
        SET sessionExists = TRUE;
    END IF;
    SELECT sessionExists;
END

DELIMITER ;