<?php

if (!function_exists('progress_log')) {
    /**
     * Write a progress log entry to a file in the project root
     *
     * @param string|array|object $message The message or data to log
     * @param array|object|null $context Optional context data
     * @return void
     */
    function progress_log($message, $context = null): void {
        try {
            // Get the project root path
            $rootPath = base_path();
            $logsDir = $rootPath . DIRECTORY_SEPARATOR . 'logs';
            
            // Create logs directory if it doesn't exist
            if (!is_dir($logsDir)) {
                @mkdir($logsDir, 0777, true);
            }
            
            $logFile = $logsDir . DIRECTORY_SEPARATOR . 'progress.log';
            
            $timestamp = date('Y-m-d H:i:s');
            
            // Normalize message
            if (is_array($message) || is_object($message)) {
                $message = json_encode($message, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
            }
            
            // Normalize context (optional extra data)
            if ($context !== null) {
                if (is_array($context) || is_object($context)) {
                    $context = json_encode($context, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
                }
                $message .= ' | CONTEXT: ' . $context;
            }
            
            $line = "[{$timestamp}] {$message}" . PHP_EOL;
            
            // Append atomically
            file_put_contents($logFile, $line, FILE_APPEND | LOCK_EX);
            
        } catch (Throwable $e) {
            // Never allow logging failures to break execution
            // Silent by design
        }
    }
}

