<?php session_start(); ?>
<?php
	include("includes/connect.php");

	//secure the page to only Admins and Organizers and Users
	if(!isset($_SESSION['userType']) || ($_SESSION['userType']!="Admin" && $_SESSION['userType']!="Organizer" && $_SESSION['userType']!="User")){
		echo "<script>location.href='index.php?err=rights';</script>";
	}

	// ── AJAX POST handler ──────────────────────────────────────────────────
	// If this is a POST request, handle registration and return JSON, then exit.
	if($_SERVER['REQUEST_METHOD'] === 'POST'){
		header('Content-Type: application/json');

		$userid  = intval($_SESSION['id']);
		$eventid = isset($_POST['event_id']) ? intval($_POST['event_id']) : 0;

		if($eventid <= 0){
			echo json_encode(["success" => false, "message" => "Please select a valid event."]);
			exit;
		}

		// Verify event is not full and user isn't already registered
		$checkSql = "SELECT e.id FROM events e WHERE e.id=$eventid AND (e.max IS NULL OR (SELECT COUNT(*) FROM participants p WHERE p.event=e.id) < e.max) AND e.id NOT IN (SELECT event FROM participants WHERE user=$userid)";
		$checkResult = $smeConn->query($checkSql);

		if($checkResult->num_rows === 0){
			echo json_encode(["success" => false, "message" => "Event is unavailable or you are already registered."]);
			exit;
		}

		$insertSql = "INSERT INTO participants (user, event) VALUES ($userid, $eventid)";
		if($smeConn->query($insertSql)){
			echo json_encode(["success" => true, "message" => "Successfully registered for the event!"]);
		} else {
			echo json_encode(["success" => false, "message" => "Failed: " . $smeConn->error]);

		}
		exit;
	}

	// Fetch logged-in user's info for pre-filling the form
	$userInfo = null;
	if(isset($_SESSION['id'])){
		$userid = intval($_SESSION['id']);
		$userSql = "SELECT first, last, email, phone FROM users WHERE id=$userid";
		$userResult = $smeConn->query($userSql);
		if($userResult && $userResult->num_rows > 0){
			$userInfo = $userResult->fetch_assoc();
		}
	}
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>SignMeUp - Event Management - Participant Home</title>
	<?php include("includes/head.php"); ?>
  </head>
  <body>
  <header>
   <?php include("includes/nav.php"); ?>
</header>
<main role="main" class="container">
	<div class="row">
		<div class="col-8">
			<h3>Participant Home</h3>
		    <?php
				if(isset($_SESSION['id'])){
					$userid=$_SESSION['id'];
					$sql="select events.id, events.name, events.time, events.location, events.date, participants.event from participants, events where participants.user=$userid AND participants.event=events.id order by events.date, events.time";
					$result=$smeConn->query($sql);
					while($row=$result->fetch_assoc()){
						echo "<h4 class='row'>";
						echo "<div class='col-4'>".$row['name']."</div>";
						echo "<div class='col-4'>".date("m/d/Y", strtotime($row['date'])).", ".date("h:m a", strtotime($row['time']))."</div>";
						echo "<div class='col-4'>".$row['location']."</div>";
						echo "</h4>";
					}
				}//end get if
			?>
		</div><!-- /.col-8 -->

		<aside class="col-4">
			<h3>Register for an Event</h3>
			<div id="register-alert" class="d-none" role="alert"></div>
			<form id="register-form">
				<div class="form-group">
					<label for="reg-first">First Name</label>
					<input type="text" class="form-control" id="reg-first" name="first" value="<?php echo htmlspecialchars($userInfo['first'] ?? ''); ?>" required>
				</div>
				<div class="form-group">
					<label for="reg-last">Last Name</label>
					<input type="text" class="form-control" id="reg-last" name="last" value="<?php echo htmlspecialchars($userInfo['last'] ?? ''); ?>" required>
				</div>
				<div class="form-group">
					<label for="reg-email">Email</label>
					<input type="email" class="form-control" id="reg-email" name="email" value="<?php echo htmlspecialchars($userInfo['email'] ?? ''); ?>" required>
				</div>
				<div class="form-group">
					<label for="reg-phone">Phone</label>
					<input type="tel" class="form-control" id="reg-phone" name="phone" value="<?php echo htmlspecialchars($userInfo['phone'] ?? ''); ?>">
				</div>
				<div class="form-group">
					<label for="reg-event">Event</label>
					<select class="form-control" id="reg-event" name="event_id" required>
						<option value="">-- Select an Event --</option>
						<?php
							if(isset($_SESSION['id'])){
								$userid = intval($_SESSION['id']);
								$eventSql = "SELECT e.id, e.name, e.date, e.time FROM events e WHERE (e.max IS NULL OR (SELECT COUNT(*) FROM participants p WHERE p.event=e.id) < e.max) AND e.id NOT IN (SELECT event FROM participants WHERE user=$userid) ORDER BY e.date, e.time";
								$eventResult = $smeConn->query($eventSql);
								if($eventResult && $eventResult->num_rows > 0){
									while($eRow = $eventResult->fetch_assoc()){
										echo "<option value='".intval($eRow['id'])."'>".htmlspecialchars($eRow['name'])." — ".date("m/d/Y", strtotime($eRow['date']))." ".date("h:i a", strtotime($eRow['time']))."</option>";
									}
								} else {
									echo "<option value='' disabled>No available events</option>";
								}
							}
						?>
					</select>
				</div>
				<button type="submit" class="btn btn-primary" id="register-btn">Register</button>
			</form>
		</aside><!-- /.col-4 -->

	</div><!-- /.row -->
</main><!-- /.container -->

<?php include("includes/footer.php"); ?>

<script>
    document.getElementById('register-form').addEventListener('submit', function(e){
    	e.preventDefault();
    
    	var btn     = document.getElementById('register-btn');
    	var eventId = document.getElementById('reg-event').value;
    
    	if(!eventId){
    		showAlert('warning', 'Please select an event before registering.');
    		return;
    	}
    
    	btn.disabled = true;
    	btn.textContent = 'Registering…';
    
    	fetch('participant.php', {
    		method: 'POST',
    		body: new FormData(this)
    	})
    	.then(function(response){ return response.json(); })
    	.then(function(data){
    		if(data.success){
    			showAlert('success', data.message);
    			setTimeout(function(){ location.reload(); }, 1200);
    		} else {
    			showAlert('danger', data.message || 'Registration failed. Please try again.');
    			btn.disabled = false;
    			btn.textContent = 'Register';
    		}
    	})
    	.catch(function(){
    		showAlert('danger', 'A network error occurred. Please try again.');
    		btn.disabled = false;
    		btn.textContent = 'Register';
    	});
    });
    
    function showAlert(type, message){
    	var alertBox = document.getElementById('register-alert');
    	alertBox.className = 'alert alert-' + type;
    	alertBox.textContent = message;
    	alertBox.classList.remove('d-none');
    }
    </script>
    
    </body>
</html>
