<?php

use App\Core\Database;

/*
--------------------------------------------------
Unified Audit Logger
--------------------------------------------------
Supports both legacy and extended calls
--------------------------------------------------
*/

if (!function_exists('audit_log')) {

    function audit_log(
        string $action,
        ?string $entity = null,
        ?int $entityId = null,
        $details = null
    ): void {

        /*
        Session safety
        */

        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        /*
        User detection (supports both session formats)
        */

        $userId = null;
        $orgId  = null;

        if (isset($_SESSION['user_id'])) {

            $userId =
                (int)$_SESSION['user_id'];

            $orgId =
                $_SESSION['org_id'] ?? null;

        }
        elseif (isset($_SESSION['user'])) {

            $userId =
                (int)($_SESSION['user']['id'] ?? 0);

            $orgId =
                $_SESSION['user']['org_id'] ?? null;

        }

        if (!$userId) {
            return;
        }

        /*
        Database
        */

        $db =
            Database::getInstance();

        /*
        Normalize details
        */

        if (is_array($details)) {

            $details =
                json_encode($details);

        }

        /*
        Insert audit record
        */

        $db->prepare("
            INSERT INTO audit_logs
            (
                user_id,
                action,
                entity_name,
                entity_id,
                details,
                ip_address,
                user_agent,
                org_id,
                created_at
            )
            VALUES
            (?, ?, ?, ?, ?, ?, ?, ?, NOW())
        ")
        ->execute([

            $userId,

            $action,

            $entity,

            $entityId,

            $details,

            $_SERVER['REMOTE_ADDR']
                ?? '',

            $_SERVER['HTTP_USER_AGENT']
                ?? '',

            $orgId

        ]);

    }

}
