<?php

	/* ***************** SESSION LOGIC ******************/
	
	try {
		$pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
		$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$obj_users = new Users($pdo);
	} catch(PDOException $e) {
		die("Connection failed: " . $e->getMessage());
	}

	$obj_users = new Users($pdo);
	
	if(!$obj_users->checkUserLoginOrNot()){
	    header('Location: '.BASEURL.'login.php');
	} 
	
	// Logout logic
	if (isset($_GET['logout'])) {
		// Destroy the session
		session_unset();
		session_destroy();
		header("Location: ../login.php"); // Redirect to the login page
		exit();
	}
	
	if($_SESSION['user_type']!='super' && $_SESSION['user_type']!='admin'){ 
		session_destroy();
		header('Location: '.BASEURL.'login.php');
		exit();
	}
	
	if($_SESSION['user_type'] == 'super') {
		$usertype = 'super';
	} else if($_SESSION['user_type'] == 'admin') {
		$usertype = 'admin';
		$stmt = $pdo->prepare("SELECT group_id FROM wp_users WHERE id = ?");
		$stmt->execute([$_SESSION['front_user_id']]);
		$_SESSION['group_id'] = $stmt->fetchColumn();
	}


	
	
	/******************************************************************/
	/* ***************** FROM USERS AND GROUPS PAGES ******************/
	
	$groupWhere = "";
	
	if($_SESSION['user_type'] == 'super') {
		$groupWhere = "";  // Super admin sees all groups
	} else if($_SESSION['user_type'] == 'admin') {
		$stmt = $pdo->prepare("SELECT group_id FROM wp_users WHERE id = ?");
		$stmt->execute([$_SESSION['front_user_id']]);
		$group_id = $stmt->fetchColumn();
		$_SESSION['group_id'] = $group_id;
		$groupWhere = " WHERE group_id = :group_id";  // Regular admin only sees their group
	}
	
	if (isset($_GET["groupsort"]) && !empty($_GET["groupsort"])){
		if ($_GET["groupsort"] === "ORDER BY user_group asc") {
			 $groupSort = "ORDER BY user_group asc, user_email asc";
			 $groupSortNext = "ORDER BY user_group desc";
			 $groupLabel = "Sort Down";
			 $groupSortSimple = "user_group asc, ";
		} else {
			 $groupSort = "ORDER BY user_group desc, user_email asc";
			 $groupSortNext = "ORDER BY user_group asc";
			 $groupLabel = "Sort Up";
			 $groupSortSimple = "user_group desc, ";
		}
	}
	else {
		  $groupSort = "";
		  $groupSortNext = "ORDER BY user_group desc";
		  $groupLabel = "Sort Down";
		  $groupSortSimple = "";
	}

	if (isset($_GET["emailsort"]) && !empty($_GET["emailsort"])){
		if ($_GET["emailsort"] === "ORDER BY user_email asc") {
			 $emailSort = "ORDER BY user_email asc";
			 $emailSortNext = "ORDER BY user_email desc";
			 $emailLabel = "Sort Down";
		}
		else {
			 $emailSort = "ORDER BY user_email desc";
			 $emailSortNext = "ORDER BY user_email asc";
			 $emailLabel = "Sort Up";
		}
	}
	else {
		  $emailSort = "";
		  $emailSortNext = "ORDER BY $groupSortSimple user_email desc";
		  $emailLabel = "Sort Down";
	}


	if  (!isset($_GET["emailsort"]) && !isset($_GET["groupsort"])) {
		  $emailSort = "ORDER BY user_email asc";
		  $emailSortNext = "ORDER BY user_email desc";
		  $emailLabel = "Sort Down";
	}

	/***************** feature licenses check *****************/
	
	function checkFeatureLicense($feature_name) {
		global $pdo;
		
		// Check if license exists and is active
		$stmt = $pdo->prepare("
			SELECT status, last_verified 
			FROM wp_features 
			WHERE feature_name = ? 
			AND status = 'active'
		");
		$stmt->execute([$feature_name]);
		$license = $stmt->fetch(PDO::FETCH_ASSOC);
		
		if (!$license) {
			return false;
		}
		
		// If license hasn't been verified in the last 24 hours, verify it again
		if (!$license['last_verified'] || strtotime($license['last_verified']) < strtotime('-24 hours')) {
			// Get license key
			$stmt = $pdo->prepare("SELECT license_key FROM wp_features WHERE feature_name = ?");
			$stmt->execute([$feature_name]);
			$license_key = $stmt->fetchColumn();
			
            // Verify license with external service
            $ch = curl_init(LICENSE_URL);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
                'license_key' => $license_key,
                'domain' => $_SERVER['HTTP_HOST']
            ]));
            $response = curl_exec($ch);
            curl_close($ch);
			
			$verification = json_decode($response, true);
			
			if (!$verification['valid']) {
				// Update license status to inactive
				$stmt = $pdo->prepare("
					UPDATE wp_features 
					SET status = 'inactive', 
						last_verified = CURRENT_TIMESTAMP 
					WHERE feature_name = ?
				");
				$stmt->execute([$feature_name]);
				return false;
			}
			
			// Update last verification time
			$stmt = $pdo->prepare("
				UPDATE wp_features 
				SET last_verified = CURRENT_TIMESTAMP 
				WHERE feature_name = ?
			");
			$stmt->execute([$feature_name]);
		}
		
		return true;
	}

	// Set feature availability in session
	$_SESSION['pass_feature'] = checkFeatureLicense('pass_feature') ? 'paid' : 'free';
	
	$stmt = $pdo->prepare("SELECT status FROM wp_features WHERE feature_name = 'pass_feature'");
	$stmt->execute();
	$pass_feature = $stmt->fetchColumn() === 'active' ? 'Active' : 'Inactive';
	/******************************************************************/
	
?>