<?php
/**
 * Audit Logger — Forensic Trail
 * Records EVERY significant action in the system.
 */

class AuditLogger {

    /**
     * Log an action to audit_logs table.
     * 
     * @param PDO $db
     * @param int|null $userId Who performed the action
     * @param string $action e.g., CREATED_PURCHASE, REVERSED_SALE, LOGIN
     * @param string|null $tableName Target table
     * @param int|null $recordId Target record
     * @param array|null $oldPayload Previous state (for updates)
     * @param array|null $newPayload New state
     * @param string|null $ip Client IP address
     */
    public static function log(
        PDO $db,
        ?int $userId,
        string $action,
        ?string $tableName = null,
        ?int $recordId = null,
        ?array $oldPayload = null,
        ?array $newPayload = null,
        ?string $ip = null
    ): void {
        try {
            $ip = $ip ?? ($_SERVER['REMOTE_ADDR'] ?? 'unknown');

            $stmt = $db->prepare("
                INSERT INTO audit_logs (user_id, action, table_name, record_id, old_payload, new_payload, ip_address)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");

            $stmt->execute([
                $userId,
                $action,
                $tableName,
                $recordId,
                $oldPayload ? json_encode($oldPayload, JSON_UNESCAPED_UNICODE) : null,
                $newPayload ? json_encode($newPayload, JSON_UNESCAPED_UNICODE) : null,
                $ip
            ]);
        } catch (Exception $e) {
            // Audit logging should NEVER break the main operation
            error_log("AuditLogger Error: " . $e->getMessage());
        }
    }
}
