<?php
	require_once('session.php');
	require_once('dbconfig.php');
	require_once('dbconfig2.php');
	
	//Time & Date
	date_default_timezone_set ("Africa/Lagos");
	$DATE_NOW 			= date("D d M Y");
	$TIME_NOW 			= date("h:i:s A", time()); // 12:45:00 AM
	$datetimeFormat 	= 'D d M Y h:i:s A';
	
	//Login Token
	$email_token = openssl_random_pseudo_bytes(5);
	$token 			   = bin2hex($email_token);
	
	
	//Temperory Password
	$temp_password 	   = mt_rand(1, 99999);
	
	//Rand Numbers
	$rand 		 		= mt_rand(1, 99999)."-".mt_rand(1, 99999)."-".mt_rand(1, 99999);
	$rand_t 		 	= mt_rand(1, 999)."-".mt_rand(1, 999)."-".mt_rand(1, 999)."-".mt_rand(1, 999);
	
	//Saved Admin Session Details with proper checks
	$SESS_ID_ADMIN				  =	isset($_SESSION['SESS_ID_ADMIN']) ? $_SESSION['SESS_ID_ADMIN'] : null;
	$SESS_FULLNAME_ADMIN		  = isset($_SESSION['SESS_FULLNAME_ADMIN']) ? $_SESSION['SESS_FULLNAME_ADMIN'] : null;
	$SESS_EMAIL_ADMIN			  =	isset($_SESSION['SESS_EMAIL_ADMIN']) ? $_SESSION['SESS_EMAIL_ADMIN'] : null;
	$SESS_USERNAME_ADMIN		  =	isset($_SESSION['SESS_USERNAME_ADMIN']) ? $_SESSION['SESS_USERNAME_ADMIN'] : null;
	$SESS_PASSWORD_ADMIN		  =	isset($_SESSION['SESS_PASSWORD_ADMIN']) ? $_SESSION['SESS_PASSWORD_ADMIN'] : null;
	$SESS_PHOTO_ADMIN			  =	isset($_SESSION['SESS_PHOTO_ADMIN']) ? $_SESSION['SESS_PHOTO_ADMIN'] : null;
	$SESS_REGISTRATION_DATE_ADMIN =	isset($_SESSION['SESS_REGISTRATION_DATE_ADMIN']) ? $_SESSION['SESS_REGISTRATION_DATE_ADMIN'] : null;
	$SESS_ACCESS_LEVEL_ADMIN	  =	isset($_SESSION['SESS_ACCESS_LEVEL_ADMIN']) ? $_SESSION['SESS_ACCESS_LEVEL_ADMIN'] : null;
	$SESS_HASH_ADMIN			  =	isset($_SESSION['SESS_HASH_ADMIN']) ? $_SESSION['SESS_HASH_ADMIN'] : null;
	$SESS_STATUS_ADMIN			  = isset($_SESSION['SESS_STATUS_ADMIN']) ? $_SESSION['SESS_STATUS_ADMIN'] : null;
	$SESS_TOKEN_ADMIN			  =	isset($_SESSION['SESS_TOKEN_ADMIN']) ? $_SESSION['SESS_TOKEN_ADMIN'] : null;
	
	
	//Saved User Session Details with proper checks
	$SESS_ID_USER			  	  = isset($_SESSION['SESS_ID']) ? $_SESSION['SESS_ID'] : null;
	$SESS_PROFILE_PIC_USER  	  = isset($_SESSION['SESS_PROFILE_PIC']) ? $_SESSION['SESS_PROFILE_PIC'] : null;
	$SESS_FULLNAME_USER  		  = isset($_SESSION['SESS_FULLNAME']) ? $_SESSION['SESS_FULLNAME'] : null;
	$SESS_EMAIL_USER 			  = isset($_SESSION['SESS_EMAIL']) ? $_SESSION['SESS_EMAIL'] : null;
	$SESS_PASSWORD_USER 	 	  = isset($_SESSION['SESS_PASSWORD']) ? $_SESSION['SESS_PASSWORD'] : null;
	$SESS_GENDER_USER 	  		  = isset($_SESSION['SESS_GENDER']) ? $_SESSION['SESS_GENDER'] : null;
	$SESS_CLASS_USER 		  	  = isset($_SESSION['SESS_CLASS']) ? $_SESSION['SESS_CLASS'] : null;
	$SESS_SUBCLASS_USER 	  	  = isset($_SESSION['SESS_SUBCLASS']) ? $_SESSION['SESS_SUBCLASS'] : null;
	$SESS_SUBJECT_USER 	  		  = isset($_SESSION['SESS_SUBJECT']) ? $_SESSION['SESS_SUBJECT'] : null;
	$SESS_PHONE_USER 			  = isset($_SESSION['SESS_PHONE']) ? $_SESSION['SESS_PHONE'] : null;
	$SESS_COUNTRY_USER 			  = isset($_SESSION['SESS_COUNTRY']) ? $_SESSION['SESS_COUNTRY'] : null;
	$SESS_REGISTRATION_DATE_USER  = isset($_SESSION['SESS_REGISTRATION_DATE']) ? $_SESSION['SESS_REGISTRATION_DATE'] : null;
	$SESS_ACCESS_LEVEL_USER 	  = isset($_SESSION['SESS_ACCESS_LEVEL']) ? $_SESSION['SESS_ACCESS_LEVEL'] : null;
	$SESS_HASH_USER 			  = isset($_SESSION['SESS_HASH']) ? $_SESSION['SESS_HASH'] : null;
	$SESS_EMAIL_VERIFIED_USER     = isset($_SESSION['SESS_EMAIL_VERIFIED']) ? $_SESSION['SESS_EMAIL_VERIFIED'] : null;
	$SESS_STATUS_USER 			  = isset($_SESSION['SESS_STATUS']) ? $_SESSION['SESS_STATUS'] : null;
	$SESS_TOKEN_USER 			  = isset($_SESSION['SESS_TOKEN']) ? $_SESSION['SESS_TOKEN'] : null;
    $SESS_S_TYPE                  = isset($_SESSION['SESS_S_TYPE']) ? $_SESSION['SESS_S_TYPE'] : null;
    $SESS_TEACHER_USER            = isset($_SESSION['SESS_TEACHER']) ? $_SESSION['SESS_TEACHER'] : null;
	
	// TEACHER SPECIFIC SESSION VARIABLES - Added for teacher dashboard compatibility
	$SESS_ID_TEACHER               = isset($_SESSION['SESS_ID_TEACHER']) ? $_SESSION['SESS_ID_TEACHER'] : null;
	$SESS_TEACHER_NAME             = isset($_SESSION['SESS_FULLNAME']) ? $_SESSION['SESS_FULLNAME'] : null;
	$SESS_TEACHER_EMAIL            = isset($_SESSION['SESS_EMAIL']) ? $_SESSION['SESS_EMAIL'] : null;
	$SESS_TEACHER_ACCESS_LEVEL     = isset($_SESSION['SESS_ACCESS_LEVEL']) ? $_SESSION['SESS_ACCESS_LEVEL'] : null;
	$TEACHER_AUTHENTICATED         = isset($_SESSION['TEACHER_AUTHENTICATED']) ? $_SESSION['TEACHER_AUTHENTICATED'] : false;
	$SESS_LOGIN_TIME               = isset($_SESSION['SESS_LOGIN_TIME']) ? $_SESSION['SESS_LOGIN_TIME'] : null;
	$SESS_USER_TYPE                = isset($_SESSION['SESS_USER_TYPE']) ? $_SESSION['SESS_USER_TYPE'] : null;

	// Check if teacher is logged in (for main.php compatibility)
	$isTeacherLoggedIn = isset($_SESSION['SESS_ID_TEACHER']) && !empty($_SESSION['SESS_ID_TEACHER']) && $_SESSION['SESS_TEACHER'] == 'true';
	
	//salt
	$salt = "yOShxX$1$2SQNI4nm0$Ael58";
	
	//human time
	function human_time($ts,$datetimeFormat){
		$date = new \DateTime();
		$date->setTimestamp($ts);
		return $date->format($datetimeFormat);
	}
	
	// PDO Function To Handle Prepared Statements (FOR ALL QUERY)
	function sql($DBH, $query, $params, $return='null') {
		try {
			// Prepare statement
			$STH = $DBH->prepare($query);
			// Execute statement
			$STH->execute($params);
			// Decide whether to return the rows themselves, or just count the rows
			if ($return == "rows") {
				return $STH->fetchAll();
			}
		  	else if ($return == "count") {
				return $STH->rowCount();
			}else{
				return $STH;
			}
		}
		catch(PDOException $e) { 
			file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND); # Errors Log File
			return false;
		}
	}
	
	//Redirect
	function redirect($url) {
		try {
			header("Location: $url");
			exit();
		}
		catch(PDOException $e) { 
			file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND); # Errors Log File
		}
	}

	//Logout
	function logout($url = "https://portal.vda.com.ng/coll_teacher") {
		try {
			session_unset();
			session_destroy();
			header("Location: https://portal.vda.com.ng/coll_teacher");
			exit();
		}
		catch(PDOException $e) { 
			file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND); # Errors Log File
		}
	}

	// Teacher-specific functions
	function isTeacherLoggedIn() {
		return isset($_SESSION['SESS_ID_TEACHER']) && !empty($_SESSION['SESS_ID_TEACHER']) && 
			   isset($_SESSION['SESS_TEACHER']) && $_SESSION['SESS_TEACHER'] == 'true';
	}
	
	function getTeacherId() {
		return isset($_SESSION['SESS_ID_TEACHER']) ? $_SESSION['SESS_ID_TEACHER'] : null;
	}
	
	function getTeacherName() {
		return isset($_SESSION['SESS_FULLNAME']) ? $_SESSION['SESS_FULLNAME'] : 'Teacher';
	}
	
	function getTeacherEmail() {
		return isset($_SESSION['SESS_EMAIL']) ? $_SESSION['SESS_EMAIL'] : null;
	}
	
	// Function to restrict access to teachers only
	function restrictToTeachers($redirectUrl = 'index.php') {
		if (!isTeacherLoggedIn()) {
			$_SESSION['msg'] = 'access_denied';
			header("Location: $redirectUrl");
			exit();
		}
	}
	
	// Function to check if user has teacher access level
	function hasTeacherAccess() {
		$accessLevel = isset($_SESSION['SESS_ACCESS_LEVEL']) ? $_SESSION['SESS_ACCESS_LEVEL'] : '';
		return in_array($accessLevel, ['Teacher', 'Admin', 'User']);
	}
	
	// Function to validate teacher session
	function validateTeacherSession() {
		if (!isTeacherLoggedIn()) {
			return false;
		}
		
		// Check if session has expired (24 hours)
		if (isset($_SESSION['SESS_LOGIN_TIME'])) {
			$sessionDuration = time() - $_SESSION['SESS_LOGIN_TIME'];
			if ($sessionDuration > 86400) { // 24 hours in seconds
				logout();
				return false;
			}
		}
		
		return true;
	}

	// Function to get teacher's uploaded results count
	function getTeacherResultsCount($DBH, $teacherId) {
		try {
			$query = "SELECT COUNT(DISTINCT CONCAT(registration_no, '-', term, '-', year)) 
					  FROM tbl_student_results 
					  WHERE uploaded_by = :teacher_id";
			$STH = $DBH->prepare($query);
			$STH->bindParam(':teacher_id', $teacherId, PDO::PARAM_INT);
			$STH->execute();
			return $STH->fetchColumn();
		} catch (PDOException $e) {
			error_log("Error getting teacher results count: " . $e->getMessage());
			return 0;
		}
	}

	// Function to get teacher's classes count (if you have a teacher_class table)
	function getTeacherClassesCount($DBH, $teacherId) {
		try {
			// This is a placeholder - adjust based on your actual database structure
			// If you have a teacher_class assignment table, use it here
			$query = "SELECT COUNT(DISTINCT class_id) FROM teacher_classes WHERE teacher_id = :teacher_id";
			$STH = $DBH->prepare($query);
			$STH->bindParam(':teacher_id', $teacherId, PDO::PARAM_INT);
			$STH->execute();
			return $STH->fetchColumn();
		} catch (PDOException $e) {
			// If the table doesn't exist, return 0
			return 0;
		}
	}

?>