<?php

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

class Cregis_Logger {
    private $logger;
    private $debug_mode;
    
    public function __construct($debug_mode = false) {
        $this->debug_mode = $debug_mode;
        
        if (class_exists('WC_Logger')) {
            $this->logger = wc_get_logger();
        } else {
            $this->logger = null;
        }
    }
    
    /**
     * Log debug message
     */
    public function debug($message, $context = array()) {
        if ($this->debug_mode) {
            $this->log('debug', $message, $context);
        }
    }
    
    /**
     * Log info message
     */
    public function info($message, $context = array()) {
        $this->log('info', $message, $context);
    }
    
    /**
     * Log error message
     */
    public function error($message, $context = array()) {
        $this->log('error', $message, $context);
    }
    
    /**
     * Log warning message
     */
    public function warning($message, $context = array()) {
        $this->log('warning', $message, $context);
    }
    
    /**
     * Log message
     */
    private function log($level, $message, $context = array()) {
        if ($this->logger) {
            $this->logger->log($level, $message, array_merge($context, array('source' => 'cregis-payment-for-woocommerce')));
        } else {
            // Fallback to error_log if WC_Logger is not available
            $log_message = sprintf('[%s] [Cregis Payment] %s', strtoupper($level), $message);
            if (!empty($context)) {
                $log_message .= ' ' . print_r($context, true);
            }
            error_log($log_message);
        }
    }
    
    /**
     * Log API request
     */
    public function log_api_request($endpoint, $data) {
        $this->debug(sprintf('API Request to %s: %s', $endpoint, json_encode($data)));
    }
    
    /**
     * Log complete API request with all parameters
     */
    public function log_complete_api_request($endpoint, $request_data) {
        $this->debug(sprintf('Complete API Request to %s: %s', $endpoint, json_encode($request_data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)));
    }
    
    /**
     * Log API response
     */
    public function log_api_response($endpoint, $response) {
        $this->debug(sprintf('API Response from %s: %s', $endpoint, json_encode($response)));
    }
    
    /**
     * Log webhook request
     */
    public function log_webhook_request($data) {
        $this->info('Webhook received', $data);
    }
    
    /**
     * Log order status update
     */
    public function log_order_status_update($order_id, $status) {
        $this->info(sprintf('Order %s status updated to %s', $order_id, $status));
    }
}
