<?php
error_log("DEBUG: functions.php is being loaded");
require_once __DIR__ . '/db.php';

function logAudit($action, $details = '') {
    $userName = $_SESSION['user_name'] ?? 'System';
    $userRole = $_SESSION['user_role'] ?? 'system';
    $companyId = $_SESSION['company_id'] ?? null;
    
    if (!$companyId && isset($_SESSION['user_id'])) {
        // Fallback: fetch company_id if not in session
        $u = fetch("SELECT company_id FROM users WHERE id = ?", [$_SESSION['user_id']]);
        if ($u) {
            $companyId = $u['company_id'];
            $_SESSION['company_id'] = $companyId;
        }
    }

    $sql = "INSERT INTO audit_logs (company_id, user_name, user_role, action, details, created_at) VALUES (?, ?, ?, ?, ?, NOW())";
    query($sql, [$companyId, $userName, $userRole, $action, $details]);
}

/**
 * Sanitizes output for HTML
 */
function e($text) {
    return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}

/**
 * Generates a clean URL
 */
function url($page = '', $params = []) {
    // Detect base path reliably across different entry points
    $script_name = $_SERVER['SCRIPT_NAME'];
    $base_dir = dirname($script_name);
    
    // Normalize base_dir to end with a single slash if it's not root
    if ($base_dir === DIRECTORY_SEPARATOR || $base_dir === '\\' || $base_dir === '/') {
        $base_dir = '/';
    } else {
        $base_dir = rtrim($base_dir, '/\\') . '/';
    }
    
    $url = $base_dir . ltrim($page, '/');
    
    if (!empty($params)) {
        $url .= '?' . http_build_query($params);
    }
    
    return $url;
}
