CREATE DEFINER=`admin`@`localhost` FUNCTION `generate_service_id`(plant_key VARCHAR(6), sequential_id INT , shift VARCHAR(40), daytimes JSON, schedule_start TIME, trip_options JSON) RETURNS varchar(40) CHARSET utf8mb4
    DETERMINISTIC
BEGIN
	DECLARE result VARCHAR(40) DEFAULT NULL;
	SET result = IFNULL(trip_options->>"$.service_id",CONCAT(
								IF(shift='IN', 'E','S'),
								'-',
								IFNULL(UPPER(plant_key), '?'),
								'-T',
								IFNULL(
										JSON_UNQUOTE(
											JSON_EXTRACT(daytimes,
												REPLACE(
													JSON_UNQUOTE(
														JSON_SEARCH( daytimes, 'one', SUBSTRING(schedule_start, 1, 5), null, '$[*].stime' )
													),
													'.stime',
													'.dayshift'
												)
										)), '?'),
								'-',
								IFNULL(
										JSON_UNQUOTE(
											JSON_EXTRACT(daytimes,
												REPLACE(
													JSON_UNQUOTE(
														JSON_SEARCH( daytimes, 'one', SUBSTRING(schedule_start, 1, 5), null, '$[*].stime' )
													),
													'.stime',
													'.service_type'
												)
										)), '?'),
								LPAD(sequential_id, 4, '0')));
RETURN result;
END