<?php
session_start();
require("../includes/db_connect.php");

if ($conn && isset($_SESSION['usr_accountId']) && isset($_SESSION['usr_accessToken'])) {

	$sql = "SELECT accountId, session_token FROM session_tokens WHERE accountId = :accountId LIMIT 1";
	$sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
	$sth->execute([':accountId' => $_SESSION['usr_accountId']]);
	$session_tokens = $sth->fetchAll();

	if (count($session_tokens) > 0) {

		foreach ($session_tokens as $key => $value) {
			$session_token = $value['session_token'];

			if ($session_token != $_SESSION['usr_accessToken']) {
				logOut();
			}

			$req_url = $_SERVER['REQUEST_URI'];

			if (strpos($req_url, 'user/identity-verification') == false) {
				checkVerification();
			}
		}
	} else {
		logOut();
	}
} else {
	logOut();
}

function logOut()
{
	session_destroy();
	header('Location: ../login');
	exit();
}

if (isset($_GET['logout'])) {
	$session_tokens_sql = "UPDATE session_tokens SET session_token=? WHERE accountId=?";

	$update_session_token = $conn->prepare($session_tokens_sql)->execute(["0", $_SESSION['usr_accountId']]);

	logOut();
}

function checkVerification()
{
	global $conn;

	$kyc_usr_sql = "SELECT * FROM kyc_documents WHERE accountId =? LIMIT 1";
	$kyc_usr_sth = $conn->prepare($kyc_usr_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
	$kyc_usr_sth->execute([$_SESSION['usr_accountId']]);
	$kyc_users = $kyc_usr_sth->fetchAll();

	// 	check if verification_identity required by admin
	$usr_sql = "SELECT * FROM users WHERE accountId =? LIMIT 1";
	$usr_sth = $conn->prepare($usr_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
	$usr_sth->execute([$_SESSION['usr_accountId']]);
	$users = $usr_sth->fetchAll();

	if (count($users) > 0) {
		foreach ($users as $key => $value) {
			$verification_identity = $value['verification_identity'];

			if ($verification_identity == "0") {
				showVerification();
			}
		}
	}

	// 	if (count($kyc_users) > 0) {
	// 		foreach ($kyc_users as $key => $value) {
	// 			$full_legal_name = $value['full_legal_name'];

	// 			if ($full_legal_name == "default") {
	// showVerification();
	// 			}
	// 		}
	// 	}else {
	// 		showVerification();
	// 	}
}


function showVerification()
{
	header('Location: identity-verification');
	exit();
}