Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
55 kB
1
Indexable
Never
const closedEvents = [
	// "IN_AA",
	// "IN_ST",
	// "SW_TH",
	// "SW_RD",
	// "SW_IPL",
	// "SW_SG",
	// "SW_BGMI",
	// "SW_FF",
	// "SW_V",
	// "SW_SOM",
	// "SW_MM",
	// "SW_BBS",
	// "SW_ER"
]

const { updateParCoins, updateCoins, updateDWInsert, updateDWReturn } = require("./AnantaCoins");

// Check Profile Status
async function checkProfileStatus(conn, participantID) {
	const [rows, fields] = await conn.execute(
		`SELECT ProfileStatus FROM Participants WHERE ParticipantID = '${participantID}'`
	);
	if (rows.length > 0) {
		if (rows[0]["ProfileStatus"] == 1) {
			return true;
		}
		return false;
	}
	return false;
}

// Check Profile Status
async function checkPaymentStatus(conn, participantID) {
	const [rows, fields] = await conn.execute(
		`SELECT TxnStatus FROM Participants WHERE ParticipantID = '${participantID}'`
	);
	if (rows.length > 0) {
		if (rows[0]["TxnStatus"] == "TXN_SUCCESS") {
			return true;
		}
		return false;
	}
	return false;
}

async function getEvents(conn, participantID) {
	// console.log(participantID);
	const [soloRows, soloFields] = await conn.execute(
		`select * from Events inner join SoloRegistration on Events.EventCode = SoloRegistration.EventCode where SoloRegistration.ParticipantID = '${participantID}'`
	);
	const [teamRows, teamFields] = await conn.execute(
		`select * from Events inner join Teams inner join TeamRegistration on Teams.TeamID = TeamRegistration.TeamID and Events.EventCode = Teams.EventCode where TeamRegistration.ParticipantID = '${participantID}'`
	);

	if (soloRows.length > 0 || teamRows.length > 0) {
		return {
			code: 200,
			resMessage: {
				message: "Information Fetch complete...",
				data: {
					solo: soloRows,
					team: teamRows,
				},
				type: "success",
			},
		};
	} else {
		return {
			code: 500,
			resMessage: {
				message: "Failed",
				type: "error",
			},
		};
	}
}
async function fetchDigitalWalletData(conn, participantID) {
	// const participantID = await getParticipantID(conn, email);
	try {


		// console.log(participantID);
		//   const [rows, fields] = await conn.execute(
		// 	`SELECT * FROM DigitalWallet WHERE ParticipantID='${participantID}'`
		//   );
		const [rows, fields] = await conn.execute(
			`SELECT 
		  DW.*,
		  E.EventName
		FROM DigitalWallet DW
		LEFT JOIN Events E ON DW.EventCode = E.EventCode
		WHERE DW.ParticipantID='${participantID}'`
		);


		// Log the fetched data
		//   console.log(rows);
		if (rows.length > 0) {
			return {
				code: 200,
				resMessage: {
					message: "Information Fetch complete...",
					data: { rows },
					type: "success",
				},
			};
		}
		else {
			return {
				code: 500,
				resMessage: {
					message: "Failed",
					type: "error",
				},
			};
		}

		// You can return the data if needed

	} catch (error) {
		console.error('Error fetching Digital Wallet data from MySQL:', error);
		throw error;
	}
}

async function getTeamMembers(conn, teamID) {
	const [rows, fields] = await conn.execute(
		`select par.ParticipantID, par.Firstname, par.Lastname, tr.Role from Participants as par inner Join TeamRegistration as tr on tr.ParticipantID = par.ParticipantID  where tr.TeamID = '${teamID}'`
	);

	if (rows.length > 0) {
		return {
			code: 200,
			resMessage: {
				message: "Members Found",
				data: rows,
				type: "success",
			},
		};
	} else {
		return {
			code: 500,
			resMessage: {
				message: "Failed",
				type: "error",
			},
		};
	}
}

// Remove Team Member
async function removeTeamMember(conn, participantID, teamID) {
	const [rows, fields] = await conn.execute(
		`DELETE FROM TeamRegistration WHERE ParticipantID = '${participantID}' and TeamID = '${teamID}'`
	);
	const eventID = teamID.split("_")[0] + "_" + teamID.split("_")[1];
	const isUpdateRegCount = await updateRegCountNew(
		conn,
		eventID,
		participantID,

	);
	const isupdateEventRegCount = await updateEventRegistrationCount(
		conn,
		eventID
	);

	if (rows && isUpdateRegCount && isupdateEventRegCount) {
		return {
			code: 200,
			resMessage: {
				message: "Member Removed",
				type: "success",

			},
		};
	} else {
		return {
			code: 500,
			resMessage: {
				message: "Cannot Unregister",
				type: "error",


			},
		};
	}
}

async function updateEventRegistrationCount(conn, eventCode) {
	const [rows, fields] = await conn.execute(
		`SELECT HeadCount FROM Events where EventCode = '${eventCode}'`
	);

	let regCount = 0;

	if (rows.length > 0 && rows[0].HeadCount <= 1) {

		const [getRegCountRows, getRegCountFields] = await conn.execute(`SELECT COUNT(*) as total FROM SoloRegistration WHERE EventCode = '${eventCode}'`);

		if (getRegCountRows.length > 0) {
			regCount = getRegCountRows[0].total
		} else {
			regCount = 0;
		}
		console.log("Inside regCount =", regCount);

		// console.log("Total Registration before: " + total);

		// if (option == "inc") {
		// 	total++;
		// } else if (option == "dec") {
		// 	total--;
		// }

		// console.log("Total Registration after: " + total);
		// const [updateRows, updateFields] = await conn.execute(
		// 	`update Events set TotalRegistration = ${total} where EventCode = "${eventCode}"`
		// );

		// if (updateRows) {
		// 	return true;
		// } else {
		// 	return false;
		// }
	} else {
		const [getRegCountRows, getRegCountFields] = await conn.execute(`SELECT COUNT(*) as total FROM TeamRegistration WHERE TeamID LIKE '${eventCode}%' AND Role = 'Leader'`);

		if (getRegCountRows.length > 0) {
			regCount = getRegCountRows[0].total
		} else {
			regCount = 0;
		}
		console.log("Inside regCount =", regCount);
	}

	console.log("Out of Condition, regCount =", regCount)

	const [updateEventRows, updateEventFields] = await conn.execute(`UPDATE Events SET TotalRegistration = ${regCount} WHERE EventCode = '${eventCode}'`);

	if (updateEventRows) {
		return true;
	} else {
		return false;
	}
}

async function deleteEvent(
	conn,
	participantID,
	eventCode,
	isSolo,
	role,
	teamID
) {
	const [deleteCheckRow, deleteCheckFields] = await conn.execute(
		`SELECT Attendence FROM SoloRegistration WHERE EventCode = '${eventCode}' and ParticipantID = '${participantID}'`
	)
	if (isSolo) {


		console.log(deleteCheckRow[0].Attendence);
		if (deleteCheckRow[0].Attendence === 0) {
			console.log("atten 0 h")
			const [deleteRows, deleteFields] = await conn.execute(
				`DELETE FROM SoloRegistration WHERE EventCode = '${eventCode}' and ParticipantID = '${participantID}'`
			);
			const isEventRegCount = await updateEventRegistrationCount(
				conn,
				eventCode
			);
			const isUpdateRegCount = await updateRegCountNew(
				conn,
				eventCode,
				participantID,

			);

			if (deleteRows && isEventRegCount && isUpdateRegCount) {
				// const respcoin = await updateParCoins(conn,participantID);
				// console.log(respcoin);
				if (eventCode.includes('IN') || eventCode.includes('SW') || eventCode.includes('VS')) {
					await updateDWReturn(conn, participantID, eventCode, 200);
				}
				else if (eventCode.includes('EQ')) {
					await updateDWInsert(conn, participantID, eventCode, 1000);
				}
				else if (eventCode.includes('KK')) {
					await updateDWInsert(conn, participantID, eventCode, 1000);
				}


				const respcoin = await updateParCoins(conn, participantID);
				console.log(respcoin);
				return {
					code: 200,
					resMessage: {
						type: "success",
						message: "Event Unregistration Complete...",
						category: "Solo",
					},
				};

			}
			else {
				console.log("atten 0 h par fail h")
				return {
					code: 200,
					resMessage: {
						type: "Info",
						message: "Event Unregisteration Failed...",
						category: "Solo",
					},
				};

			}
		}
		// else if(deleteCheckRow[0].Attendence>0){
		// 	console.log("atten 1 h")
		// 	return{
		// 		code :500,
		// 		resMessage: {
		// 			type: "Info",
		// 			message: "You have attended this event so you cannot Unregister",

		// 		},
		// 	}
		// }

		else if (deleteCheckRow[0].Attendence > 0) {
			console.log("atten 1 h")
			return {
				code: 200,
				resMessage: {
					type: "info",
					message: "Cannot delete the event you attended...",
					category: "Solo",
				},
			};

		}
		else {
			console.log("gadbad")
			return {
				code: 200,
				resMessage: {
					type: "info",
					message: "Event Unregisteration Failed...",
					category: "Solo",
				},
			};

		}
	} else {

		const [attendanceRows, attendanceFields] = await conn.execute(
			`Select COUNT(*) as count from TeamRegistration where ParticipantID in (Select ParticipantID from TeamRegistration Where TeamID='${teamID}') and Attendence='1' and TeamID='${teamID}';`
		)
		const [attendanceRoleRows, attendanceRoleFields] = await conn.execute(
			`Select *  from TeamRegistration where ParticipantID in (Select ParticipantID from TeamRegistration Where TeamID='${teamID}') and Attendence='1' and TeamID='${teamID}';`
		)
		console.log(attendanceRows[0].count);
		console.log(attendanceRoleRows);
		console.log(role);
		
		const [deleteCheckRows, deleteCheckFields] = await conn.execute(
			`Select COUNT(*) as count FROM TeamRegistration WHERE TeamID = '${teamID}' and ParticipantID = '${participantID}'`
		);
		console.log(deleteCheckRows[0].count);
		if(deleteCheckRows[0].count>0){
			console.log("greater")
		if (attendanceRows[0].count == 0) {


			const [deleteRows, deleteFields] = await conn.execute(
				`DELETE FROM TeamRegistration WHERE TeamID = '${teamID}' and ParticipantID = '${participantID}'`
			);

			if (deleteRows) {
				if (role == "Leader") {
					console.log("Team Leader Things under process...");
					const [membersRows, membersFields] = await conn.execute(
						`select * FROM TeamRegistration WHERE TeamID = '${teamID}' and Role = 'Member'`
					);

					let count = 0;
					console.log("Team Member removal starts...");
					console.log(membersRows.length);
					console.log(membersRows);

					membersRows.forEach(async (element) => {
						console.log(element.ParticipantID);
						console.log("Team Member Delete processing...");
						console.log("EventCode: " + eventCode);
						let [deleteMemberRow, deleteMemberFields] =
							await conn.execute(
								`DELETE FROM TeamRegistration where ParticipantID = '${element.ParticipantID}'`
							);
						console.log(deleteMemberRow);
						if (
							deleteMemberRow &&
							(await updateRegCountNew(
								conn,
								eventCode,
								element.ParticipantID,

							)) &&
							(await updateEventRegistrationCount(
								conn,
								eventCode
							))
						) {
							console.log("Team Member Delete Complete.");
							count++;
						}
						console.log("Ashish Done here.");
					});
					console.log(count);

					const [deleteTeamRows, deleteTeamFields] = await conn.execute(
						`DELETE FROM Teams WHERE TeamID = '${teamID}'`
					);
					if (deleteTeamRows) {
						if ((await updateDWReturn(conn,participantID,eventCode,200)) &&
							(await updateParCoins(conn,participantID)) &&
							(await updateRegCountNew(
								conn,
								eventCode,
								participantID,

							)) &&
							(await updateEventRegistrationCount(
								conn,
								eventCode
							))
						) {
							console.log("Participant events count updated...");
							return {
								code: 200,
								resMessage: {
									type: "success",
									message: "Team Unregistered Successfully...",
									category: "Team",
								},
							};
						}
					}
				}
			}
			if (await updateRegCountNew(conn, eventCode, participantID)) {
				return {
					code: 200,
					resMessage: {
						type: "success",
						message: "Unregisteration Complete...",
						category: "Team",
					},
				};
			}
		}
		else if (attendanceRows[0].count > 0) {


			if (role == "Leader") {
				console.log("leader me enter")
				return {
					code: 500,
					resMessage: {
						type: "error",
						message: "You or your team member attended this event. So, you cant unregister this event...",
						category: "Team",
					},
				}

			}
			else if (role == "Member") {
				console.log("mmeber me enter")
				let isattended = false;

				attendanceRoleRows.forEach(async (element) => {
					console.log(element.ParticipantID);
					if (element.ParticipantID == participantID) {
						console.log("attend already done")
						isattended = true;


					}



				})
				if (isattended == true) {
					console.log(isattended,"attend kar dia");
					return {
						code: 500,
						resMessage: {
							type: "error",
							message: "You have attended this event. So, you cant unregister this event...",
							category: "Team",
						},
					}
				}
				console.log("deletetion process started");
				const [deleteRows, deleteFields] = await conn.execute(
					`DELETE FROM TeamRegistration WHERE TeamID = '${teamID}' and ParticipantID = '${participantID}'`
				);
				if (deleteRows) {
					if (await updateRegCountNew(conn, eventCode, participantID) && await updateDWReturn(conn, participantID, eventCode, 200) && await updateParCoins(conn,participantID) && await updateEventRegistrationCount(conn, eventCode)) {
						console.log("yeh msg ")

						return {

							code: 200,
							resMessage: {
								type: "success",
								message: "Unregisteration Complete...",
								category: "Team",
							},
						};
					}

				}

			}

			return {
				code: 500,
				resMessage: {
					type: "error",
					message: "You or your team member attended this event. So, you cant unregister this event...",
					category: "Team",
				},
			};
		}
		else {
			return {
				code: 500,
				resMessage: {
					type: "error",
					message: "Unregisteration Failed...",
					category: "Team",
				},
			};
		}
	}
	else{
		console.log("less");
		return {
			code: 500,
			resMessage: {
				type: "error",
				message: "already deleted",
				category: "Team",
			},
		};
	}
	}
}

// =========================== Validating the Selected Event ===========================
//clashedit
async function checkEventClash(conn, eventInfoRows,eventCode) {

	  // Construct the placeholders for the event codes
	  // Construct the placeholders for the event codes
	const placeholders = eventInfoRows.map(event => `'${event.EventCode}'`).join(', ');

	  console.log(eventCode);
	  // Construct the SQL query with placeholders for the event codes
	  const query = `
		  SELECT *
		  FROM Events
		  WHERE EventCode IN (${placeholders})
		  AND (
			StartTime BETWEEN
			  SUBTIME((SELECT StartTime FROM Events WHERE EventCode = '${eventCode}'), '00:30:00') AND
			  ADDTIME((SELECT StartTime FROM Events WHERE EventCode = '${eventCode}'), '00:30:00')
		  );
	  `
	console.log(query);
	  // Combine the event codes with the start and end times
	  const params = [...placeholders];
  
	  const [rows, fields] = await conn.execute(query, params);
	  console.log(rows);
	  return rows;


}
async function checkParticipantEventClashes(conn, eventCode, participantID) {
	// const [participantEventsRows, participantEventsFields] = await conn.execute(
	// 	`SELECT EventCode FROM SoloRegistration WHERE ParticipantID = '${participantID}'`
	// );
	const [eventInfoRows, eventInfoFields] = await conn.execute(
		`SELECT e.*
		FROM Events e
		JOIN (
			SELECT EventCode
			FROM SoloRegistration
			WHERE ParticipantID = '${participantID}'
			UNION
			SELECT EventCode
			FROM TeamRegistration
			WHERE ParticipantID = '${participantID}'
		) AS r ON e.EventCode = r.EventCode
		WHERE e.EventCode != '${eventCode}';
		`
	);
	// Check for clashes with each event code

			// Assuming your checkEventClash function is correctly implemented
			const isClash = await checkEventClash(
				conn,
				eventInfoRows,
				eventCode,

			);
			
			
			// if (isClash) {
			// 	return {
			// 		code: 200,
			// 		message: `Event Clash! Clashing with event: ${rows}`,
			// 		type: "Info",
			// 		eventCodeClashName: rows,
			// 	};
			// }
			if (isClash.length>0) {
				// Extract EventNames from the rows array
				
				const clashingEventNames = isClash.map(row => row.EventName).join(', ');
			
				return {
					code: 200,
					message: `Event Clash! Clashing with events: ${clashingEventNames}`,
					type: "Info",
					eventCodeClashName: clashingEventNames,
				};
			}

		
	// If no clashes found with any event, return success message
	return {
		code: 200,
		message: `No clashes found with any event`,
		type: "Success",
	};


}





// async function checkParticipantEventClashes(conn, eventCode, participantID) {
//     // Fetch all event codes associated with the participant ID
// 	console.log(eventCode);
// 	console.log(participantID);

//     const [participantEventsRows, participantEventsFields] = await conn.execute(
//         `SELECT EventCode FROM SoloRegistration WHERE ParticipantID = '${participantID}'`
//     );

//     // Check for clashes with each event code
//     for (let i=0;i<participantEventsRows.length;i++) {
//         const currentEventCode = participantEventsRows[i].EventCode;
// 		console.log(currentEventCode);

//         // Skip checking for the current event code itself
//         if (currentEventCode === eventCode) {
//             continue;
//         }

//         // Fetch start time of the event from the Events table
//         const [eventStartTimeRows, eventStartTimeFields] = await conn.execute(
//             `SELECT StartTime FROM Events WHERE EventCode = '${currentEventCode}'`
//         );

//         // Check for clashes
//         if (eventStartTimeRows.length > 0) {
//             const currentEventStartTime = eventStartTimeRows[0].StartTime;

//             // Assuming your checkEventClash function is correctly implemented
//             const isClash = await checkEventClash(
//                 conn,
//                 currentEventCode,
// 				eventCode,
//                 currentEventStartTime
//             );

//             if (isClash) {
//                 return true; // Clash found
//             }
//         }
//     }

//     return false; // No clashes found
// }

//end
async function checkEvent(conn, eventCode, participantID) {

	if (closedEvents.includes(eventCode)) {
		return {
			code: 500,
			message: "Registration Will Open Soon",
			type: "Info",
		};
	}

	// Check Profile
	if ((await checkProfileStatus(conn, participantID)) == false) {
		return { code: 200, message: "Profile", type: "Warning" };
	}

	// Check PaymentStatus
	if ((await checkPaymentStatus(conn, participantID)) == false) {
		return { code: 200, message: "BuyPass", type: "Warning" };
	}

	// Schedule code...

	// +++++++++++++++++++  Already Registered Starts +++++++++++++++++++++

	/*
  
  If the Participant is already registered in specific Event, Guest lecture or Workshop, then he/she can't register in that.

  Other Scenario also need to be consider given below...

  */

	// Already Registered - Solo
	const [checkSoloRegRows, checkSoloRegFields] = await conn.execute(
		`SELECT * FROM SoloRegistration WHERE EventCode = '${eventCode}' AND ParticipantID = '${participantID}'`
	);
	const [checkSoloRegFirstRows, checkSoloRegFirstFields] = await conn.execute(
		`SELECT * FROM SoloRegistration WHERE ParticipantID = '${participantID}'`
	);
	console.log(checkSoloRegFirstRows.length);
	const [checkTeamRegFirstRows, checkTeamRegFirstFields] = await conn.execute(
		`SELECT * FROM TeamRegistration WHERE ParticipantID = '${participantID}'`
	);

	// Already Registered - Team
	const [checkTeamRegRows, checkTeamRegFields] = await conn.execute(
		`SELECT COUNT(RegisterID) AS count FROM TeamRegistration WHERE TeamID LIKE '${eventCode}%' AND ParticipantID = '${participantID}'`
	);
	//editied
	const [eventStartTimeRows, eventStartTimeFields] = await conn.execute(
		`SELECT StartTime FROM Events WHERE EventCode = '${eventCode}'`
	);

	if (checkSoloRegRows.length > 0 || checkTeamRegRows[0]["count"] > 0) {
		return {
			code: 200,
			message: "You have Already Registered in this Event",
			type: "Info",
		};
	}

	else if (eventStartTimeRows.length > 0) {

		const eventStartTime = eventStartTimeRows[0].StartTime;

		// Create JavaScript Date objects
		// const dateObject = new Date(eventDate);
		// const timeObject = new Date(eventTime);
		// console.log(dateObject);
		// console.log(timeObject);
		// Combine date and time into a single string
		// const eventStartDateTimeString = `${dateObject.toISOString().split('T')[0]} ${timeObject.toISOString().split('T')[1].split('.')[0]}`;

		// // Create a JavaScript Date object
		// const eventStartTime = new Date(eventStartDateTimeString);

		console.log('Event Start Time:', eventStartTime);
		if (checkSoloRegFirstRows.length == 0) {

			console.log("first h");
			const [parRows, parFields] = await conn.execute(
				`SELECT * FROM Participants WHERE ParticipantID = '${participantID}'`
			);

			const [checkEventRows, checkEventFields] = await conn.execute(
				`SELECT * FROM Events WHERE EventCode = '${eventCode}'`
			);

			/* 
			Check Criteria:
	
			1. Events Category includes INERTIA('IN'), SWOOSH('SW')
			2. Guests Category includes INERTIA('EQ')
			3. Workshops Category includes INERTIA('IN')
	
			If total registration of above categories of Participant is less than that of Pass which he/she bought, then and then he/she are eligible to register for event.
	
			And also whether the Event vacancy is Full or not.
			If Full, the one is not allow to register
			else, yes.
	
			Other Scenario also need to be consider given below...
	
			*/

			if (checkEventRows.length > 0 && parRows.length > 0) {
				const [passRows, passFields] = await conn.execute(
					`SELECT * FROM Passes WHERE PassCode = (SELECT PassCode FROM Participants WHERE ParticipantID = '${participantID}')`
				);

				// if (["IN", "SW"].includes(eventCode.substring(0, 2))) {
				// 	if (passRows[0]["EventsLimit"] <= parRows[0]["TotalEvents"]) {
				// 		return {
				// 			code: 200,
				// 			message: "EventLimitReached",
				// 			type: "Warning",
				// 		};
				// 	}
				// }
				if (["SW"].includes(eventCode.substring(0, 2))) {
					if (parRows[0]["DigitalPoints"] < 200) {
						return {
							code: 200,
							message: "Unsufficient Coins",
							type: "Warning",
						};
					}
				}
				if (["IN"].includes(eventCode.substring(0, 2))) {
					if (parRows[0]["DigitalPoints"] < 200) {
						return {
							code: 200,
							message: "Unsufficient Coins",
							type: "Warning",
						};
					}
				}
				if (["VS"].includes(eventCode.substring(0, 2))) {
					if (parRows[0]["DigitalPoints"] < 200) {
						return {
							code: 200,
							message: "Unsufficient Coins",
							type: "Warning",
						};
					}
				}
				if (["IN"].includes(eventCode.substring(0, 2))) {
					console.log("hattt")
					if (passRows[0]["Inertia"] <= parRows[0]["TotalInertia"]) {
						return {
							code: 200,
							message: "EventLimitReached",
							type: "Warning",
						};
					}
				}
				if (["VS"].includes(eventCode.substring(0, 2))) {
					console.log("jaane be")
					if (passRows[0]["VirtualShowdownLimit"] <= parRows[0]["TotalVirtualShowdown"]) {
						return {
							code: 200,
							message: "EventLimitReached",
							type: "Warning",
						};
					}
				}
				if (["SW"].includes(eventCode.substring(0, 2))) {
					if (passRows[0]["Swoosh"] <= parRows[0]["TotalSwoosh"]) {
						return {
							code: 200,
							message: "EventLimitReached",
							type: "Warning",
						};
					}
				}
				else if (["KK"].includes(eventCode.substring(0, 2))) {
					if (passRows[0]["WorkshopsLimit"] <= parRows[0]["TotalWorkshops"]) {
						return {
							code: 200,
							message: "WorkshopsLimitReached",
							type: "Warning",
						};
					}
				} else if (["EQ"].includes(eventCode.substring(0, 2))) {
					if (passRows[0]["GuestsLimit"] <= parRows[0]["TotalGuests"]) {
						return {
							code: 200,
							message: "GuestsLimitReached",
							type: "Warning",
						};
					}
				}

				// Checking Vacancy

				// Check whether the event is Solo or Team...
				if (checkEventRows[0]["HeadCount"] == 1) {
					// Response - For Solo Category...
					if (
						checkEventRows[0]["TotalRegistration"] <
						checkEventRows[0]["MaxRegistration"]
					) {
						return {
							code: 200,
							message: "RegisterNow",
							type: "success",
							eventType: checkEventRows[0]["EventType"],
							Category: "Solo",
							// eventCodeClashName:eventCodeClashName,
							// eventCodeClashName:checkEventRow
						};
					} else {
						// Response - Event Vacancy is Full...
						return { code: 200, message: "VacancyFull", type: "Warning" };
					}
				}
				else {
					// Response - For Team Category...
					return {
						code: 200,
						message: "RegisterNow",
						type: "success",
						eventType: checkEventRows[0]["EventType"],
						Category: "Team",

					};
				}
			}
		}
		else {

			// Check for clashing events
			const isClash = await checkParticipantEventClashes(
				conn,
				eventCode,
				participantID,

			);
			console.log(isClash);
			//edited
			if (isClash.type != 'Success') {


				const [parRows, parFields] = await conn.execute(
					`SELECT * FROM Participants WHERE ParticipantID = '${participantID}'`
				);

				const [checkEventRows, checkEventFields] = await conn.execute(
					`SELECT * FROM Events WHERE EventCode = '${eventCode}'`
				);

				/* 
				Check Criteria:
		
				1. Events Category includes INERTIA('IN'), SWOOSH('SW')
				2. Guests Category includes INERTIA('EQ')
				3. Workshops Category includes INERTIA('IN')
		
				If total registration of above categories of Participant is less than that of Pass which he/she bought, then and then he/she are eligible to register for event.
		
				And also whether the Event vacancy is Full or not.
				If Full, the one is not allow to register
				else, yes.
		
				Other Scenario also need to be consider given below...
		
				*/

				if (checkEventRows.length > 0 && parRows.length > 0) {
					const [passRows, passFields] = await conn.execute(
						`SELECT * FROM Passes WHERE PassCode = (SELECT PassCode FROM Participants WHERE ParticipantID = '${participantID}')`
					);

					// if (["IN", "SW"].includes(eventCode.substring(0, 2))) {
					// 	if (passRows[0]["EventsLimit"] <= parRows[0]["TotalEvents"]) {
					// 		return {
					// 			code: 200,
					// 			message: "EventLimitReached",
					// 			type: "Warning",
					// 		};
					// 	}
					// }
					if (["SW"].includes(eventCode.substring(0, 2))) {
						if (parRows[0]["DigitalPoints"] < 200) {
							return {
								code: 200,
								message: "Unsufficient Coins",
								type: "Warning",
							};
						}
					}
					if (["IN"].includes(eventCode.substring(0, 2))) {
						if (parRows[0]["DigitalPoints"] < 200) {
							return {
								code: 200,
								message: "Unsufficient Coins",
								type: "Warning",
							};
						}
					}
					if (["VS"].includes(eventCode.substring(0, 2))) {
						if (parRows[0]["DigitalPoints"] < 200) {
							return {
								code: 200,
								message: "Unsufficient Coins",
								type: "Warning",
							};
						}
					}
					if (["IN"].includes(eventCode.substring(0, 2))) {
						if (passRows[0]["Inertia"] <= parRows[0]["TotalInertia"]) {
							return {
								code: 200,
								message: "EventLimitReached",
								type: "Warning",
							};
						}
					}
					if (["VS"].includes(eventCode.substring(0, 2))) {
						
						if (passRows[0]["VirtualShowdownLimit"] <= parRows[0]["TotalVirtualShowdown"]) {
							return {
								code: 200,
								message: "EventLimitReached",
								type: "Warning",
							};
						}
					}
					if (["SW"].includes(eventCode.substring(0, 2))) {
						if (passRows[0]["Swoosh"] <= parRows[0]["TotalSwoosh"]) {
							return {
								code: 200,
								message: "EventLimitReached",
								type: "Warning",
							};
						}
					}
					else if (["KK"].includes(eventCode.substring(0, 2))) {
						if (passRows[0]["WorkshopsLimit"] <= parRows[0]["TotalWorkshops"]) {
							return {
								code: 200,
								message: "WorkshopsLimitReached",
								type: "Warning",
							};
						}
					} else if (["EQ"].includes(eventCode.substring(0, 2))) {
						if (passRows[0]["GuestsLimit"] <= parRows[0]["TotalGuests"]) {
							return {
								code: 200,
								message: "GuestsLimitReached",
								type: "Warning",
							};
						}
					}

					// Checking Vacancy

					// Check whether the event is Solo or Team...
					if (checkEventRows[0]["HeadCount"] == 1) {
						// Response - For Solo Category...
						if (
							checkEventRows[0]["TotalRegistration"] <
							checkEventRows[0]["MaxRegistration"]
						) {
							return {
								code: 200,
								message: "RegisterNow",
								type: "success",
								eventType: checkEventRows[0]["EventType"],
								Category: "Solo",
								eventCodeClashName: isClash.eventCodeClashName,
								// eventCodeClashName:checkEventRow
							};
						} else {
							// Response - Event Vacancy is Full...
							return { code: 200, message: "VacancyFull", type: "Warning" };
						}
					} else {
						// Response - For Team Category...
						return {
							code: 200,
							message: "RegisterNow",
							type: "success",
							eventType: checkEventRows[0]["EventType"],
							Category: "Team",
							eventCodeClashName: isClash.eventCodeClashName,
						};
					}
				} else {
					// Response - No Such Event Exists...
					return { code: 200, message: "NoRecordFound", type: "Warning" };
				}
			} else if (isClash.type == "Success") {
				// Handle the case when the selected event does not exist

				//editednend
				// Checking If Already Registered in either Solo or Team Event...


				// +++++++++++++++++++  Already Registered Ends  +++++++++++++++++++++

				// +++++++++++++++++++ Check Registration Limits Starts +++++++++++++++++++++


				const [parRows, parFields] = await conn.execute(
					`SELECT * FROM Participants WHERE ParticipantID = '${participantID}'`
				);

				const [checkEventRows, checkEventFields] = await conn.execute(
					`SELECT * FROM Events WHERE EventCode = '${eventCode}'`
				);

				/* 
				Check Criteria:
			
				1. Events Category includes INERTIA('IN'), SWOOSH('SW')
				2. Guests Category includes INERTIA('EQ')
				3. Workshops Category includes INERTIA('IN')
			
				If total registration of above categories of Participant is less than that of Pass which he/she bought, then and then he/she are eligible to register for event.
			
				And also whether the Event vacancy is Full or not.
				If Full, the one is not allow to register
				else, yes.
			
				Other Scenario also need to be consider given below...
			
				*/

				if (checkEventRows.length > 0 && parRows.length > 0) {
					const [passRows, passFields] = await conn.execute(
						`SELECT * FROM Passes WHERE PassCode = (SELECT PassCode FROM Participants WHERE ParticipantID = '${participantID}')`
					);
					if (["IN"].includes(eventCode.substring(0, 2))) {
						if (passRows[0]["Inertia"] <= parRows[0]["TotalInertia"]) {
							return {
								code: 200,
								message: "EventLimitReached",
								type: "Warning",
							};
						}
					}
					if (["VS"].includes(eventCode.substring(0, 2))) {
						if (passRows[0]["VirtualShowdownLimit"] <= parRows[0]["TotalVirtualShowdown"]) {
							return {
								code: 200,
								message: "EventLimitReached",
								type: "Warning",
							};
						}
					}
					if (["SW"].includes(eventCode.substring(0, 2))) {
						if (passRows[0]["Swoosh"] <= parRows[0]["TotalSwoosh"]) {
							return {
								code: 200,
								message: "EventLimitReached",
								type: "Warning",
							};
						}
					}
					else if (["KK"].includes(eventCode.substring(0, 2))) {
						if (passRows[0]["WorkshopsLimit"] <= parRows[0]["TotalWorkshops"]) {
							return {
								code: 200,
								message: "WorkshopsLimitReached",
								type: "Warning",
							};
						}
					} else if (["EQ"].includes(eventCode.substring(0, 2))) {
						if (passRows[0]["GuestsLimit"] <= parRows[0]["TotalGuests"]) {
							return {
								code: 200,
								message: "GuestsLimitReached",
								type: "Warning",
							};
						}
					}

					// Checking Vacancy

					// Check whether the event is Solo or Team...
					if (checkEventRows[0]["HeadCount"] == 1) {
						// Response - For Solo Category...
						if (
							checkEventRows[0]["TotalRegistration"] <
							checkEventRows[0]["MaxRegistration"]
						) {

							return {

								code: 200,
								message: "RegisterNow",
								type: "success",
								eventType: checkEventRows[0]["EventType"],
								Category: "Solo",

							};

						} else {
							// Response - Event Vacancy is Full...
							return { code: 200, message: "VacancyFull", type: "Warning" };
						}
					} else {
						// Response - For Team Category...
						return {
							code: 200,
							message: "RegisterNow",
							type: "success",
							eventType: checkEventRows[0]["EventType"],
							Category: "Team",

						};
					}
				} else {
					// Response - No Such Event Exists...
					return { code: 200, message: "NoRecordFound", type: "Warning" };
				}
			}
		}
	};
}


// +++++++++++++++++++ Check Registration Limits Ends +++++++++++++++++++++

// =========================== Registration Count Update +1 Starts ===========================

// async function updateRegCount(conn, eventCode, participantID, option) {
// 	/* 

//   As soon as event participant is registered, we need to increment the values in TotalEvents, TotalGuest, and TotalWorkshops in Participants to know the total count of the participants.

//   Logic:
//   1. Fetching Old values of 'TotalEvents', 'TotalGuests' and 'TotalWorkshops' from the `Participants` table.
//   2. Increment the value of either of the category according to the 'EventCode' and update the value of variable.
//   3. Update the respective fields of `Participants` table in database. 

//   */

// 	// Fetch Query.
// 	const [parRows, parFields] = await conn.execute(
// 		`SELECT TotalVirtualShowdown,TotalInertia,TotalSwoosh,TotalEvents, TotalWorkshops, TotalGuests FROM Participants WHERE ParticipantID = '${participantID}'`
// 	);

// 	if (parRows.length > 0) {
// 		// Variable of the event, guest and workshops which hold the old value of the participants.
// 		let IneventsCount = parRows[0]["TotalInertia"];
// 		let SweventsCount = parRows[0]["TotalSwoosh"];
// 		let TotalEvents = parRows[0]["TotalEvents"]
// 		let workshopsCount = parRows[0]["TotalWorkshops"];
// 		let guestsCount = parRows[0]["TotalGuests"];
// 		let virtualCount = parRows[0]["TotalVirtualShowdown"]
// 		console.log("InEventCount before: " + IneventsCount);
// 		console.log("SwEventCount before: " + SweventsCount);
// 		console.log("EventCount before: " + TotalEvents);
// 		console.log("Virtualshowdowncount before: " + virtualCount);
// 		const date = new Date(
// 			new Date().toLocaleString("en-us", {
// 				timeZone: "Asia/Calcutta",
// 			})
// 		);
// 		const timestamp = `${date.getFullYear()}-${(
// 			"0" +
// 			(date.getMonth() + 1)
// 		).slice(-2)}-${("0" + date.getDate()).slice(-2)} ${(
// 			"0" + date.getHours()
// 		).slice(-2)}:${("0" + date.getMinutes()).slice(-2)}:${(
// 			"0" + date.getSeconds()
// 		).slice(-2)}`;
// 		console.log(timestamp);
// 		// Extract date component

// 		// Increment the value of variable according to the category.
// 		if (["IN"].includes(eventCode.substring(0, 2))) {
// 			option == "inc" ? (IneventsCount++, TotalEvents++) : (IneventsCount--, TotalEvents--);
// 			// Call updateCoins function for IN events
// 			// deduct query
// 			// console.log(option=="inc");
// 			if((option == "inc")==true){
// 			const qr = `
// 			INSERT INTO DigitalWallet (EventCode,ParticipantID,PointsInserted,Timestamp) VALUES ('${eventCode}','${participantID}',200,'${timestamp}')`
// 			console.log(qr)
// 			const [updateCoinRows, updateCoinFields] = await conn.execute(
// 				qr
// 			);
// 			}
// 			if((option=="inc")==false){
// 				const qr = `INSERT INTO DigitalWallet (EventCode,ParticipantID,PointsReturned,Timestamp) VALUES ('${eventCode}','${participantID}',200,'${timestamp}')`
// 				console.log(qr)
// 				const [updateCoinRows, updateCoinFields] = await conn.execute(
// 					qr
// 				);
// 				}
// 		} else if (["SW"].includes(eventCode.substring(0, 2))) {
// 			option == "inc" ? (SweventsCount++, TotalEvents++) : (SweventsCount--, TotalEvents--);
// 			if((option == "inc")==true){
// 				const qr = `
// 				INSERT INTO DigitalWallet (EventCode,ParticipantID,PointsInserted,Timestamp) VALUES ('${eventCode}','${participantID}',200,'${timestamp}')`
// 				console.log(qr)
// 				const [updateCoinRows, updateCoinFields] = await conn.execute(
// 					qr
// 				);
// 				}
// 				if((option=="inc")==false){
// 					const qr = `INSERT INTO DigitalWallet (EventCode,ParticipantID,PointsReturned,Timestamp) VALUES ('${eventCode}','${participantID}',200,'${timestamp}')`
// 					console.log(qr)
// 					const [updateCoinRows, updateCoinFields] = await conn.execute(
// 						qr
// 					);
// 					}
// 		}
// 		else if (["VS"].includes(eventCode.substring(0, 2))) {
// 			option == "inc" ? (virtualCount++, TotalEvents++) : (virtualCount--, TotalEvents--);
// 			if((option == "inc")==true){
// 				const qr = `
// 				INSERT INTO DigitalWallet (EventCode,ParticipantID,PointsInserted,Timestamp) VALUES ('${eventCode}','${participantID}',200,'${timestamp}')`
// 				console.log(qr)
// 				const [updateCoinRows, updateCoinFields] = await conn.execute(
// 					qr
// 				);
// 				}
// 				if((option=="inc")==false){
// 					const qr = `INSERT INTO DigitalWallet (EventCode,ParticipantID,PointsReturned,Timestamp) VALUES ('${eventCode}','${participantID}',200,'${timestamp}')`
// 					console.log(qr)
// 					const [updateCoinRows, updateCoinFields] = await conn.execute(
// 						qr
// 					);
// 					}
// 		}
// 		else if (["KK"].includes(eventCode.substring(0, 2))) {
// 			option == "inc" ? workshopsCount++ : workshopsCount--;
// 			if((option == "inc")==true){
// 				const qr = `
// 				INSERT INTO DigitalWallet (EventCode,ParticipantID,PointsInserted,Timestamp) VALUES ('${eventCode}','${participantID}',1000,'${timestamp}')`
// 				console.log(qr)
// 				const [updateCoinRows, updateCoinFields] = await conn.execute(
// 					qr
// 				);
// 				}


// 		} else if (["EQ"].includes(eventCode.substring(0, 2))) {
// 			option == "inc" ? guestsCount++ : guestsCount--;
// 		}

// 		console.log("InEventCount after: " + IneventsCount);
// 		console.log("SwEventCount after: " + SweventsCount);
// 		console.log("EventCount after: " + TotalEvents);
// 		console.log("Virtualshowdowncount after: " + virtualCount);
// 		// Update Query
// 		const [updateParRows, updateParFields] = await conn.execute(
// 			`UPDATE Participants SET TotalInertia = ${IneventsCount},TotalSwoosh = ${SweventsCount},TotalEvents=${TotalEvents},TotalVirtualShowdown=${virtualCount}, TotalWorkshops = ${workshopsCount}, TotalGuests = ${guestsCount} WHERE ParticipantID = '${participantID}'`
// 		);

// 		// Return if Updated Successfully...
// 		if (updateParRows) {
// 			return true;
// 		} else {
// 			return false;
// 		}
// 	} else {
// 		return false;
// 	}
// }
//new code for calc total events
async function updateRegCountNew(conn, eventCode, participantID) {
	try {

		const [totalRows, totalFields] = await conn.execute(`SELECT 
     'Total' AS RegistrationType,
    COALESCE(SUM(INCountSolo), 0) AS TotalINCount,
    COALESCE(SUM(SWCountSolo), 0) AS TotalSWCount,
    COALESCE(SUM(VSCountSolo), 0) AS TotalVSCount,
	COALESCE(SUM(KKTCountSolo), 0) AS TotalKKTCount,
    COALESCE(SUM(KKNTCountSolo), 0) AS TotalKKNTCount,
    COALESCE(SUM(EQCountSolo), 0) AS TotalEQCount
FROM (
    SELECT 
        'Solo' AS RegistrationType,
        SUM(CASE WHEN EventCode LIKE 'IN%' THEN 1 ELSE 0 END) AS INCountSolo,
        SUM(CASE WHEN EventCode LIKE 'SW%' THEN 1 ELSE 0 END) AS SWCountSolo,
        SUM(CASE WHEN EventCode LIKE 'VS%' THEN 1 ELSE 0 END) AS VSCountSolo,
		SUM(CASE WHEN EventCode LIKE 'KK%NT'  THEN 1 ELSE 0 END) AS KKNTCountSolo,
		SUM(CASE WHEN EventCode LIKE 'KK%' AND EventCode NOT LIKE 'KK%NT' THEN 1 ELSE 0 END) AS KKTCountSolo,
		SUM(CASE WHEN EventCode LIKE 'EQ%' THEN 1 ELSE 0 END) AS EQCountSolo
    FROM SoloRegistration
    WHERE ParticipantID = ?

    UNION ALL

		SELECT
        'Team' AS RegistrationType,
        SUM(CASE WHEN EventCode LIKE 'IN%' THEN 1 ELSE 0 END) AS INCountTeam,
        SUM(CASE WHEN EventCode LIKE 'SW%' THEN 1 ELSE 0 END) AS SWCountTeam,
        SUM(CASE WHEN EventCode LIKE 'VS%' THEN 1 ELSE 0 END) AS VSCountTeam,
		SUM(CASE WHEN EventCode LIKE 'KK%NT'  THEN 1 ELSE 0 END) AS KKNTCountTeam,
        SUM(CASE WHEN EventCode LIKE 'KK%' AND EventCode NOT LIKE 'KK%NT' THEN 1 ELSE 0 END) AS KKTCountTeam,
		SUM(CASE WHEN EventCode LIKE 'EQ%' THEN 1 ELSE 0 END) AS EQCountTeam
    FROM TeamRegistration
    WHERE ParticipantID = ?
) AS subquery`, [participantID, participantID]);
		// console.log(totalRows[0].TotalINCount);
		console.log(totalRows);

		let TotalInertia = Number(totalRows[0].TotalINCount);
		let TotalSwoosh = Number(totalRows[0].TotalSWCount);
		let TotalVirtualShowdown = Number(totalRows[0].TotalVSCount);
		let guestsCount = Number(totalRows[0].TotalEQCount);
		let WorkshopNonTech = Number(totalRows[0].TotalKKNTCount);
		let WorkshopTech = Number(totalRows[0].TotalKKTCount);

		console.log("Inertia", TotalInertia);
		console.log("Swoosh", TotalSwoosh);
		console.log("VirtualShowdown", TotalVirtualShowdown);

		let TotalEvents = TotalVirtualShowdown + TotalSwoosh + TotalInertia;
		console.log("totalevents", TotalEvents);

		let workshopsCount = WorkshopNonTech + WorkshopTech;
		console.log("totalworkshops", workshopsCount);
		console.log("totalworkshopsNT", WorkshopNonTech);
		console.log("totalworkshopsT", WorkshopTech);
		console.log("totalGuest", guestsCount);


		const [updateParRows, updateParFields] = await conn.execute(
			`UPDATE Participants SET TotalInertia = ${TotalInertia},TotalSwoosh = ${TotalSwoosh},TotalEvents=${TotalEvents},TotalVirtualShowdown=${TotalVirtualShowdown}, TotalWorkshops = ${workshopsCount}, TotalGuests = ${guestsCount} WHERE ParticipantID = '${participantID}'`
		);
		if (updateParRows) {
			return true;
		}
		else {
			return false;
		}
	}

	catch (error) {
		console.error(error);
		return false;
		// Handle the error appropriately
	}
}




// =========================== Registration Count Update +1 Ends ===========================

// =========================== Solo Registration Starts ===========================

async function registerSoloEvent(conn, eventCode, participantID) {
	/*

  Registration of Solo Event
  
  Logic:
  1. Check whether the participant already registered in that event of not
  2. If Registered, will return the already registered message.
  3. Else, will Insert the Record in `SoloRegistration` table.
  4. Update the 'TotalEventCount' and other in Participant Table by calling ->updateRegCount()<- function.

  */

	// const registrationStatus = await checkEvent(conn, eventCode, participantID);

	// Handle registration status


	if (closedEvents.includes(eventCode)) {
		return {
			code: 500,
			message: "Registration Will Open Soon",
			type: "info",
		};
	}

	const date = new Date(
		new Date().toLocaleString("en-us", {
			timeZone: "Asia/Calcutta",
		})
	);
	const timestamp = `${date.getFullYear()}-${(
		"0" +
		(date.getMonth() + 1)
	).slice(-2)}-${("0" + date.getDate()).slice(-2)} ${(
		"0" + date.getHours()
	).slice(-2)}:${("0" + date.getMinutes()).slice(-2)}:${(
		"0" + date.getSeconds()
	).slice(-2)}`;

	// Checking
	const [checkRegRows, checkRegFields] = await conn.execute(
		`SELECT * FROM SoloRegistration WHERE EventCode = '${eventCode}' AND ParticipantID = '${participantID}'`
	);

	if (checkRegRows.length > 0) {

		return { code: 200, message: "Already Registered", type: "success" };
	} else {
		//insert into
		const [soloRegisterRows, soloRegisterFields] = await conn.execute(
			`INSERT INTO SoloRegistration (ParticipantID, EventCode, Timestamp) VALUES ('${participantID}', '${eventCode}', '${timestamp}')`
		);

		if (soloRegisterRows) {

			if (
				//dw coins insert

				//update events
				(await updateRegCountNew(conn, eventCode, participantID)) &&
				(await updateEventRegistrationCount(conn, eventCode))


			) {

				if (eventCode.includes('IN') || eventCode.includes('SW') || eventCode.includes('VS')) {
					await updateDWInsert(conn, participantID, eventCode, 200);
					return {
						code: 200,
						message: "Registration Successful...",
						type: "success",
					};
				}
				let coins=0;
				if (eventCode.includes('KK') || eventCode.includes('EQ')) {
					if(eventCode.includes('NT') && eventCode.includes('KK')){
						coins = 300;
					}
					if(eventCode.includes('KK') && !eventCode.includes('NT')){
						coins = 200;
					}
					if(eventCode.includes('EQ')){
						coins=0;
					}
					await updateDWReturn(conn, participantID, eventCode, coins);
					return {
						code: 200,
						message: "Registration Successful...",
						type: "success",
					};
				}

				else {

					return { code: 403, message: 'Event doesnt exist', type: 'error' }
				}



			}

			return {
				code: 500,
				message: "RegistrationCountNotUpdated",
				type: "error",
			};
		}
		return { code: 500, message: "SQL Insert Error", type: "error" };
	}
}



// =========================== Solo Registration Ends  ===========================

// =========================== Generate TeamID Starts ===========================

async function genTeamID(conn, eventCode) {
	let teamID = "";

	const [fetchTeamsRows, fetchTeamsFields] = await conn.execute(
		`SELECT * FROM Teams WHERE EventCode = '${eventCode}' order by TeamID desc`
	);

	if (fetchTeamsRows.length > 0) {
		const no = parseInt(fetchTeamsRows[0]["TeamID"].split("_")[2]) + 1;
		console.log(no);
		let teamNo = "";
		if (0 < no && no <= 9) {
			teamNo = "00" + no;
		} else if (9 < no && no <= 99) {
			teamNo = "0" + no;
		} else if (99 < no && no <= 999) {
			teamNo = "" + no + "";
		}
		teamID = eventCode + "_" + teamNo;

	} else {
		teamID = eventCode + "_" + "001";
	}

	console.log(teamID)

	return teamID;
}

// =========================== Generate TeamID Ends ===========================

// =========================== Create Team Starts ===========================

async function createTeam(conn, eventCode, participantID, teamName) {

	if (closedEvents.includes(eventCode)) {
		return {
			code: 500,
			message: "Registration Will Open Soon",
			type: "Info",
		};
	}

	const date = new Date(
		new Date().toLocaleString("en-us", {
			timeZone: "Asia/Calcutta",
		})
	);
	const timestamp = `${date.getFullYear()}-${(
		"0" +
		(date.getMonth() + 1)
	).slice(-2)}-${("0" + date.getDate()).slice(-2)} ${(
		"0" + date.getHours()
	).slice(-2)}:${("0" + date.getMinutes()).slice(-2)}:${(
		"0" + date.getSeconds()
	).slice(-2)}`;

	const [checkTeamRows, checkTeamFields] = await conn.execute(
		`SELECT Count(TeamName) as count from Teams where TeamName = '${teamName}'`
	);

	const [eventRow, eventFields] = await conn.execute(
		`SELECT * FROM Events WHERE EventCode = '${eventCode}'`
	);

	console.log(eventRow.length);
	console.log(eventRow[0]);

	if (checkTeamRows[0]["count"] > 0) {
		return {
			code: 500,
			message: "Team Already Exists...",
			type: "error",
		};
	} else if (
		eventRow.length > 0 &&
		eventRow[0].TotalRegistration >= eventRow[0].MaxRegistration
	) {
		return {
			code: 500,
			message:
				"This Event Registrations is at its peak.\nPlease continue registering in another event of your interest",
			type: "error",
		};
	} else {
		const teamID = await genTeamID(conn, eventCode);
		console.log(teamID);

		const [insertTeamRows, insertTeamFields] = await conn.execute(
			`INSERT INTO Teams (TeamID, TeamName, EventCode, Timestamp) VALUES ('${teamID}', '${teamName}', '${eventCode}', '${timestamp}')`
		);

		if (insertTeamRows) {
			const [insertParRows, insertParFields] = await conn.execute(
				`INSERT INTO TeamRegistration (TeamID, ParticipantID, Role, Timestamp, EventCode) VALUES ('${teamID}', '${participantID}', 'Leader', '${timestamp}', '${eventCode}')`
			);
			console.log("isda");

			if (insertParRows) {
				// Update Registration Count
				if (
					(await updateRegCountNew(
						conn,
						eventCode,
						participantID,

					)) &&
					(await updateEventRegistrationCount(conn, eventCode))
				) {
					await updateDWInsert(conn, participantID, eventCode, 200);

					return {
						code: 200,
						message: "Team Created Successfully...",
						type: "success",
						teamID: teamID,
						teamName: teamName,
						mailStatus: "",
					};

				}

				return {
					code: 500,
					message: "Registration Count Not Updated",
					type: "error",
				};
			}
			return {
				code: 500,
				message: "Team ParNotRegistered",
				type: "error",
			};
		}
		return { code: 500, message: "Tream Creation Failed", type: "error" };
	}
}

// =========================== Create Team Ends ===========================

// =========================== Join Team Starts ===========================

async function joinTeam(conn, eventCode, participantID, teamID) {

	if (closedEvents.includes(eventCode)) {
		return {
			code: 500,
			message: "Registration Will Open Soon",
			type: "Info",
		};
	}

	const date = new Date(
		new Date().toLocaleString("en-us", {
			timeZone: "Asia/Calcutta",
		})
	);
	const timestamp = `${date.getFullYear()}-${(
		"0" +
		(date.getMonth() + 1)
	).slice(-2)}-${("0" + date.getDate()).slice(-2)} ${(
		"0" + date.getHours()
	).slice(-2)}:${("0" + date.getMinutes()).slice(-2)}:${(
		"0" + date.getSeconds()
	).slice(-2)}`;

	const [checkTeamExistRows, checkTeamExistFields] = await conn.execute(
		`SELECT Count(TeamID) as count FROM Teams WHERE TeamID = '${teamID}' and EventCode = '${eventCode}'`
	);

	if (checkTeamExistRows[0]["count"] > 0) {
		const [countRows, countFields] = await conn.execute(
			`select count(TeamID) as count from TeamRegistration where TeamID = '${teamID}'`
		);

		const [headCountRows, headCountFields] = await conn.execute(
			`SELECT HeadCount FROM Events WHERE EventCode = '${eventCode}'`
		);

		if (countRows.length > 0 && headCountRows.length > 0) {
			if (countRows[0].count >= headCountRows[0].HeadCount) {
				return {
					code: 200,
					message:
						"You Can't Join!!\nMaximum Capacity of Team reached...",
					type: "error",
				};
			}
		}

		console.log(
			`SELECT Count(RegisterID) AS Count FROM TeamRegistration WHERE TeamID LIKE '${eventCode}%' AND ParticipantID = '${participantID}'`
		);
		const [checkExistRows, checkExistFields] = await conn.execute(
			`SELECT Count(RegisterID) AS Count FROM TeamRegistration WHERE TeamID LIKE '${eventCode}%' AND ParticipantID = '${participantID}'`
		);

		if (checkExistRows[0]["Count"] > 0) {
			return { code: 200, message: "AlreadyRegistered", type: "error" };
		} else {
			const [insertTRRows, insertTRFields] = await conn.execute(
				`INSERT INTO TeamRegistration (TeamID, ParticipantID, Role, Timestamp, EventCode) VALUES ('${teamID}', '${participantID}', 'Member', '${timestamp}', '${eventCode}')`
			);

			if (insertTRRows) {
				// Update Registration Count
				if (
					(await updateRegCountNew(
						conn,
						eventCode,
						participantID,

					)) == true
				) {
					await updateDWInsert(conn, participantID, eventCode, 200);
					return {
						code: 200,
						message: "Team Registration Complete",
						type: "success",
					};
				}

				return {
					code: 500,
					message: "RegistrationCountNotUpdated",
					type: "error",
				};
			}
			return { code: 500, message: "Team not joined", type: "error" };
		}
	}
	return { code: 500, message: "Team not found...", type: "error" };
}

// =========================== Join Team Ends ===========================

async function getTeamInfo(conn, teamID) {
	const [checkTeamExistRows, checkTeamExistFields] = await conn.execute(
		`select Teams.TeamName, TeamRegistration.ParticipantID from Teams inner join TeamRegistration on Teams.TeamID = TeamRegistration.TeamID where Teams.TeamID="${teamID}" and TeamRegistration.Role = 'Leader';`
	);

	if (checkTeamExistRows.length > 0) {
		const [parNameRows, parNameFields] = await conn.execute(
			`select Firstname, Lastname from Participants where ParticipantID = '${checkTeamExistRows[0].ParticipantID}'`
		);

		if (parNameRows.length > 0) {
			return {
				code: 200,
				resMessage: {
					type: "success",
					message: "Information fetched successfully",
					teamName: checkTeamExistRows[0].TeamName,
					teamLeader:
						parNameRows[0].Firstname +
						" " +
						parNameRows[0].Lastname,
				},
			};
		} else {
			return {
				code: 500,
				resMessage: {
					type: "error",
					message: "Information fetched successfully",
					teamName: checkTeamExistRows[0].TeamName,
					teamLeader: "Not Found",
				},
			};
		}
	} else {
		return {
			code: 500,
			resMessage: {
				type: "error",
				message: "Team Not Found...",
			},
		};
	}
}

// Exporting All Modules...
module.exports = {
	checkEvent,
	updateEventRegistrationCount,
	registerSoloEvent,
	createTeam,
	joinTeam,
	getTeamInfo,
	getEvents,
	deleteEvent,
	getTeamMembers,
	removeTeamMember,
	fetchDigitalWalletData
};
Leave a Comment