<?php
// session_config_emp.php
// Shared session config + validation for employee system
// Adjust DB connection usage as required (uses $conn variable where needed).

// ------------ SECURITY SETTINGS ------------
ini_set('session.use_only_cookies', 1);
ini_set('session.use_strict_mode', 1);
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_samesite', 'Lax');

// ------------ COOKIE / SESSION PARAMETERS ------------
// lifetime = 0 -> session cookie (will be removed when browser process ends)
// We'll use both server-side remember-me token (persistent) and session cookie 0.
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => '', // set if needed
    'secure' => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on',
    'httponly' => true,
    'samesite' => 'Lax'
]);

ini_set('session.use_trans_sid', 0);

// Idle timeout and max lifetime (in seconds)
$session_timeout = 1800; // 30 minutes
$max_session_lifetime = 7200; // 2 hours

session_name('EMP_SESS_' . substr(md5(__FILE__), 0, 8));
session_start();

// Initialize session meta
if (!isset($_SESSION['CREATED'])) $_SESSION['CREATED'] = time();
if (!isset($_SESSION['LAST_ACTIVITY'])) $_SESSION['LAST_ACTIVITY'] = time();
if (empty($_SESSION['csrf_token'])) $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
if (!isset($_SESSION['USER_AGENT'])) $_SESSION['USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'] ?? '';

// ------------ DATABASE CONNECTION ------------
// TODO: include or create your DB connection here, set $conn.
// Example: include 'connect.php';
// require_once 'connect.php';

// ------------ REMEMBER-ME CHECK (auto-login) ------------
// Checks persistent cookie 'remember_emp' if session not set
function tryRememberLogin($conn) {
    if (isset($_SESSION['employee_id'])) return; // already logged in
    if (empty($_COOKIE['remember_emp'])) return;

    $token = $_COOKIE['remember_emp'];
    // Token format: raw token; server stores hashed token (hash_hmac)
    // TODO: Adjust table/column names to your DB schema.
    $sql = "SELECT user_id, token_hash, expires_at FROM remember_tokens WHERE token_hash = ? LIMIT 1";
    if ($stmt = $conn->prepare($sql)) {
        $hash = hash('sha256', $token);
        $stmt->bind_param('s', $hash);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($row = $res->fetch_assoc()) {
            if (strtotime($row['expires_at']) > time()) {
                // Valid token — log user in
                $userId = $row['user_id'];
                // TODO: load user details into session (example fields)
                $_SESSION['employee_id'] = $userId;
                // set other session fields (cnic etc) via DB lookup
                // Also set server-side active_session_id so only one active session exists per user:
                $_SESSION['ACTIVE_SESSION_ID'] = bin2hex(random_bytes(16));
                // store in DB as user's active session
                $sql2 = "UPDATE users SET active_session_id = ? WHERE id = ?";
                if ($s2 = $conn->prepare($sql2)) {
                    $s2->bind_param('si', $_SESSION['ACTIVE_SESSION_ID'], $userId);
                    $s2->execute();
                }
            } else {
                // expired token - remove cookie and token from DB
                setcookie('remember_emp', '', time() - 3600, '/', '', isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on', true);
                $del = $conn->prepare("DELETE FROM remember_tokens WHERE token_hash = ?");
                if ($del) { $del->bind_param('s', $hash); $del->execute(); }
            }
        }
        $stmt->close();
    }
}

// Call tryRememberLogin if you included DB connection above
// if (isset($conn)) tryRememberLogin($conn);

// ------------ SESSION VALIDATION FUNCTION ------------
function validateUserSession($conn = null) {
    global $session_timeout;

    // basic checks
    if (empty($_SESSION['employee_id'])) return false;
    if (time() - ($_SESSION['LAST_ACTIVITY'] ?? 0) > $session_timeout) return false;
    if (!isset($_SESSION['USER_AGENT']) || $_SESSION['USER_AGENT'] !== ($_SERVER['HTTP_USER_AGENT'] ?? '')) return false;

    // Optional: server-side single-session check using DB active_session_id
    if ($conn && isset($_SESSION['employee_id'], $_SESSION['ACTIVE_SESSION_ID'])) {
        $sql = "SELECT active_session_id FROM users WHERE id = ? LIMIT 1";
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param('i', $_SESSION['employee_id']);
            $stmt->execute();
            $res = $stmt->get_result();
            if ($row = $res->fetch_assoc()) {
                if ($row['active_session_id'] !== $_SESSION['ACTIVE_SESSION_ID']) {
                    return false; // another session replaced this
                }
            }
            $stmt->close();
        }
    }

    return true;
}

// ------------ SESSION TIMEOUT HANDLING ------------
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > $session_timeout)) {
    // idle logout
    $_SESSION = [];
    if (ini_get("session.use_cookies")) {
        $p = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000, $p['path'], $p['domain'], $p['secure'], $p['httponly']);
    }
    session_destroy();
}

if (isset($_SESSION['CREATED']) && (time() - $_SESSION['CREATED'] > $max_session_lifetime)) {
    // force re-login
    $_SESSION = [];
    if (ini_get("session.use_cookies")) {
        $p = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000, $p['path'], $p['domain'], $p['secure'], $p['httponly']);
    }
    session_destroy();
}

// secureSessionRegeneration() available globally
function secureSessionRegeneration() {
    session_regenerate_id(true);
    $_SESSION['CREATED'] = time();
    $_SESSION['LAST_ACTIVITY'] = time();
    $_SESSION['USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Update last activity
$_SESSION['LAST_ACTIVITY'] = time();

// ------------ CSRF helper ------------
if (empty($_SESSION['csrf_token'])) $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
function validateCsrfToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}
function regenerateCsrfToken() {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    return $_SESSION['csrf_token'];
}

// ------------ Destroy session completely ------------
function destroySessionCompletely($conn = null) {
    if (isset($_SESSION['employee_id']) && $conn) {
        // Clear user's active_session_id in DB so other devices can't reuse
        $sql = "UPDATE users SET active_session_id = NULL WHERE id = ?";
        if ($s = $conn->prepare($sql)) {
            $s->bind_param('i', $_SESSION['employee_id']);
            $s->execute();
            $s->close();
        }
    }

    // remove remember cookie if present
    if (isset($_COOKIE['remember_emp'])) {
        setcookie('remember_emp', '', time() - 3600, '/', '', isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on', true);
    }

    // destroy session cookie + session
    $_SESSION = [];
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params["path"], $params["domain"], $params["secure"], $params["httponly"]
        );
    }
    session_destroy();
}
?>
