<?php
/**
 * Central Logger Helper
 * Logs events, errors, audits, and security alerts to daily rotating files in storage/logs/
 * Automatically scrubs passwords, tokens, bank accounts, and sensitive data
 */

require_once __DIR__ . '/Security.php';

class Logger {
    private static string $logDir = __DIR__ . '/../../storage/logs';

    public static function info(string $message, array $context = []): void {
        self::log('INFO', $message, $context);
    }

    public static function warning(string $message, array $context = []): void {
        self::log('WARNING', $message, $context);
    }

    public static function error(string $message, array $context = []): void {
        self::log('ERROR', $message, $context);
    }

    public static function critical(string $message, array $context = []): void {
        self::log('CRITICAL', $message, $context);
    }

    public static function audit(string $action, array $context = []): void {
        self::log('AUDIT', "Action: {$action}", $context);
    }

    public static function security(string $event, array $context = []): void {
        self::log('SECURITY', $event, $context);
    }

    public static function log(string $level, string $message, array $context = []): void {
        if (!is_dir(self::$logDir)) {
            @mkdir(self::$logDir, 0755, true);
        }

        $logFile = self::$logDir . '/cargoo-' . date('Y-m-d') . '.log';
        $timestamp = date('Y-m-d H:i:s');
        $ip = Security::getClientIp();
        $userId = $_SESSION['user_id'] ?? 'guest';

        // Scrub sensitive values from context
        $scrubbedContext = self::scrubSensitiveData($context);
        $contextJson = !empty($scrubbedContext) ? ' | Context: ' . json_encode($scrubbedContext, JSON_UNESCAPED_UNICODE) : '';

        $logEntry = sprintf(
            "[%s] [%s] [IP: %s] [User: %s] %s%s%s",
            $timestamp,
            strtoupper($level),
            $ip,
            $userId,
            $message,
            $contextJson,
            PHP_EOL
        );

        @file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
    }

    /**
     * Recursively mask sensitive fields (passwords, tokens, bank accounts)
     */
    public static function scrubSensitiveData(array $data): array {
        $securityConfig = file_exists(__DIR__ . '/../../config/security.php')
            ? require __DIR__ . '/../../config/security.php'
            : [];
        $scrubKeys = $securityConfig['scrub_keys'] ?? [
            'password', 'confirm_password', 'current_password', 'new_password',
            'token', 'csrf_token', 'secret', 'api_key', 'bank_account_no', 'cvv'
        ];

        $cleaned = [];
        foreach ($data as $key => $value) {
            $lowerKey = strtolower((string)$key);
            $shouldScrub = false;

            foreach ($scrubKeys as $sKey) {
                if (strpos($lowerKey, $sKey) !== false) {
                    $shouldScrub = true;
                    break;
                }
            }

            if ($shouldScrub) {
                $cleaned[$key] = '********';
            } elseif (is_array($value)) {
                $cleaned[$key] = self::scrubSensitiveData($value);
            } else {
                $cleaned[$key] = $value;
            }
        }

        return $cleaned;
    }
}
