PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ]); if (session_status() === PHP_SESSION_NONE) { @session_start(); } if (isset($_SESSION['user_id'])) { $pdo->exec("SET @app_user_id = " . (int)$_SESSION['user_id']); } } // FORCE SET IT EVERY TIME db() IS CALLED just in case the connection was dropped or it wasn't set! if (isset($_SESSION['user_id']) && $pdo) { try { $pdo->exec("SET @app_user_id = " . (int)$_SESSION['user_id']); } catch (Exception $e) {} } return $pdo; } /** * Generates the next reference number for a given type (inbound/outbound/internal) * Format: IN-Year-Serial or OUT-Year-Serial or INT-Year-Serial */ function generateRefNo($type) { $prefix = 'IN'; $table = 'inbound_mail'; if ($type === 'outbound') { $prefix = 'OUT'; $table = 'outbound_mail'; } elseif ($type === 'internal') { $prefix = 'INT'; $table = 'internal_mail'; } $year = date('Y'); $pattern = $prefix . '-' . $year . '-%'; // Query the specific table for the type $stmt = db()->prepare("SELECT ref_no FROM $table WHERE ref_no LIKE ? ORDER BY id DESC LIMIT 1"); $stmt->execute([$pattern]); $last_ref = $stmt->fetchColumn(); $serial = 1; if ($last_ref) { $parts = explode('-', $last_ref); if (count($parts) === 3) { $serial = (int)$parts[2] + 1; } } return $prefix . '-' . $year . '-' . str_pad($serial, 3, '0', STR_PAD_LEFT); }