<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/**
 * BASIC AUTH CHECK
 */
if (
    empty($_SESSION['loggedin']) ||
    empty($_SESSION['user_id']) ||
    empty($_SESSION['company_id'])
) {
    header("Location: sign-in.php");
    exit;
}

/**
 * OPTIONAL: Prevent session fixation
 */
if (empty($_SESSION['initiated'])) {
    session_regenerate_id(true);
    $_SESSION['initiated'] = true;
}

$timeout = 7200; // 120 minutes

if (isset($_SESSION['last_activity']) &&
    (time() - $_SESSION['last_activity']) > $timeout
) {
    session_unset();
    session_destroy();
    header("Location: sign-in.php");
    exit;
}

$_SESSION['last_activity'] = time();


/**
 * Session variables now guaranteed:
 * $_SESSION['user_id']
 * $_SESSION['company_id']
 * $_SESSION['email']
 * $_SESSION['user_name']
 * $_SESSION['role']
 */
