<?php

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';

/**
 * Logger class to handle API request logging
 */
class Logger {
    // Log levels
    const DEBUG = 'debug';
    const INFO = 'info';
    const WARNING = 'warning';
    const ERROR = 'error';
    
    /**
     * Log API request details
     * 
     * @param string $clientId Client ID
     * @param string $endpoint API endpoint
     * @param string $method HTTP method
     * @param int $statusCode HTTP status code
     * @param int $responseTime Response time in milliseconds
     * @param string $ipAddress Client IP address
     * @return bool Success state
     */
    public static function logApiRequest($clientId, $endpoint, $method, $statusCode, $responseTime, $ipAddress) {
        try {
            $db = Database::getApiConnection();
            
            $stmt = $db->prepare("
                INSERT INTO api_request_logs 
                (client_id, endpoint, method, status_code, response_time, ip_address) 
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->bind_param("sssiii", $clientId, $endpoint, $method, $statusCode, $responseTime, $ipAddress);
            
            $result = $stmt->execute();
            $stmt->close();
            
            return $result;
        } catch (Exception $e) {
            self::log(self::ERROR, "Failed to log API request: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Write log entry to file
     * 
     * @param string $level Log level
     * @param string $message Log message
     * @param array $context Additional context data
     */
    public static function log($level, $message, $context = []) {
        // Check if we should log this level based on configuration
        if (!self::shouldLog($level)) {
            return;
        }
        
        // Create logs directory if it doesn't exist
        if (!is_dir(LOG_DIRECTORY)) {
            mkdir(LOG_DIRECTORY, 0755, true);
        }
        
        $logFile = LOG_DIRECTORY . '/' . date('Y-m-d') . '.log';
        $timestamp = date('Y-m-d H:i:s');
        
        $contextString = '';
        if (!empty($context)) {
            $contextString = ' ' . json_encode($context);
        }
        
        $logEntry = "[{$timestamp}] [{$level}] {$message}{$contextString}" . PHP_EOL;
        
        file_put_contents($logFile, $logEntry, FILE_APPEND);
    }
    
    /**
     * Determine if we should log at the specified level
     * 
     * @param string $level Log level
     * @return bool Whether to log or not
     */
    private static function shouldLog($level) {
        $logLevels = [
            self::DEBUG => 0,
            self::INFO => 1,
            self::WARNING => 2,
            self::ERROR => 3
        ];
        
        $configLevel = strtolower(LOG_LEVEL);
        
        // If the level doesn't exist, default to logging everything
        if (!isset($logLevels[$configLevel])) {
            return true;
        }
        
        // Log if the current level is higher or equal to the configured level
        return $logLevels[$level] >= $logLevels[$configLevel];
    }
} 