<?php

namespace Pixeldev\SquareWooSync\Logger;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Debug Logger for immediate file-based logging.
 * Writes to a debug.log file in the plugin directory for tail-style review.
 */
class DebugLogger
{
    private static $log_file;
    private static $enabled = null;
    private static $max_file_size = 5242880; // 5MB

    private static function isEnabled()
    {
        if (self::$enabled === null) {
            self::$enabled = (defined('WP_DEBUG') && WP_DEBUG) || apply_filters('squarewoosync_debug_logging_enabled', false);
        }
        return self::$enabled;
    }

    public static function init()
    {
        self::$log_file = dirname(dirname(__DIR__)) . '/square-woo-sync-debug.log';

        if (!file_exists(self::$log_file)) {
            @touch(self::$log_file);
        }

        self::rotate_if_needed();
    }

    private static function rotate_if_needed()
    {
        if (!file_exists(self::$log_file)) {
            return;
        }

        $file_size = @filesize(self::$log_file);

        if ($file_size && $file_size > self::$max_file_size) {
            $lines = @file(self::$log_file);
            if ($lines && count($lines) > 1000) {
                $lines = array_slice($lines, -1000);
                @file_put_contents(self::$log_file, implode('', $lines), LOCK_EX);

                $notice = sprintf(
                    "[%s] ℹ [SYSTEM] INFO: Log rotated - kept last 1000 lines (previous size: %.2fMB)" . PHP_EOL,
                    date('Y-m-d H:i:s'),
                    $file_size / 1024 / 1024
                );
                @file_put_contents(self::$log_file, $notice, FILE_APPEND | LOCK_EX);
            }
        }
    }

    public static function log($category, $message, $context = [], $level = 'info')
    {
        if (!self::isEnabled()) {
            return;
        }

        if (!self::$log_file) {
            self::init();
        }

        $timestamp = date('Y-m-d H:i:s');
        $microtime = microtime(true);
        $milliseconds = sprintf("%03d", ($microtime - floor($microtime)) * 1000);

        $level_indicator = match ($level) {
            'error' => '✗',
            'warning' => '⚠',
            'success' => '✓',
            'debug' => '⚙',
            default => 'ℹ'
        };

        $log_entry = sprintf(
            "[%s.%s] %s [%s] %s: %s",
            $timestamp,
            $milliseconds,
            $level_indicator,
            strtoupper($category),
            strtoupper($level),
            $message
        );

        if (!empty($context)) {
            $log_entry .= " | Context: " . json_encode($context, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        }

        if (in_array($level, ['error', 'warning'])) {
            $memory      = round(memory_get_usage() / 1024 / 1024, 2) . 'MB';
            $peak_memory = round(memory_get_peak_usage() / 1024 / 1024, 2) . 'MB';
            $log_entry  .= sprintf(" | Memory: %s (Peak: %s)", $memory, $peak_memory);
        }

        $log_entry .= PHP_EOL;

        @file_put_contents(self::$log_file, $log_entry, FILE_APPEND | LOCK_EX);

        if ($level === 'error') {
            error_log("Square Woo Sync - " . $log_entry);
        }
    }

    public static function clear()
    {
        if (self::$log_file && file_exists(self::$log_file)) {
            @file_put_contents(self::$log_file, '');
            self::log('SYSTEM', 'Debug log cleared', [], 'info');
        }
    }

    public static function get_log_path()
    {
        if (!self::$log_file) {
            self::init();
        }
        return self::$log_file;
    }

    public static function setEnabled($enabled)
    {
        self::$enabled = (bool) $enabled;
    }

    public static function isLoggingEnabled()
    {
        return self::isEnabled();
    }

    public static function getFileSize()
    {
        if (!self::$log_file) {
            self::init();
        }

        if (file_exists(self::$log_file)) {
            return round(filesize(self::$log_file) / 1024 / 1024, 2);
        }

        return 0;
    }
}
