<?php
/**
 * Security Helper Class
 * 
 * Handles security-related functionality like API key validation
 */
class Security {
    /**
     * Validate API key
     * 
     * @param string $apiKey The API key to validate
     * @return bool True if valid, false otherwise
     */
    public static function validateApiKey($apiKey) {
        $validKey = getenv('CRON_API_KEY');
        
        if (empty($validKey)) {
            error_log("CRON_API_KEY not set in environment");
            return false;
        }
        
        return hash_equals($validKey, $apiKey);
    }
    
    /**
     * Generate a secure random string
     * 
     * @param int $length Length of the string to generate
     * @return string Random string
     */
    public static function generateRandomString($length = 32) {
        return bin2hex(random_bytes($length / 2));
    }
    
    /**
     * Log security event
     * 
     * @param string $event Event name/type
     * @param array $data Additional event data
     * @return bool True if logged successfully
     */
    public static function logSecurityEvent($event, $data = []) {
        $logFile = __DIR__ . '/../logs/security.log';
        $logDir = dirname($logFile);
        
        // Create logs directory if it doesn't exist
        if (!is_dir($logDir)) {
            mkdir($logDir, 0755, true);
        }
        
        $logEntry = sprintf(
            "[%s] %s: %s\n",
            date('Y-m-d H:i:s'),
            $event,
            json_encode($data, JSON_PRETTY_PRINT)
        );
        
        return file_put_contents($logFile, $logEntry, FILE_APPEND) !== false;
    }
}
