<?php
/**
 * AUTO TESTER - Security Logging API
 * Logs security events for copy protection monitoring
 */

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

class SecurityLogger {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance();
    }
    
    /**
     * Log security event
     */
    public function logSecurityEvent($eventType, $data) {
        try {
            // Create security audit log entry
            $stmt = $this->db->prepare("
                INSERT INTO security_audit_log 
                (event_type, event_level, user_id, username, ip_address, user_agent, 
                 resource_accessed, action_performed, additional_data, created_at)
                VALUES (?, 'warning', ?, ?, ?, ?, ?, ?, ?, NOW())
            ");
            
            $stmt->execute([
                $eventType,
                $data['user_id'] ?? null,
                $this->getUsername($data['user_id'] ?? null),
                $_SERVER['REMOTE_ADDR'] ?? 'unknown',
                $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
                $data['url'] ?? '',
                $eventType,
                json_encode($data)
            ]);
            
            // Check for suspicious patterns
            $this->checkSuspiciousPatterns($eventType, $data);
            
            return ['success' => true];
            
        } catch (Exception $e) {
            // Log error but don't expose to user
            error_log("Security logging error: " . $e->getMessage());
            return ['success' => false];
        }
    }
    
    /**
     * Check for suspicious patterns
     */
    private function checkSuspiciousPatterns($eventType, $data) {
        $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
        $userId = $data['user_id'] ?? null;
        
        // Check for repeated violations
        $stmt = $this->db->prepare("
            SELECT COUNT(*) as violation_count 
            FROM security_audit_log 
            WHERE event_type = ? 
            AND (ip_address = ? OR user_id = ?)
            AND created_at >= DATE_SUB(NOW(), INTERVAL 1 HOUR)
        ");
        
        $stmt->execute([$eventType, $ip, $userId]);
        $result = $stmt->fetch();
        
        if ($result && $result['violation_count'] > 5) {
            $this->handleSuspiciousActivity($eventType, $data, $result['violation_count']);
        }
    }
    
    /**
     * Handle suspicious activity
     */
    private function handleSuspiciousActivity($eventType, $data, $violationCount) {
        // Create security alert
        $stmt = $this->db->prepare("
            INSERT INTO system_alerts 
            (alert_type, alert_level, alert_title, alert_message, alert_source, 
             component_affected, metric_data, notification_sent, created_at)
            VALUES (?, 'warning', ?, ?, ?, ?, ?, ?, NOW())
        ");
        
        $stmt->execute([
            'security',
            'Suspicious Activity Detected',
            "Multiple security violations detected: {$eventType}",
            "User has performed {$violationCount} violations in the last hour. IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'),
            'copy_protection',
            $eventType,
            json_encode($data),
            false
        ]);
        
        // Optional: Block IP or user temporarily
        if ($violationCount > 10) {
            $this->temporaryBlock($data['user_id'] ?? null, $_SERVER['REMOTE_ADDR'] ?? 'unknown');
        }
    }
    
    /**
     * Temporary block IP or user
     */
    private function temporaryBlock($userId, $ip) {
        $stmt = $this->db->prepare("
            INSERT INTO failed_login_attempts 
            (username, ip_address, attempt_time, failure_reason, is_blocked, block_expires_at)
            VALUES (?, ?, NOW(), 'security_violation', 1, DATE_ADD(NOW(), INTERVAL 1 HOUR))
            ON DUPLICATE KEY UPDATE 
            is_blocked = 1, 
            block_expires_at = DATE_ADD(NOW(), INTERVAL 1 HOUR),
            attempt_time = NOW()
        ");
        
        $stmt->execute([
            $this->getUsername($userId),
            $ip
        ]);
    }
    
    /**
     * Get username from user ID
     */
    private function getUsername($userId) {
        if (!$userId || $userId === 'anonymous') {
            return 'anonymous';
        }
        
        try {
            $stmt = $this->db->prepare("SELECT username FROM users WHERE id = ?");
            $stmt->execute([$userId]);
            $result = $stmt->fetch();
            return $result ? $result['username'] : 'unknown';
        } catch (Exception $e) {
            return 'unknown';
        }
    }
    
    /**
     * Get security statistics
     */
    public function getSecurityStats() {
        try {
            $stmt = $this->db->prepare("
                SELECT 
                    event_type,
                    COUNT(*) as event_count,
                    MAX(created_at) as last_occurrence,
                    COUNT(DISTINCT ip_address) as unique_ips,
                    COUNT(DISTINCT user_id) as unique_users
                FROM security_audit_log 
                WHERE created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
                GROUP BY event_type
                ORDER BY event_count DESC
            ");
            
            $stmt->execute();
            return ['success' => true, 'data' => $stmt->fetchAll()];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error'];
        }
    }
    
    /**
     * Get recent security events
     */
    public function getRecentEvents($limit = 50) {
        try {
            $stmt = $this->db->prepare("
                SELECT 
                    event_type,
                    event_level,
                    username,
                    ip_address,
                    action_performed,
                    additional_data,
                    created_at
                FROM security_audit_log 
                WHERE created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
                ORDER BY created_at DESC
                LIMIT ?
            ");
            
            $stmt->execute([$limit]);
            return ['success' => true, 'data' => $stmt->fetchAll()];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error'];
        }
    }
}

// API Handler
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET');
header('Access-Control-Allow-Headers: Content-Type');

$logger = new SecurityLogger();
$method = $_SERVER['REQUEST_METHOD'];

try {
    if ($method === 'POST') {
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (isset($data['event_type']) && isset($data['data'])) {
            echo json_encode($logger->logSecurityEvent($data['event_type'], $data['data']));
        } else {
            echo json_encode(['success' => false, 'message' => 'Missing required fields']);
        }
    } elseif ($method === 'GET') {
        $endpoint = $_GET['endpoint'] ?? '';
        
        switch ($endpoint) {
            case 'stats':
                echo json_encode($logger->getSecurityStats());
                break;
            case 'events':
                $limit = intval($_GET['limit'] ?? 50);
                echo json_encode($logger->getRecentEvents($limit));
                break;
            default:
                echo json_encode(['success' => false, 'message' => 'Invalid endpoint']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Server error']);
}
?>
