<?php
// ============================================================
//  MediCore — Audit Log Helper
//  File: includes/audit.php
//  Include after includes/db.php and includes/auth.php.
//  Provides log_action() — call it after any critical change.
// ============================================================

// ── Auto-create audit_logs table ───────────────────────────────
function ensure_audit_table(): void {
    static $checked = false;
    if ($checked) return; // only run the CREATE once per request
    $checked = true;

    db_run("CREATE TABLE IF NOT EXISTS audit_logs (
        id          INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        user_id     INT UNSIGNED,
        user_name   VARCHAR(100) DEFAULT '',
        action      VARCHAR(50)  NOT NULL,
        module      VARCHAR(50)  NOT NULL,
        record_id   INT UNSIGNED DEFAULT NULL,
        details     TEXT,
        ip_address  VARCHAR(45)  DEFAULT '',
        created_at  TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_user    (user_id),
        INDEX idx_module  (module),
        INDEX idx_action  (action),
        INDEX idx_created (created_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
}

/**
 * Log a critical action to the audit trail.
 *
 * @param string     $action    Short verb, e.g. 'create','update','delete','login','permission_change'
 * @param string     $module    Module/area, e.g. 'sales','purchases','settings','users','sale_returns'
 * @param int|null   $recordId  Related record ID (sale id, user id, etc.) — null if not applicable
 * @param string     $details   Free-text description, e.g. "Invoice INV-2025-0001 — ৳1,250.00"
 */
function log_action(string $action, string $module, ?int $recordId = null, string $details = ''): void {
    try {
        ensure_audit_table();

        $userId   = function_exists('current_user_id')   ? current_user_id()   : 0;
        $userName = function_exists('current_user_name') ? current_user_name() : 'System';
        $ip       = $_SERVER['REMOTE_ADDR'] ?? '';

        db_run(
            "INSERT INTO audit_logs (user_id, user_name, action, module, record_id, details, ip_address)
             VALUES (?,?,?,?,?,?,?)",
            [$userId ?: null, $userName, $action, $module, $recordId, $details, $ip]
        );
    } catch (Throwable $e) {
        // Audit logging must never break the main request — fail silently
        error_log('Audit log failed: ' . $e->getMessage());
    }
}
