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

	// ── AJAX POST handler ──────────────────────────────────────────────────
	if($_SERVER['REQUEST_METHOD'] === 'POST'){
		header('Content-Type: application/json');

		if(!isset($_SESSION['userType']) || ($_SESSION['userType']!="Admin" && $_SESSION['userType']!="Organizer")){
			echo json_encode(["success" => false, "message" => "Unauthorized"]);
			exit;
		}

		$organizer = intval($_SESSION['id']);

		$name     = isset($_POST['name'])     ? trim($_POST['name'])     : '';
		$location = isset($_POST['location']) ? trim($_POST['location']) : '';
		$address  = isset($_POST['address'])  ? trim($_POST['address'])  : '';
		$date     = isset($_POST['date'])     ? trim($_POST['date'])     : '';
		$time     = isset($_POST['time'])     ? trim($_POST['time'])     : '';
		$max      = isset($_POST['max'])      ? trim($_POST['max'])      : '';

		// Server-side validation
		if(empty($name) || !preg_match("/^[a-zA-Z0-9 '\-]{1,50}$/", $name)){
			echo json_encode(["success" => false, "message" => "Invalid event name."]);
			exit;
		}
		if(empty($location) || !preg_match("/^[a-zA-Z0-9 ',.\-]{1,50}$/", $location)){
			echo json_encode(["success" => false, "message" => "Invalid location."]);
			exit;
		}
		if(empty($address) || !preg_match("/^[a-zA-Z0-9 ',.\-#]{1,150}$/", $address)){
			echo json_encode(["success" => false, "message" => "Invalid address."]);
			exit;
		}
		if(empty($date) || !preg_match("/^\d{4}-\d{2}-\d{2}$/", $date)){
			echo json_encode(["success" => false, "message" => "Invalid date."]);
			exit;
		}
		if(empty($time) || !preg_match("/^\d{2}:\d{2}$/", $time)){
			echo json_encode(["success" => false, "message" => "Invalid time."]);
			exit;
		}

		$maxVal = NULL;
		if($max !== ''){
			if(!ctype_digit($max)){
				echo json_encode(["success" => false, "message" => "Max participants must be a whole number."]);
				exit;
			}
			$maxVal = intval($max);
		}

		$nameStripped = str_replace([' ', "'", '-'], '', $name);
		if(!ctype_alnum($nameStripped)){
			echo json_encode(["success" => false, "message" => "Event name contains invalid characters."]);
			exit;
		}

		$name     = $smeConn->real_escape_string($name);
		$location = $smeConn->real_escape_string($location);
		$address  = $smeConn->real_escape_string($address);
		$date     = $smeConn->real_escape_string($date);
		$time     = $smeConn->real_escape_string($time);
		$maxSql   = ($maxVal !== NULL) ? $maxVal : "NULL";

		$insertSql = "INSERT INTO events (name, location, address, date, time, max, organizer) VALUES ('$name', '$location', '$address', '$date', '$time', $maxSql, $organizer)";

		if($smeConn->query($insertSql)){
			$newId = $smeConn->insert_id;
			echo json_encode([
				"success" => true,
				"message" => "Event created successfully!",
				"event"   => [
					"id"       => $newId,
					"name"     => htmlspecialchars($_POST['name']),
					"location" => htmlspecialchars($_POST['location']),
					"date"     => $_POST['date'],
					"time"     => $_POST['time']
				]
			]);
		} else {
			echo json_encode(["success" => false, "message" => "Failed: " . $smeConn->error]);
		}
		exit;
	}
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Jekyll v3.8.6">
    <title>SignMeUp - Event Management - Admin Home</title>
	<?php include("includes/head.php"); ?>
	<?php include("includes/connect.php"); ?>
  </head>
  <body>
  <header>
   <?php include("includes/nav.php"); ?>
</header>
<main role="main" class="container" >
	<div class="row">
		<div class="col-8">
			<h3>Organizer Home</h3>
			<!--
				On the organizer page show a list of all the events that the 
				person is organizing with a list of participants in alphabetical 
				order.   
			-->
			<div id="events-list">
			<?php
				if(isset($_SESSION['id'])){
					$userid=$_SESSION['id'];
					$sql="select * from events where organizer=$userid order by date, time";
					$result=$smeConn->query($sql);
					while($row=$result->fetch_assoc()){
						echo "<div class='row' id='event-".$row['id']."'>";
						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['name']."</div>";
						echo "<div class='col-4'>".$row['location']."</div>";
						echo "</div>";

						$eventid=$row['id'];
						$partSql="select participants.user, users.last, users.first from participants, users where participants.event=$eventid and users.id=participants.user order by users.last, users.first";
						$partRes=$smeConn->query($partSql);
						echo "<ol id='participants-".$eventid."'>";
						while($partRow=$partRes->fetch_assoc()){
							echo "<li class='row'>";
							echo "<span class='col-12'>".$partRow['last'].", ".$partRow['first']."</span>";
							echo "</li>";
						}
						echo "</ol>";
					}
				}//end get if
			?>
			</div>
		</div><!-- /.col-8 -->

		<aside class="col-4">
			<h3>Create New Event</h3>
			<div id="event-alert" class="d-none" role="alert"></div>
			<form id="event-form">
				<div class="form-group">
					<label for="ev-name">Event Name</label>
					<input type="text" class="form-control" id="ev-name" name="name" maxlength="50" required>
					<small class="form-text text-danger d-none" id="err-name">Letters, numbers, spaces, hyphens and apostrophes only.</small>
				</div>
				<div class="form-group">
					<label for="ev-location">Location</label>
					<input type="text" class="form-control" id="ev-location" name="location" maxlength="50" required>
					<small class="form-text text-danger d-none" id="err-location">Letters, numbers, spaces and basic punctuation only.</small>
				</div>
				<div class="form-group">
					<label for="ev-address">Address</label>
					<input type="text" class="form-control" id="ev-address" name="address" maxlength="150" required>
					<small class="form-text text-danger d-none" id="err-address">Letters, numbers, spaces and basic punctuation only.</small>
				</div>
				<div class="form-group">
					<label for="ev-date">Date</label>
					<input type="date" class="form-control" id="ev-date" name="date" required>
					<small class="form-text text-danger d-none" id="err-date">Please enter a valid date.</small>
				</div>
				<div class="form-group">
					<label for="ev-time">Time</label>
					<input type="time" class="form-control" id="ev-time" name="time" required>
					<small class="form-text text-danger d-none" id="err-time">Please enter a valid time.</small>
				</div>
				<div class="form-group">
					<label for="ev-max">Max Participants <small class="text-muted">(optional)</small></label>
					<input type="number" class="form-control" id="ev-max" name="max" min="1">
					<small class="form-text text-danger d-none" id="err-max">Must be a positive whole number.</small>
				</div>
				<button type="submit" class="btn btn-primary" id="event-btn">Create Event</button>
			</form>
		</aside><!-- /.col-4 -->

	</div><!-- /.row -->
</main><!-- /.container -->
<?php include("includes/footer.php"); ?>

<script>
var patterns = {
	name:     /^[a-zA-Z0-9 '\-]{1,50}$/,
	location: /^[a-zA-Z0-9 ',.\-]{1,50}$/,
	address:  /^[a-zA-Z0-9 ',.\-#]{1,150}$/,
	max:      /^\d+$/
};

function validateField(id, pattern){
	var input = document.getElementById(id);
	var err   = document.getElementById('err-' + id.replace('ev-', ''));
	var val   = input.value.trim();

	if(id === 'ev-max' && val === '') return true;

	if(val === '' || (pattern && !pattern.test(val))){
		input.classList.add('is-invalid');
		if(err) err.classList.remove('d-none');
		return false;
	} else {
		input.classList.remove('is-invalid');
		if(err) err.classList.add('d-none');
		return true;
	}
}

document.getElementById('ev-name').addEventListener('blur',     function(){ validateField('ev-name',     patterns.name); });
document.getElementById('ev-location').addEventListener('blur', function(){ validateField('ev-location', patterns.location); });
document.getElementById('ev-address').addEventListener('blur',  function(){ validateField('ev-address',  patterns.address); });
document.getElementById('ev-date').addEventListener('blur',     function(){ validateField('ev-date',     null); });
document.getElementById('ev-time').addEventListener('blur',     function(){ validateField('ev-time',     null); });
document.getElementById('ev-max').addEventListener('blur',      function(){ validateField('ev-max',      patterns.max); });

document.getElementById('event-form').addEventListener('submit', function(e){
	e.preventDefault();

	var valid = true;
	valid = validateField('ev-name',     patterns.name)     && valid;
	valid = validateField('ev-location', patterns.location) && valid;
	valid = validateField('ev-address',  patterns.address)  && valid;
	valid = validateField('ev-date',     null)              && valid;
	valid = validateField('ev-time',     null)              && valid;
	valid = validateField('ev-max',      patterns.max)      && valid;

	if(!valid) return;

	var btn = document.getElementById('event-btn');
	btn.disabled = true;
	btn.textContent = 'Creating…';

	fetch('organizer.php', {
		method: 'POST',
		body: new FormData(this)
	})
	.then(function(response){ return response.json(); })
	.then(function(data){
		if(data.success){
			showAlert('success', data.message);
			document.getElementById('event-form').reset();
			document.querySelectorAll('.is-invalid').forEach(function(el){ el.classList.remove('is-invalid'); });
			appendEvent(data.event);
		} else {
			showAlert('danger', data.message || 'Could not create event. Please try again.');
		}
		btn.disabled = false;
		btn.textContent = 'Create Event';
	})
	.catch(function(){
		showAlert('danger', 'A network error occurred. Please try again.');
		btn.disabled = false;
		btn.textContent = 'Create Event';
	});
});

function appendEvent(ev){
	var list = document.getElementById('events-list');

	var dateParts = ev.date.split('-');
	var formatted_date = dateParts[1] + '/' + dateParts[2] + '/' + dateParts[0];

	var timeParts = ev.time.split(':');
	var hours = parseInt(timeParts[0]);
	var minutes = timeParts[1];
	var ampm = hours >= 12 ? 'pm' : 'am';
	hours = hours % 12 || 12;
	var formatted_time = (hours < 10 ? '0' + hours : hours) + ':' + minutes + ' ' + ampm;

	var row = document.createElement('div');
	row.className = 'row';
	row.id = 'event-' + ev.id;
	row.innerHTML =
		'<div class="col-4">' + formatted_date + ', ' + formatted_time + '</div>' +
		'<div class="col-4">' + ev.name + '</div>' +
		'<div class="col-4">' + ev.location + '</div>';
	list.appendChild(row);

	var ol = document.createElement('ol');
	ol.id = 'participants-' + ev.id;
	list.appendChild(ol);
}

function showAlert(type, message){
	var alertBox = document.getElementById('event-alert');
	alertBox.className = 'alert alert-' + type;
	alertBox.textContent = message;
	alertBox.classList.remove('d-none');
}
</script>

</body>
</html>