<?php
// Load security helpers
// mbstring fallback — no-op where the extension is loaded; guarded so a
// partial deploy (dbconn.php landing before the polyfill) cannot break boot.
if (file_exists(__DIR__ . '/afm_mb_polyfill.php')) { require_once __DIR__ . '/afm_mb_polyfill.php'; }
require_once __DIR__ . '/DatabaseHelper.php';
require_once __DIR__ . '/SecurityHelper.php';
require_once __DIR__ . '/ErrorHandler.php';
require_once __DIR__ . '/SessionHelper.php';
require_once __DIR__ . '/RateLimiter.php';
require_once __DIR__ . '/MigrationRunner.php';
require_once __DIR__ . '/AuditLogger.php';
require_once __DIR__ . '/CacheHelper.php';

/**
 * Cloudflare real-client-IP restoration.
 * When the site is served through Cloudflare, $_SERVER['REMOTE_ADDR'] becomes a
 * Cloudflare edge IP for EVERY visitor — which would break audit logging, login
 * lockout and rate-limiting (all users would share one IP). We restore the true
 * visitor IP from the CF-Connecting-IP header, but ONLY when the connecting IP is
 * inside Cloudflare's published ranges, so a direct attacker can't spoof the header.
 * No-op when not behind Cloudflare (direct hits don't match the ranges).
 */
if (!function_exists('_cfIpInCidr')) {
    function _cfIpInCidr($ip, $cidr) {
        if (strpos($cidr, '/') === false) return false;
        list($subnet, $mask) = explode('/', $cidr, 2);
        $maskI = (int)$mask;
        $ipBin = @inet_pton($ip);
        $subBin = @inet_pton($subnet);
        if ($ipBin === false || $subBin === false || strlen($ipBin) !== strlen($subBin)) return false;
        $bytes = intdiv($maskI, 8); $bits = $maskI % 8;
        if ($bytes > 0 && substr($ipBin, 0, $bytes) !== substr($subBin, 0, $bytes)) return false;
        if ($bits === 0) return true;
        $m = chr((0xFF << (8 - $bits)) & 0xFF);
        return ((ord($ipBin[$bytes]) & ord($m)) === (ord($subBin[$bytes]) & ord($m)));
    }
}
if (!empty($_SERVER['HTTP_CF_CONNECTING_IP']) && !empty($_SERVER['REMOTE_ADDR'])) {
    $_cfRanges = [
        '173.245.48.0/20','103.21.244.0/22','103.22.200.0/22','103.31.4.0/22','141.101.64.0/18',
        '108.162.192.0/18','190.93.240.0/20','188.114.96.0/20','197.234.240.0/22','198.41.128.0/17',
        '162.158.0.0/15','104.16.0.0/13','104.24.0.0/14','172.64.0.0/13','131.0.72.0/22',
        '2400:cb00::/32','2606:4700::/32','2803:f800::/32','2405:b500::/32','2405:8100::/32','2a06:98c0::/29','2c0f:f248::/32',
    ];
    foreach ($_cfRanges as $_cfCidr) {
        if (_cfIpInCidr($_SERVER['REMOTE_ADDR'], $_cfCidr)) {
            $_cfReal = trim((string)$_SERVER['HTTP_CF_CONNECTING_IP']);
            if (filter_var($_cfReal, FILTER_VALIDATE_IP)) {
                $_SERVER['REMOTE_ADDR'] = $_cfReal;
                $_SERVER['HTTP_X_FORWARDED_FOR'] = $_cfReal;
            }
            break;
        }
    }
    unset($_cfRanges, $_cfCidr, $_cfReal);
}

/**
 * Safe stripslashes that handles null values (PHP 8.1+ compatibility)
 * @param mixed $string The string to strip slashes from
 * @return string The stripped string, or empty string if null
 */
if (!function_exists('ss')) {
    function ss($string) {
        return stripslashes($string ?? '');
    }
}

/**
 * Escape a value for output inside HTML.
 *
 * USE THIS, NOT ss(), WHENEVER YOU ECHO A VALUE INTO A PAGE.
 *
 * ss() is stripslashes() and nothing else — the name reads like "safe string"
 * but it performs no escaping whatsoever. `echo ss($row['name'])` will happily
 * emit a <script> tag. That is fine for values the system itself generated
 * (ids, dates, numbers) and dangerous for anything a human typed: patient and
 * staff names, addresses, notes, remarks, and above all anything arriving from
 * an unauthenticated source (a login form, an HL7 feed, a public endpoint).
 *
 * esc() does the stripslashes ss() did, then escapes for HTML, so it is a
 * drop-in replacement at any plain-text output site.
 *
 * DO NOT use it for values that are deliberately HTML — rich-text/summernote
 * fields, or markup this codebase builds itself. Those need plainText() or to
 * be left alone.
 */
if (!function_exists('esc')) {
    function esc($string) {
        return htmlspecialchars(stripslashes((string)($string ?? '')), ENT_QUOTES, 'UTF-8');
    }
}

/**
 * Strip HTML tags from rich-text editor output, converting block tags to newlines.
 * Use for displaying HTML-containing fields in plain text contexts (textareas, table cells).
 */
if (!function_exists('plainText')) {
    function plainText($html) {
        if (empty($html)) return '';
        $text = str_replace(['<br>','<br/>','<br />','</p>','</div>','</li>','</tr>'], "\n", $html);
        $text = strip_tags($text);
        $text = preg_replace('/\n{3,}/', "\n\n", $text);
        return trim(stripslashes($text));
    }
}

/**
 * Return an image URL with a filemtime-based cache-busting version parameter.
 * Falls back to globbing for files where the extension may have changed (logo, stamp).
 * Usage: imgv('assets/images/clogo.png')  →  'assets/images/clogo.png?v=1709123456'
 */
if (!function_exists('imgv')) {
    function imgv($path) {
        if (empty($path)) return $path;
        $abs = __DIR__ . '/' . ltrim($path, '/');
        if (file_exists($abs)) {
            return $path . '?v=' . filemtime($abs);
        }
        // File may have been re-uploaded with a different extension — find by glob
        $base = preg_replace('/\.[^.]+$/', '', $abs); // strip extension
        $matches = glob($base . '.*');
        if ($matches) {
            $found = str_replace(__DIR__ . '/', '', $matches[0]);
            return $found . '?v=' . filemtime($matches[0]);
        }
        return $path; // file not found, return as-is
    }
}

/**
 * Square-slot logo. Some facilities' logos are a wide lockup (mark + wordmark), which is right on a
 * letterhead but turns into an unreadable strip inside a small square: the sign-in badge (34x34), the
 * collapsed-sidebar mark (30px), the favicon and the installed-app icon. Where a site has supplied a
 * square source at assets/images/micon_src.png, prefer it in those slots; otherwise nothing changes and
 * the ordinary logo is used. Returns a RAW path — wrap in imgv() for cache-busting.
 */
if (!function_exists('afmSquareLogo')) {
    function afmSquareLogo($logo = '') {
        if (is_file(__DIR__ . '/assets/images/micon_src.png')) { return 'assets/images/micon_src.png'; }
        $logo = preg_replace('/\?.*$/', '', (string)$logo);
        return $logo !== '' ? $logo : 'assets/images/clogo.png';
    }
}

// Initialize error handler
ErrorHandler::register(false); // Set to true for development mode

// Initialize secure session
try {
    SessionHelper::init(7200); // 2 hour timeout — aligned with .user.ini session.gc_maxlifetime
} catch (ApplicationException $e) {
    header('Location: index.php');
    exit;
}

// Installation gate: redirect to installer if not yet configured
if (!file_exists(__DIR__ . '/dbconfig.php') && !file_exists(__DIR__ . '/installed.lock')) {
    $_install_script = basename($_SERVER['SCRIPT_FILENAME'] ?? '');
    if (!in_array($_install_script, ['install.php', 'install_run.php'], true)) {
        if (php_sapi_name() !== 'cli') {
            if (!headers_sent()) { header('Location: install.php'); exit; }
            else { echo '<script>window.location.href="install.php";</script>'; exit; }
        }
    }
}

// Database connection
// Load database config (use dbconfig.php for hosting, or defaults for local dev)
if (file_exists(__DIR__ . '/dbconfig.php')) {
    require_once __DIR__ . '/dbconfig.php';
    $db_host = DB_HOST;
    $db_user = DB_USER;
    $db_pass = DB_PASS;
    $db_name = DB_NAME;
} else {
    // Fallback to local development settings
    $db_host = 'localhost';
    $db_user = 'root';
    $db_pass = '';
    $db_name = 'hosdb';
    // No dbconfig.php means this is the local dev / vendor install. Customer
    // tenants always ship with a dbconfig.php (which carries their own DB
    // credentials). The VENDOR_INSTALL flag unlocks the vendor-only Tenant
    // Manager / vendor CRM. Tenant installs leave it undefined.
    if (!defined('VENDOR_INSTALL')) define('VENDOR_INSTALL', true);
}

$server = $_SESSION['server'] = $db_host;

// Use 127.0.0.1 (TCP) as primary — works on all hosts.
// localhost (Unix socket) fails with "No such file or directory" on some cPanel hosts
// where the socket path is non-standard.
if (PHP_OS_FAMILY === 'Windows') {
    $db_connect_host = $db_host;
} else {
    $db_connect_host = '127.0.0.1';
}

/**
 * Circuit breaker: if MySQL was down <15 seconds ago, fail fast instead of blocking.
 * Prevents retry storms during MySQL restarts.
 */
if (!function_exists('_db_circuit_open')) {
function _db_circuit_open() {
    $lockFile = sys_get_temp_dir() . '/afyamed_db_down.lock';
    if (!file_exists($lockFile)) return false;
    $contents = @file_get_contents($lockFile);
    if ($contents === false) return false;
    $downSince = (int)$contents;
    if (time() - $downSince < 15) {
        return true; // Circuit open — MySQL was down recently, don't retry
    }
    @unlink($lockFile); // Expired — close circuit
    return false;
}
}
if (!function_exists('_db_circuit_trip')) {
function _db_circuit_trip() {
    $lockFile = sys_get_temp_dir() . '/afyamed_db_down.lock';
    @file_put_contents($lockFile, time());
}
}

/**
 * Attempt a MySQL connection with minimal retry.
 * Returns mysqli instance on success or null on failure.
 */
if (!function_exists('_try_connect_db')) {
function _try_connect_db($host, $user, $pass, $name, $attempts = 2, $delaySeconds = 1) {
    for ($i = 0; $i < $attempts; $i++) {
        try {
            $conn = @mysqli_connect($host, $user, $pass, $name);
            if ($conn) {
                // Enable auto-reconnect at MySQL level
                @$conn->options(MYSQLI_OPT_CONNECT_TIMEOUT, 30);
                @$conn->set_charset('utf8mb4');
                // Increase wait_timeout for this session
                @$conn->query("SET SESSION wait_timeout=600, SESSION interactive_timeout=600");
                return $conn;
            }
        } catch (\Exception $e) {
            // Connection failed — will retry or return null
        }
        if ($i < $attempts - 1) {
            usleep(500000); // 0.5 second
        }
    }
    return null;
}
} // end if !function_exists('_try_connect_db')

/**
 * Reconnect to the database if an existing connection is lost.
 * Uses circuit breaker to avoid retry storms when MySQL is down.
 */
if (!function_exists('reconnectDatabase')) {
function reconnectDatabase() {
    global $db, $db_connect_host, $db_user, $db_pass, $db_name;

    if (isset($db) && $db instanceof mysqli) {
        try {
            if (@$db->ping()) return $db;
        } catch (\Exception $e) {
            // Connection is dead, proceed to reconnect
        }
    }

    // Circuit breaker: fail fast if MySQL was down recently
    if (_db_circuit_open()) {
        return null;
    }

    $newDb = _try_connect_db($db_connect_host, $db_user, $db_pass, $db_name, 2, 1);
    if (!$newDb && $db_connect_host === 'localhost') {
        // Fallback: try TCP if socket failed
        $newDb = _try_connect_db('127.0.0.1', $db_user, $db_pass, $db_name, 1, 0);
    }

    if ($newDb) {
        try {
            @mysqli_query($newDb, "SET wait_timeout=300, interactive_timeout=300");
            @mysqli_set_charset($newDb, 'utf8mb4');
        } catch (\Exception $e) {
            // Post-connect setup failed but connection may still work
        }
        $db = $newDb;
    } else {
        // Trip circuit breaker — stop retrying for 15 seconds
        _db_circuit_trip();
    }

    return $newDb;
}
} // end if !function_exists('reconnectDatabase')

$db = reconnectDatabase();

if (!$db) {
    // Single clean log line instead of flooding
    error_log('[AfyaMed] DB connection failed at ' . date('Y-m-d H:i:s') . ': ' . mysqli_connect_error());
    http_response_code(503);
    die('<!DOCTYPE html><html><head><title>Temporarily Unavailable</title><meta http-equiv="refresh" content="10"></head><body style="font-family:Arial;text-align:center;padding:60px;"><h2>System Temporarily Unavailable</h2><p>The database is restarting. This page will auto-refresh in 10 seconds.</p></body></html>');
}

// Keep the connection alive on shared hosting (prevents "MySQL server has gone away")
try {
    mysqli_options($db, MYSQLI_OPT_CONNECT_TIMEOUT, 30);
    @mysqli_query($db, "SET SESSION wait_timeout=600, SESSION interactive_timeout=600");
    mysqli_set_charset($db, 'utf8mb4');
} catch (Exception $e) {
    usleep(500000);
    $db = reconnectDatabase();
    if ($db) {
        @mysqli_query($db, "SET SESSION wait_timeout=600, SESSION interactive_timeout=600");
        @mysqli_set_charset($db, 'utf8mb4');
    }
}

// Global "gone away" exception handler — catches ANY mysqli_query failure and auto-reconnects
// This is the LAST LINE OF DEFENSE for all raw mysqli_query($db, ...) calls across the codebase
$_originalExHandler = set_exception_handler(null);
restore_exception_handler();
set_exception_handler(function($e) use (&$db, &$dbHelper, &$rateLimiter, &$auditLogger) {
    global $_originalExHandler;
    $msg = $e->getMessage();
    if ($e instanceof \mysqli_sql_exception && (stripos($msg, 'gone away') !== false || stripos($msg, 'Lost connection') !== false)) {
        // Auto-reconnect
        $newDb = function_exists('reconnectDatabase') ? reconnectDatabase() : null;
        if ($newDb instanceof \mysqli) {
            $db = $newDb;
            $GLOBALS['db'] = $newDb;
            if (isset($dbHelper)) $dbHelper = new DatabaseHelper($newDb);
            if (isset($rateLimiter)) $rateLimiter = new RateLimiter($newDb);
            if (isset($auditLogger)) $auditLogger = new AuditLogger($newDb);
        }
        // Log but don't crash — the page will get a partial response but won't show an error page
        @error_log('[AfyaMed] Auto-reconnected after: ' . $msg);
        return; // Swallow the exception
    }
    // For all other exceptions, use the original handler
    if (is_callable($_originalExHandler)) {
        call_user_func($_originalExHandler, $e);
    } else {
        // Default: let ErrorHandler handle it
        if (class_exists('ErrorHandler') && method_exists('ErrorHandler', 'handleException')) {
            ErrorHandler::handleException($e);
        } else {
            throw $e;
        }
    }
});

// Create database helper instance
$dbHelper = new DatabaseHelper($db);

// Create rate limiter, audit logger, and cache instances (globally available)
$rateLimiter = new RateLimiter($db);
$auditLogger = new AuditLogger($db);
$cache = new CacheHelper();

// Run pending database migrations (auto-tracks applied migrations)
$_migRunner = new MigrationRunner($db);
$_migApplied = $_migRunner->run();
if (!empty($_migApplied)) {
    error_log('[dbconn] Auto-applied migrations: ' . implode(', ', $_migApplied));
}
unset($_migRunner, $_migApplied);

// ── Core system integrity verification ──
// The gate applies whether or not the system_license table exists: a missing
// table means NOT ACTIVATED (dropping the table must never unlock the system).
// Verification itself lives in modules/license/LicenseCrypto.php, shared with
// license_check.php so the two gates cannot drift.
//
// Activation records are RSA-signed by the vendor and re-verified here on every
// request. Before 2026-09-09 this checked only that an 'active' row existed with
// a matching domain_hash — no signature — so one INSERT via phpMyAdmin unlocked
// any install permanently.
//
// The activation/installer scripts are allowlisted by an explicit constant they
// define BEFORE including this file, not by basename. A basename allowlist let
// anyone copy an application page to `install.php` and run it ungated.
require_once __DIR__ . '/modules/license/LicenseCrypto.php';

$_afmLicenseBootstrap = defined('AFM_LICENSE_BOOTSTRAP')
    && in_array(basename($_SERVER['SCRIPT_FILENAME'] ?? ''),
                ['activate.php', 'activate_license.php', 'install.php', 'install_run.php'], true);

if (php_sapi_name() !== 'cli' && !$_afmLicenseBootstrap) {
    $_afmGate = LicenseCrypto::gate($db);
    if (!$_afmGate['ok']) {
        @error_log('[AfyaMed] License gate refused request: ' . $_afmGate['reason']);
        if (!headers_sent()) { header('Location: activate.php?r=' . urlencode($_afmGate['reason'])); exit; }
        else { echo '<script>window.location.href="activate.php?r=' . htmlspecialchars($_afmGate['reason'], ENT_QUOTES) . '";</script>'; exit; }
    }
    if (!empty($_afmGate['legacy'])) {
        // Pre-signing activation running inside its migration-216 amnesty.
        $GLOBALS['_license_legacy_grace_until'] = $_afmGate['grace_until'];
    }
    unset($_afmGate);
}
unset($_afmLicenseBootstrap);

// Initialize BranchManager for multi-location support
require_once __DIR__ . '/BranchManager.php';
require_once __DIR__ . '/BranchFilterHelper.php';

if (!function_exists('tableHasColumn')) {
    function tableHasColumn($table, $column) {
        static $cache = [];
        $table = trim((string)$table);
        $column = trim((string)$column);
        $key = strtolower($table) . '.' . strtolower($column);
        if (isset($cache[$key])) {
            return $cache[$key];
        }
        if (!preg_match('/^[A-Za-z0-9_]+$/', $table) || !preg_match('/^[A-Za-z0-9_]+$/', $column)) {
            $cache[$key] = false;
            return false;
        }
        $db = $GLOBALS['db'] ?? null;
        if (!$db) {
            $cache[$key] = false;
            return false;
        }
        $result = mysqli_query($db, "SHOW COLUMNS FROM `$table` LIKE '$column'");
        $cache[$key] = $result && mysqli_num_rows($result) > 0;
        return $cache[$key];
    }
}

if (!function_exists('ensureColumnExists')) {
    function ensureColumnExists($table, $column, $definition) {
        static $checked = [];
        $table = trim((string)$table);
        $column = trim((string)$column);
        $definition = trim((string)$definition);
        $key = strtolower($table) . '.' . strtolower($column);
        if (isset($checked[$key])) {
            return tableHasColumn($table, $column);
        }
        $checked[$key] = true;
        if (tableHasColumn($table, $column)) {
            return true;
        }
        if (!preg_match('/^[A-Za-z0-9_]+$/', $table) || !preg_match('/^[A-Za-z0-9_]+$/', $column)) {
            return false;
        }
        if ($definition === '') {
            return false;
        }
        $db = $GLOBALS['db'] ?? null;
        if (!$db) {
            return false;
        }
        mysqli_query($db, "ALTER TABLE `$table` ADD COLUMN `$column` $definition");
        return tableHasColumn($table, $column);
    }
}

// (2026-10-22) DHCF 2i — tell the clinical audit triggers (clinical_audit_helper.php, migration 326) who is writing and from where.
// Per connection, so it is set on every request; a failure here must never stop the page.
try {
    if (isset($db) && $db instanceof mysqli) {
        $_afmAu = (string)($_SESSION['valid_user'] ?? '');
        $_afmSc = basename((string)($_SERVER['SCRIPT_NAME'] ?? ($_SERVER['PHP_SELF'] ?? '')));
        if ($_afmAu === '') $_afmAu = PHP_SAPI === 'cli' ? 'cli:' . $_afmSc : 'script:' . $_afmSc;
        $_afmTm = (PHP_SAPI === 'cli' ? 'cli' : (string)($_SERVER['REMOTE_ADDR'] ?? '')) . ' ' . $_afmSc;
        $_afmSt = @mysqli_prepare($db, "SET @afm_user = ?, @afm_terminal = ?");
        if ($_afmSt) { $_afmAu = substr($_afmAu, 0, 64); $_afmTm = substr($_afmTm, 0, 100); @mysqli_stmt_bind_param($_afmSt, 'ss', $_afmAu, $_afmTm); @mysqli_stmt_execute($_afmSt); @mysqli_stmt_close($_afmSt); }
    }
} catch (\Throwable $e) {}

// Only initialize if user is logged in
if (isset($_SESSION['valid_user'])) {
    // ── Single active session per user (last login wins) ──────────────
    // One device at a time. The user record holds the token of the currently
    // active device. On each (throttled) request we compare ours to it:
    //   • our token != DB token  → another device took over → sign us out.
    //   • we have NO token (session predates this feature):
    //       - DB token empty → claim the slot for this session.
    //       - DB token set   → another device is active → sign us out.
    // Skipped on login/logout/login-page so signing in is never interrupted.
    {
        $_sessScript = basename($_SERVER['SCRIPT_NAME'] ?? ($_SERVER['PHP_SELF'] ?? ''));
        $_sessSkip = in_array($_sessScript, ['login.php', 'logout.php', 'index.php'], true);
        $_sessDue = !isset($_SESSION['_sess_chk_at']) || (time() - (int)$_SESSION['_sess_chk_at']) >= 8;
        if (!$_sessSkip && $_sessDue) {
            $_SESSION['_sess_chk_at'] = time();
            // Desktop and the mobile PWA hold separate slots: sessions marked
            // client=mobile (set by login.php for m.php logins) are compared
            // against users.mobile_session_token; everything else against
            // users.session_token. A phone login therefore no longer kicks the
            // same account's desktop session, and vice versa.
            $_tokCol = (($_SESSION['client'] ?? '') === 'mobile') ? 'mobile_session_token' : 'session_token';
            $_sessRow = $dbHelper->selectOne("SELECT `$_tokCol` AS tok, status FROM users WHERE name = ? LIMIT 1", [$_SESSION['valid_user']], "s");
            if (!$_sessRow && $_tokCol !== 'session_token') {
                // Column not migrated yet on this site — fall back to the legacy slot.
                $_sessRow = $dbHelper->selectOne("SELECT session_token AS tok, status FROM users WHERE name = ? LIMIT 1", [$_SESSION['valid_user']], "s");
                $_tokCol = 'session_token';
            }
            $_dbTok = $_sessRow ? (string)($_sessRow['tok'] ?? '') : '';
            $_myTok = (string)($_SESSION['session_token'] ?? '');
            $_sessKick = false;
            // Disabled accounts lose their ACTIVE session too — without this, a
            // user disabled in User Management keeps working until they log out.
            if ($_sessRow && isset($_sessRow['status']) && (int)$_sessRow['status'] !== 1) {
                $_sessKick = true;
            }
            // (2026-10-22) DHCF 2n — an account past its expiry date (users.account_expires, migration 326) loses its live session too.
            // Separate query: on a site where the column is not there yet it simply returns nothing.
            if (!$_sessKick) {
                try {
                    $_expRow = @$dbHelper->selectOne("SELECT account_expires FROM users WHERE name = ? LIMIT 1", [$_SESSION['valid_user']], "s");
                    $_expOn = $_expRow ? trim((string)($_expRow['account_expires'] ?? '')) : '';
                    if ($_expOn !== '' && $_expOn !== '0000-00-00' && $_expOn <= date('Y-m-d')) { $_sessKick = true; $_sessEndWhy = 'expired'; }
                } catch (\Throwable $e) {}
            }
            if ($_myTok === '') {
                // Grandfathered session (no token yet).
                if ($_dbTok === '') {
                    // No active device on record — claim the slot for this one.
                    $_myTok = bin2hex(random_bytes(16));
                    $_SESSION['session_token'] = $_myTok;
                    $dbHelper->update("UPDATE users SET `$_tokCol` = ?, session_started = NOW() WHERE name = ?", [$_myTok, $_SESSION['valid_user']], "ss");
                } else {
                    // Another device already holds the slot — this older one loses.
                    $_sessKick = true;
                }
            } elseif ($_dbTok !== '' && !hash_equals($_dbTok, $_myTok)) {
                $_sessKick = true;
            }
            if ($_sessKick) {
                $_SESSION = [];
                @session_destroy();
                $_acc = $_SERVER['HTTP_ACCEPT'] ?? '';
                $_isXhr = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
                $_wantsJson = strpos($_acc, 'application/json') !== false;
                $_sessEndQ = isset($_sessEndWhy) ? $_sessEndWhy : '1';
                $_redir = "<script>try{window.top.location.href='index.php?ended=" . $_sessEndQ . "';}catch(e){window.location.href='index.php?ended=" . $_sessEndQ . "';}</script>";
                if ($_wantsJson) {
                    // JSON callers (the heartbeat + jQuery dataType:json AJAX, which the
                    // global ajaxError handler watches) → 440 so the client redirects.
                    if (!headers_sent()) { http_response_code(440); header('Content-Type: application/json'); }
                    echo json_encode(['session_ended' => true]);
                } elseif ($_isXhr) {
                    // HTML-injecting XHR (e.g. the notification poller refreshchat() that
                    // does $('#chata').html(data)) → return the redirect SCRIPT at 200 so it
                    // runs when injected. This kicks idle OLD pages (loaded before the
                    // heartbeat) on their next background poll, with no click needed.
                    echo $_redir;
                } else {
                    if (!headers_sent()) { header('Location: index.php?ended=' . $_sessEndQ); }
                    echo $_redir;
                }
                exit;
            }


        // ── (2026-10-07) Session timeout policy (System Settings → Session Timeout) ──
        //   session_idle_minutes  sign out after this much inactivity (0 = never)
        //   session_max_hours     sign out this long after login regardless (0 = no limit)
        // Passive requests (ping.php, dbstream heartbeat) restore the previous stamp unless they carry active=1,
        // so only a person's own activity keeps the session alive. The cookie is re-issued on every request so an
        // active user is no longer cut off when the 2 h cookie set at login expires.
        if (!isset($GLOBALS['afmSessionPolicy'])) {
            $GLOBALS['afmSessionPolicy'] = ['idle' => 120, 'warn' => 2, 'max_hours' => 0, 'lock' => 0];
            try {
                $_spRows = $dbHelper->select("SELECT setting_key, setting_value FROM system_settings WHERE setting_key IN ('session_idle_minutes','session_warn_minutes','session_max_hours','session_lock_minutes')", [], "");
                foreach (($_spRows ?: []) as $_spR) {
                    if ($_spR['setting_key'] === 'session_idle_minutes') $GLOBALS['afmSessionPolicy']['idle'] = max(0, (int)$_spR['setting_value']);
                    if ($_spR['setting_key'] === 'session_warn_minutes') $GLOBALS['afmSessionPolicy']['warn'] = max(0, (int)$_spR['setting_value']);
                    if ($_spR['setting_key'] === 'session_max_hours') $GLOBALS['afmSessionPolicy']['max_hours'] = max(0, (int)$_spR['setting_value']);
                    if ($_spR['setting_key'] === 'session_lock_minutes') $GLOBALS['afmSessionPolicy']['lock'] = max(0, (int)$_spR['setting_value']);
                }
            } catch (\Throwable $_spE) {}
        }
        $_spPol = $GLOBALS['afmSessionPolicy'];
        $_spScript = basename((string)($_SERVER['SCRIPT_NAME'] ?? ''));
        $_spPassive = ($_spScript === 'ping.php') || (($_REQUEST['id'] ?? '') === 'heartbeat');
        if ($_spPassive && empty($_REQUEST['active'])) {
            // keep the stamp of the last real activity
            $_SESSION['last_activity'] = $_SESSION['prev_activity'] ?? ($_SESSION['last_activity'] ?? time());
        }
        if (empty($_SESSION['session_login_at'])) { $_SESSION['session_login_at'] = time(); }
        $_spIdleFor = time() - (int)($_SESSION['prev_activity'] ?? time());
        $_spEnd = '';
        if ($_spPol['idle'] > 0 && $_spIdleFor > $_spPol['idle'] * 60 + 30) { $_spEnd = 'idle'; }
        if ($_spPol['max_hours'] > 0 && (time() - (int)$_SESSION['session_login_at']) > $_spPol['max_hours'] * 3600) { $_spEnd = 'max'; }
        if ($_spEnd !== '') {
            $_SESSION = [];
            @session_destroy();
            $_acc = $_SERVER['HTTP_ACCEPT'] ?? '';
            $_isXhr = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
            $_redir = "<script>try{window.top.location.href='index.php?ended=" . $_spEnd . "';}catch(e){window.location.href='index.php?ended=" . $_spEnd . "';}</script>";
            if (strpos($_acc, 'application/json') !== false) {
                if (!headers_sent()) { http_response_code(440); header('Content-Type: application/json'); }
                echo json_encode(['session_ended' => true, 'reason' => $_spEnd]);
            } elseif ($_isXhr) {
                echo $_redir;
            } else {
                if (!headers_sent()) { header('Location: index.php?ended=' . $_spEnd); }
                echo $_redir;
            }
            exit;
        }
        // ── (2026-10-22) Screen lock (System Settings → Session Timeout → "Lock the screen after"; DHCF Appendix 1(a) 2e/2f) ──
        // Idle longer than the lock time → the session is LOCKED, not ended: the page stays as it was under app.php's lock overlay,
        // and until the user's own password is given again (session_lock.php) every other request is refused with 423 — so the
        // record cannot be read or changed behind the overlay. A locked session is passive: it does not count as activity, so the
        // idle sign-out above still ends it in time.
        if ((int)($_spPol['lock'] ?? 0) > 0 && empty($_SESSION['afm_locked']) && $_spIdleFor > (int)$_spPol['lock'] * 60 + 30 && ($_SESSION['client'] ?? '') !== 'mobile') {
            $_SESSION['afm_locked'] = time();
        }
        // re-issue the session cookie so its expiry follows the policy, not the login time
        if (!headers_sent() && PHP_SAPI !== 'cli') {
            $_spLife = $_spPol['idle'] > 0 ? max(7200, $_spPol['idle'] * 60 + 600) : 86400;
            $_spHttps = (!empty($_SERVER['HTTPS']) && strtolower((string)$_SERVER['HTTPS']) !== 'off') || (int)($_SERVER['SERVER_PORT'] ?? 0) === 443 || strtolower((string)($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https';
            @setcookie(session_name(), session_id(), ['expires' => time() + $_spLife, 'path' => '/', 'domain' => '', 'secure' => $_spHttps, 'httponly' => true, 'samesite' => 'Lax']);
        }
        }
    }

    // ── (2026-10-22) Screen lock enforcement — on EVERY request (the policy block above runs only every 8 s, inside the
    // single-session throttle). While locked, nothing but the unlock call, the heartbeat, sign-out and the app shell answers. ──
    if (!empty($_SESSION['afm_locked'])) {
        $_SESSION['last_activity'] = $_SESSION['prev_activity'] ?? ($_SESSION['last_activity'] ?? time());
        $_lkScript = basename((string)($_SERVER['SCRIPT_NAME'] ?? ''));
        if (!in_array($_lkScript, ['session_lock.php', 'ping.php', 'logout.php', 'index.php', 'login.php', 'mfa.php', 'app.php', 'manifest.php', 'mobile_manifest.php', 'mobile_icon.php'], true) && PHP_SAPI !== 'cli') {
            $_lkAcc = $_SERVER['HTTP_ACCEPT'] ?? '';
            $_lkXhr = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
            if (!headers_sent()) { http_response_code(423); header('Cache-Control: no-store'); }
            if ($_lkXhr || strpos($_lkAcc, 'application/json') !== false) {
                if (!headers_sent()) header('Content-Type: application/json');
                echo json_encode(['locked' => true, 'message' => 'The screen is locked. Unlock it with your password.']);
            } else {
                echo '<!doctype html><meta charset="utf-8"><title>Screen locked</title><body style="font-family:Arial,sans-serif;padding:40px;color:#111">'
                   . '<h2>Screen locked</h2><p>Go back to the AfryxMed window and unlock it with your password.</p></body>';
            }
            exit;
        }
    }

    // ── Password expiry — configurable via system_settings (mig 233) ────
    //   pw_expiry_days       0 = never expire; N = expire after N days
    //   pw_expiry_mode       enforce (force a change) | warn (banner only) | off
    //   pw_expiry_warn_days  start warning this many days before expiry
    // Sets $_SESSION['pwd_expired'] (enforce), $_SESSION['pwd_expiry_warn']
    // (days left, or -1 = past due in warn mode) and $_SESSION['pwd_expiry_days']
    // (effective days, for the modal copy). NULL password_changed_at (new or
    // admin-reset accounts) counts as expired so a fresh password must be set.
    // Settings are read inline (acctSetting/functions.php may not be loaded yet).
    if (!isset($_SESSION['pwd_expired'])) {
        $_SESSION['pwd_expired'] = 0; $_SESSION['pwd_expiry_warn'] = 0; $_SESSION['pwd_expiry_days'] = 0;
        try {
            $_pwCfg = ['pw_expiry_days' => '30', 'pw_expiry_mode' => 'enforce', 'pw_expiry_warn_days' => '5'];
            foreach (($dbHelper->select("SELECT setting_key, setting_value FROM system_settings WHERE setting_key IN ('pw_expiry_days','pw_expiry_mode','pw_expiry_warn_days')") ?: []) as $_r) {
                if (isset($_r['setting_value']) && $_r['setting_value'] !== '') $_pwCfg[$_r['setting_key']] = $_r['setting_value'];
            }
            $_pwDays = max(0, (int)$_pwCfg['pw_expiry_days']);
            $_pwMode = strtolower(trim((string)$_pwCfg['pw_expiry_mode']));
            $_pwWarn = max(0, (int)$_pwCfg['pw_expiry_warn_days']);
            $_SESSION['pwd_expiry_days'] = $_pwDays;
            if ($_pwDays > 0 && $_pwMode !== 'off') {
                $_pcRow = $dbHelper->selectOne("SELECT password_changed_at FROM users WHERE name = ? LIMIT 1", [$_SESSION['valid_user']], "s");
                if ($_pcRow !== null) {
                    $_pc = $_pcRow['password_changed_at'] ?? '';
                    $_ageDays = empty($_pc) ? PHP_INT_MAX : (int)floor((time() - strtotime($_pc)) / 86400);
                    if ($_ageDays >= $_pwDays) {
                        if ($_pwMode === 'warn') { $_SESSION['pwd_expiry_warn'] = -1; }
                        else { $_SESSION['pwd_expired'] = 1; }
                    } elseif ($_pwWarn > 0 && $_ageDays >= ($_pwDays - $_pwWarn)) {
                        $_SESSION['pwd_expiry_warn'] = max(1, $_pwDays - $_ageDays);
                    }
                }
            }
        } catch (\Throwable $_pcEx) { $_SESSION['pwd_expired'] = 0; }
    }

    // Get user ID from database if not in session
    if (!isset($_SESSION['userid'])) {
        $userRow = $dbHelper->selectOne("SELECT userid FROM users WHERE name = ?", [$_SESSION['valid_user']], "s");
        $_SESSION['userid'] = $userRow['userid'] ?? 1;
    }
    
    $branchManager = new BranchManager($db, $dbHelper, $_SESSION['userid']);
    
    // Set current branch in session if not set
    if (!isset($_SESSION['current_branch_id'])) {
        $_SESSION['current_branch_id'] = $branchManager->getCurrentBranch();
    }
    
    // Make branch manager globally available
    $GLOBALS['branchManager'] = $branchManager;
    
    // Get current branch details for use throughout the application
    $currentBranchId = $_SESSION['current_branch_id'];
    $currentBranch = $branchManager->getBranchDetails($currentBranchId);
    
    // Set branch context variables for backward compatibility
    $userbranch = $currentBranch ? $currentBranch['branch_code'] : 'MAIN';
    $_SESSION['userbranch'] = $userbranch;
    $_SESSION['current_branch_name'] = $currentBranch ? $currentBranch['branch_name'] : 'Main Branch';

    // ── Workstation heartbeat ──
    // Stamp last_seen/last_user on the registered computer (compips) matching
    // this request's IP, throttled to once per 2 minutes per session. Powers
    // the online/offline status on the Departmental Computers page. Fails
    // silently on pre-migration-178 schemas.
    if (php_sapi_name() !== 'cli') {
        $_hbNow = time();
        if ((int)($_SESSION['_comp_hb'] ?? 0) < $_hbNow - 120) {
            $_SESSION['_comp_hb'] = $_hbNow;
            $_hbIp = $_SERVER['REMOTE_ADDR'] ?? '';
            if ($_hbIp !== '') {
                @mysqli_query($db, "UPDATE compips SET last_seen=NOW(), last_user='"
                    . mysqli_real_escape_string($db, (string)($_SESSION['valid_user'] ?? '')) . "' WHERE ip='"
                    . mysqli_real_escape_string($db, $_hbIp) . "'");
            }
        }
    }
}
?>
