<?php
if(session_status() === PHP_SESSION_NONE){ session_start(); }
require_once "functions.php";

// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = $login_err = "";

// Processing form data when form is submitted
if(isset($_POST['login'])){
	$username_err = $password_err = $login_err = "";

	// Define variables
	$username = trim($_POST["UName"]);
	$password = trim($_POST["UPassword"]);

    // Check if username is empty
    if (empty($username)) {
        $username_err = "Please enter your username.";
    }

    // Check if password is empty
    if (empty($password)) {
        $password_err = "Please enter your password.";
    }

    // Validate credentials
    if (empty($username_err) && empty($password_err)) {
		$conn = loadDBData();

        // Parameterised: username is bound, never concatenated into SQL.
        $stmt = $conn->prepare("SELECT UId, UName, UEmail, UPassword, URole FROM users WHERE UName = ?");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();

		if ($result->num_rows == 0) {
			$login_err = "Invalid username or password.";		
		} elseif ($result->num_rows > 1) {
			$login_err = "Overlapping username found. Contact Admin!";
		} else {
			$row = $result->fetch_assoc();
			$stmt->close();

			// Accounts awaiting email confirmation must not be able to log in.
			if($row['URole'] === 'pending'){
				$login_err = "Your account is not yet activated. Please check your email for the confirmation link.";
			} elseif(password_verify($password, $row['UPassword'])){
				// Prevent session fixation: issue a fresh session id on login.
				session_regenerate_id(true);

				// Store data in session variables
				$_SESSION["loggedin"] = true;
				$_SESSION["UId"] = $row["UId"];
				$_SESSION["UName"] = $row["UName"];
				$_SESSION["URole"] = $row["URole"];
				
				$DEmail = getDriverEmail($conn, $_SESSION["UId"]);
				if(!empty($DEmail)){
					$_SESSION["UEmail"] = $DEmail;
				}else{
					$_SESSION["UEmail"] = $row["UEmail"];
				}
				
				// Find Driver Name
				$dstmt = $conn->prepare("SELECT DPic, DName, DContact, DClass, DLicense, DLCheck, DFuelCard FROM drivers WHERE DUserID = ?");
				$dstmt->bind_param("i", $_SESSION["UId"]);
				$dstmt->execute();
				$result = $dstmt->get_result();
				if ($result->num_rows == 1) {
					$row = $result->fetch_assoc();
					if(!empty($row["DName"]) && ($row["DName"] !== $_SESSION["UName"])){
						$_SESSION["DName"] = $row["DName"];
					}else{
						$_SESSION["DName"] = $_SESSION["UName"];
					}
				} else {
					$_SESSION["DName"] = $_SESSION["UName"];
				}
				
				// Redirect user to welcome page
				$dstmt->close();
				$conn->close();
				header("Location: index.php");
				exit;
			} else {
				$login_err = "Username / Password mismatched.";
			}	
		}

		$conn->close();
    }
}

// Header output must come AFTER the POST block: it emits HTML, and once any
// output is sent, session_regenerate_id() and the header("Location: ...")
// redirect above both fail silently, leaving a correct login stranded on
// this page with no error shown.
load("loginheader");
?>


<div class="auth-shell">
	<!-- ============ Left: Brand / Marketing Panel ============ -->
	<aside class="auth-brand" aria-hidden="true">
		<div class="auth-brand__glow auth-brand__glow--teal"></div>
		<div class="auth-brand__glow auth-brand__glow--purple"></div>
		<div class="auth-brand__grid"></div>

		<div class="auth-brand__inner">
			<span class="auth-brand__lockup"><img class="auth-brand__mark" src="<?php echo ROOTPATH; ?>img/dbs_logo_clean.png" alt=""></span>
			<h2 class="auth-brand__title">Facilities for<br><span>Film &amp; TV</span></h2>
			<p class="auth-brand__copy">
				Log your shifts, call times and wraps from anywhere on location &mdash;
				and let the office handle the rest.
			</p>

			<ul class="auth-brand__points">
				<li><i class="bi bi-clock-history"></i><span>Shift &amp; overtime tracking</span></li>
				<li><i class="bi bi-truck"></i><span>Vehicle &amp; trailer assignment</span></li>
				<li><i class="bi bi-file-earmark-spreadsheet"></i><span>Payroll-ready summaries</span></li>
			</ul>
		</div>

		<!-- aria-hidden="false" re-exposes just the footer: the surrounding
		     aside is decorative, but the agency link inside must stay reachable
		     to screen readers and the keyboard. -->
		<div class="auth-brand__footer" aria-hidden="false">
			<span>&copy; <?php echo date('Y'); ?> DBS Facilities</span>
			<span class="auth-brand__agency">Business Automation by
				<a href="https://ztream.dev" target="_blank" rel="noopener">Ztream.dev</a></span>
		</div>
	</aside>

	<!-- ============ Right: Login Form ============ -->
	<main class="auth-panel">
		<div class="auth-card">
			<img class="auth-card__logo" src="<?php echo ROOTPATH; ?>img/dbs_logo_clean.png" alt="DBS Facilities">

			<header class="auth-card__head">
				<h1>Welcome back</h1>
				<p>Sign in to your driver portal.</p>
			</header>

			<?php if (!empty($login_err)): ?>
				<div class="auth-alert auth-alert--error" role="alert">
					<i class="bi bi-exclamation-triangle-fill" aria-hidden="true"></i>
					<div><?php echo $login_err; ?></div>
				</div>
			<?php endif; ?>

			<form id="loginForm" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" autocomplete="on" novalidate>
				<div class="auth-field">
					<label for="UName">Username</label>
					<div class="auth-input">
						<i class="bi bi-person" aria-hidden="true"></i>
						<input id="UName" name="UName" type="text"
							class="<?php echo (!empty($username_err)) ? 'is-invalid' : ''; ?>"
							value="<?php echo htmlspecialchars($username); ?>"
							placeholder="Your username" autocomplete="username"
							<?php if(!empty($username_err)) echo 'aria-invalid="true" aria-describedby="UName-err"'; ?>
							required autofocus>
					</div>
					<?php if(!empty($username_err)): ?>
						<p class="auth-err" id="UName-err" role="alert"><?php echo $username_err; ?></p>
					<?php endif; ?>
				</div>

				<div class="auth-field">
					<label for="password">Password</label>
					<div class="auth-input">
						<i class="bi bi-lock" aria-hidden="true"></i>
						<input id="password" name="UPassword" type="password"
							class="<?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>"
							placeholder="Your password" autocomplete="current-password"
							<?php if(!empty($password_err)) echo 'aria-invalid="true" aria-describedby="pw-err"'; ?>
							required>
						<button type="button" class="auth-eye" id="pwToggle"
							aria-label="Show password" aria-pressed="false">
							<i class="bi bi-eye" aria-hidden="true"></i>
						</button>
					</div>
					<?php if(!empty($password_err)): ?>
						<p class="auth-err" id="pw-err" role="alert"><?php echo $password_err; ?></p>
					<?php endif; ?>
				</div>

				<div class="auth-row">
					<a href="recoverpw.php">Forgot password?</a>
				</div>

				<button type="submit" name="login" class="auth-submit">
					<span>Sign In</span>
					<i class="bi bi-arrow-right" aria-hidden="true"></i>
				</button>

				<p class="auth-foot">
					Don't have an account? <a href="register.php">Register now</a>
				</p>
			</form>
		</div>
	</main>
</div>

<script>
(function(){
	var toggle = document.getElementById('pwToggle');
	var field  = document.getElementById('password');
	if (toggle && field) {
		toggle.addEventListener('click', function(){
			var show = field.type === 'password';
			field.type = show ? 'text' : 'password';
			toggle.setAttribute('aria-pressed', show ? 'true' : 'false');
			toggle.setAttribute('aria-label', show ? 'Hide password' : 'Show password');
			toggle.querySelector('i').className = show ? 'bi bi-eye-slash' : 'bi bi-eye';
		});
	}

	// Submit affordance: prevents double-posting on slow connections.
	// IMPORTANT: the submit button is <button type="submit" name="login">, and
	// the PHP handler is gated on isset($_POST['login']). A disabled button is
	// omitted from the POST body, so disabling it *during* the submit event
	// strips "login" and the handler never runs (page just reloads with no
	// error). Defer the disable to the next tick so the browser has already
	// serialised the form — the affordance still fires, the field is still sent.
	var form = document.getElementById('loginForm');
	if (form) {
		form.addEventListener('submit', function(){
			var btn = form.querySelector('.auth-submit');
			if (btn && form.checkValidity()) {
				setTimeout(function(){
					btn.classList.add('is-loading');
					btn.disabled = true;
				}, 0);
			}
		});
	}
})();
</script>
</body>
</html>
