<?php
if (!isset($__DATABASE)) {
    header("Location: " . $__FORBID_ADDR);
    exit;
}

if (!isLogin()) {
    header("Location: " . $__AUTH_ADDR);
    exit;
}

if (isLogin()) {
    $user_id = $_SESSION['id'];

    // Fetch the session ID stored in the database for the current user
    $query = "SELECT session_id FROM users WHERE id = :id";
    $stmt = PDO_CONNECTION->prepare($query);
    $stmt->bindParam(":id", $user_id);
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    // Compare the current session ID with the one in the database
    if (session_id() != $result['session_id']) {
        // Session ID does not match, force logout
        session_destroy(); // End the session
        echo "You have been logged out because you logged in on another device.";
        exit();
    }
}

function isAllowedToVisit()
{
    $current_page = explode(".", basename($_SERVER['PHP_SELF']))[0];

    if (in_array($current_page, $_SESSION['not_allowed'])) {
        return false;
    }
    return true;
}
