DROP FUNCTION IF EXISTS fn_ipd_details;
CREATE FUNCTION fn_ipd_details(a_data_flag varchar(10), a_admission_id int)
RETURNS VARCHAR(1000)
BEGIN
	DECLARE	v_return VARCHAR(1000);

	IF a_data_flag = 'BED' THEN
		SELECT JSON_ARRAYAGG(JSON_OBJECT(	
			'occupied_from', occupied_from,
			'occupied_to', occupied_to,
			'bed_dtls', bed_dtls
			))
		INTO	v_return
		FROM
		(
			SELECT	occupied_from, occupied_to, CONCAT(room_type, '-', room_name, '-', bed_name, '-') bed_dtls
			FROM	ipd_bed_details ibd, bed b, floorwise_room fr
			WHERE	ibd.bed_id = b.id 
			AND		fr.id = b.room_id
			AND		ipd_admission_id = a_admission_id
		) bed_dtls;
		
	ELSEIF a_data_flag = 'CONSULTANT' THEN
		SELECT JSON_ARRAYAGG(JSON_OBJECT(	
			'addtion_date', addtion_date,
			'doc_name', doc_name
			))
		INTO	v_return
		FROM
		(
			SELECT	addtion_date, doc.doctor_name doc_name
			FROM	ipd_patient_consultant ipc, doctors doc
			WHERE	ipc.doctor_id = doc.id 
			AND		ipd_admission_id = a_admission_id
		) cons;
		
	END IF;
	return v_return;
END;