DROP FUNCTION IF EXISTS fn_symptom_vital_hist;
CREATE FUNCTION fn_symptom_vital_hist(data_type varchar(1), 
									op_ip_flag varchar(1), 
									op_ip_id int)
RETURNS TEXT
BEGIN
DECLARE	v_return TEXT;

	IF data_type = 'S' THEN
		SELECT JSON_ARRAYAGG(JSON_OBJECT(	
				'capture_date', capture_date,
				'details', details
				))
				INTO	v_return
				FROM
					(
				SELECT	psd.capture_date as capture_date,
				GROUP_CONCAT(sd.symptom_disease_name) as details 
				FROM	patient_symptom_disease psd
				INNER JOIN		symptom_disease sd ON	psd.symptom_disease_id = sd.id
						WHERE	psd.opd_ipd_ot_flag = op_ip_flag
						AND	psd.opd_ipd_ot_id = op_ip_id
					) Sympton;
	ELSEIF	data_type = 'V' THEN
			SELECT JSON_ARRAYAGG(JSON_OBJECT(	
			'capture_date', capture_date,
			'details', details
				))
				INTO	v_return
				FROM
					(
						SELECT	psd.visit_id as visit_id,
						psd.opd_ipd_ot_id as opd_ipd_ot_id,
						psd.vital_capture_date as capture_date,
						GROUP_CONCAT(CONCAT(sd.vital_name, " - ", vital_data)) as details 
						FROM	patient_vitals psd
						INNER JOIN		vitals sd ON	psd.vital_id = sd.id
						WHERE	psd.opd_ipd_ot_flag = op_ip_flag
						AND	psd.opd_ipd_ot_id = op_ip_id
					) vital;
	END IF;
	
	return v_return;
END;