/**
 * AUTO TESTER - Copy Protection System
 * Prevents copying, printing, and screenshots of sensitive content
 */

class CopyProtection {
    constructor() {
        this.init();
    }

    init() {
        this.disableTextSelection();
        this.disableContextMenu();
        this.disableKeyboardShortcuts();
        this.disableDragDrop();
        this.disablePrint();
        this.developerProtection();
        this.screenshotProtection();
        this.contentProtection();
        this.watermarkProtection();
        this.sessionMonitoring();
    }

    // Disable text selection
    disableTextSelection() {
        // CSS styles
        const style = document.createElement('style');
        style.textContent = `
            * {
                -webkit-user-select: none !important;
                -moz-user-select: none !important;
                -ms-user-select: none !important;
                user-select: none !important;
                -webkit-touch-callout: none !important;
                -webkit-tap-highlight-color: transparent !important;
            }
            
            input, textarea, [contenteditable] {
                -webkit-user-select: text !important;
                -moz-user-select: text !important;
                -ms-user-select: text !important;
                user-select: text !important;
            }
            
            ::selection {
                background: transparent !important;
                color: inherit !important;
            }
            
            ::-moz-selection {
                background: transparent !important;
                color: inherit !important;
            }
        `;
        document.head.appendChild(style);

        // JavaScript events
        document.addEventListener('selectstart', (e) => {
            if (!this.isInputElement(e.target)) {
                e.preventDefault();
                return false;
            }
        });

        document.addEventListener('mousedown', (e) => {
            if (e.detail > 1) { // Prevent double/triple click selection
                if (!this.isInputElement(e.target)) {
                    e.preventDefault();
                    return false;
                }
            }
        });

        document.addEventListener('selectstart', (e) => {
            if (!this.isInputElement(e.target)) {
                e.preventDefault();
                return false;
            }
        });
    }

    // Disable right-click context menu
    disableContextMenu() {
        document.addEventListener('contextmenu', (e) => {
            e.preventDefault();
            e.stopPropagation();
            return false;
        });

        // Prevent context menu on specific elements
        document.addEventListener('mousedown', (e) => {
            if (e.button === 2) { // Right click
                e.preventDefault();
                e.stopPropagation();
                return false;
            }
        });
    }

    // Disable keyboard shortcuts
    disableKeyboardShortcuts() {
        document.addEventListener('keydown', (e) => {
            // Prevent common copy shortcuts
            const forbiddenKeys = [
                e.ctrlKey && e.key === 'c',
                e.ctrlKey && e.key === 'C',
                e.ctrlKey && e.key === 'x',
                e.ctrlKey && e.key === 'X',
                e.ctrlKey && e.key === 'v',
                e.ctrlKey && e.key === 'V',
                e.ctrlKey && e.key === 'a',
                e.ctrlKey && e.key === 'A',
                e.ctrlKey && e.key === 's',
                e.ctrlKey && e.key === 'S',
                e.ctrlKey && e.key === 'p',
                e.ctrlKey && e.key === 'P',
                e.ctrlKey && e.shiftKey && e.key === 'I', // DevTools
                e.ctrlKey && e.shiftKey && e.key === 'J', // DevTools
                e.ctrlKey && e.shiftKey && e.key === 'C', // DevTools
                e.ctrlKey && e.shiftKey && e.key === 'K', // DevTools
                e.key === 'F12',
                e.metaKey && e.key === 'c', // Mac
                e.metaKey && e.key === 'C', // Mac
                e.metaKey && e.key === 'x', // Mac
                e.metaKey && e.key === 'X', // Mac
                e.metaKey && e.key === 'v', // Mac
                e.metaKey && e.key === 'V', // Mac
                e.metaKey && e.key === 'a', // Mac
                e.metaKey && e.key === 'A', // Mac
                e.metaKey && e.key === 's', // Mac
                e.metaKey && e.key === 'S', // Mac
                e.metaKey && e.key === 'p', // Mac
                e.metaKey && e.key === 'P'  // Mac
            ];

            // Allow these shortcuts for input elements
            if (this.isInputElement(e.target) && !e.ctrlKey && !e.metaKey) {
                return;
            }

            // Check if any forbidden key combination is pressed
            for (const forbidden of forbiddenKeys) {
                if (forbidden) {
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                }
            }
        });

        // Disable print screen
        document.addEventListener('keyup', (e) => {
            if (e.key === 'PrintScreen') {
                this.clearClipboard();
                e.preventDefault();
                return false;
            }
        });
    }

    // Disable drag and drop
    disableDragDrop() {
        document.addEventListener('dragstart', (e) => {
            e.preventDefault();
            return false;
        });

        document.addEventListener('drop', (e) => {
            e.preventDefault();
            return false;
        });

        document.addEventListener('dragover', (e) => {
            e.preventDefault();
            return false;
        });

        document.addEventListener('dragenter', (e) => {
            e.preventDefault();
            return false;
        });

        document.addEventListener('dragleave', (e) => {
            e.preventDefault();
            return false;
        });
    }

    // Disable printing
    disablePrint() {
        // CSS print styles
        const printStyle = document.createElement('style');
        printStyle.textContent = `
            @media print {
                body {
                    display: none !important;
                }
                
                * {
                    visibility: hidden !important;
                }
            }
        `;
        document.head.appendChild(printStyle);

        // JavaScript print events
        window.addEventListener('beforeprint', (e) => {
            e.preventDefault();
            document.body.innerHTML = '<div style="text-align: center; padding: 50px; font-family: Arial;">Printing is disabled for security reasons.</div>';
            return false;
        });

        window.addEventListener('afterprint', () => {
            location.reload();
        });

        // Override window.print
        window.print = function() {
            alert('Printing is disabled for security reasons.');
            return false;
        };
    }

    // Developer tools protection
    developerProtection() {
        // Console detection
        let devtools = {
            open: false,
            orientation: null
        };

        const threshold = 160;
        const emitEvent = (state, orientation) => {
            if (devtools.open !== state || devtools.orientation !== orientation) {
                devtools.open = state;
                devtools.orientation = orientation;
                if (state) {
                    this.handleDevToolsDetection();
                }
            }
        };

        setInterval(() => {
            if (window.outerHeight - window.innerHeight > threshold || 
                window.outerWidth - window.innerWidth > threshold) {
                if (!devtools.open) {
                    emitEvent(true, 'vertical');
                }
            } else {
                if (devtools.open) {
                    emitEvent(false, null);
                }
            }
        }, 500);

        // Console.log detection
        const originalLog = console.log;
        const originalWarn = console.warn;
        const originalError = console.error;
        const originalInfo = console.info;
        const originalDebug = console.debug;

        console.log = function() {
            this.handleConsoleDetection();
            return originalLog.apply(console, arguments);
        };

        console.warn = function() {
            this.handleConsoleDetection();
            return originalWarn.apply(console, arguments);
        };

        console.error = function() {
            this.handleConsoleDetection();
            return originalError.apply(console, arguments);
        };

        console.info = function() {
            this.handleConsoleDetection();
            return originalInfo.apply(console, arguments);
        };

        console.debug = function() {
            this.handleConsoleDetection();
            return originalDebug.apply(console, arguments);
        };
    }

    // Screenshot protection
    screenshotProtection() {
        // Disable screenshot APIs
        if (navigator.getDisplayMedia) {
            const originalGetDisplayMedia = navigator.getDisplayMedia;
            navigator.getDisplayMedia = function() {
                return Promise.reject(new Error('Screen capture is disabled for security reasons.'));
            };
        }

        if (navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) {
            const originalGetDisplayMedia = navigator.mediaDevices.getDisplayMedia;
            navigator.mediaDevices.getDisplayMedia = function() {
                return Promise.reject(new Error('Screen capture is disabled for security reasons.'));
            };
        }

        // Detect screenshot attempts
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
                this.handleScreenshotAttempt();
            }
        });

        // Detect window focus changes
        window.addEventListener('blur', () => {
            this.handleScreenshotAttempt();
        });

        // Prevent screen recording
        if ('screen' in window && 'orientation' in screen) {
            screen.orientation.addEventListener('change', () => {
                this.handleScreenshotAttempt();
            });
        }
    }

    // Content protection
    contentProtection() {
        // Prevent image copying
        document.addEventListener('mousedown', (e) => {
            if (e.target.tagName === 'IMG') {
                e.preventDefault();
                return false;
            }
        });

        // Prevent right-click on images
        document.addEventListener('contextmenu', (e) => {
            if (e.target.tagName === 'IMG') {
                e.preventDefault();
                return false;
            }
        });

        // Add transparent overlay to sensitive content
        this.addProtectionOverlay();
    }

    // Watermark protection
    watermarkProtection() {
        this.createWatermark();
    }

    // Session monitoring
    sessionMonitoring() {
        // Monitor for suspicious activity
        let suspiciousActivity = 0;
        const maxSuspiciousActivity = 10;

        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey || e.metaKey) {
                suspiciousActivity++;
                if (suspiciousActivity >= maxSuspiciousActivity) {
                    this.handleSuspiciousActivity();
                }
            }
        });

        document.addEventListener('contextmenu', () => {
            suspiciousActivity++;
            if (suspiciousActivity >= maxSuspiciousActivity) {
                this.handleSuspiciousActivity();
            }
        });
    }

    // Helper methods
    isInputElement(element) {
        const inputTags = ['INPUT', 'TEXTAREA', 'SELECT'];
        const editableElements = document.querySelectorAll('[contenteditable="true"]');
        
        return inputTags.includes(element.tagName) || 
               element.hasAttribute('contenteditable') ||
               element.closest('[contenteditable="true"]');
    }

    clearClipboard() {
        try {
            const textarea = document.createElement('textarea');
            textarea.value = 'Content copying is disabled.';
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand('copy');
            document.body.removeChild(textarea);
        } catch (e) {
            // Modern clipboard API
            if (navigator.clipboard) {
                navigator.clipboard.writeText('Content copying is disabled.');
            }
        }
    }

    addProtectionOverlay() {
        const overlay = document.createElement('div');
        overlay.id = 'copy-protection-overlay';
        overlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: 999999;
            background: transparent;
            display: none;
        `;
        document.body.appendChild(overlay);

        // Show overlay on potential copy attempts
        document.addEventListener('mousedown', () => {
            overlay.style.display = 'block';
            setTimeout(() => {
                overlay.style.display = 'none';
            }, 100);
        });
    }

    createWatermark() {
        const watermark = document.createElement('div');
        watermark.id = 'copy-protection-watermark';
        watermark.innerHTML = `
            <div style="
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%) rotate(-45deg);
                font-size: 100px;
                color: rgba(0, 0, 0, 0.1);
                pointer-events: none;
                z-index: 999998;
                font-weight: bold;
                white-space: nowrap;
                user-select: none;
            ">AUTO TESTER - CONFIDENTIAL</div>
        `;
        document.body.appendChild(watermark);
    }

    // Event handlers
    handleDevToolsDetection() {
        console.clear();
        console.log('%c WARNING: Developer tools detected!', 'color: red; font-size: 20px; font-weight: bold;');
        console.log('%c This action has been logged for security purposes.', 'color: red; font-size: 14px;');
        
        // Log to server
        this.logSecurityEvent('devtools_detected', {
            timestamp: new Date().toISOString(),
            userAgent: navigator.userAgent,
            url: window.location.href
        });

        // Optional: Redirect or take action
        // window.location.href = '/security-warning';
    }

    handleConsoleDetection() {
        this.logSecurityEvent('console_access', {
            timestamp: new Date().toISOString(),
            userAgent: navigator.userAgent,
            url: window.location.href
        });
    }

    handleScreenshotAttempt() {
        this.logSecurityEvent('screenshot_attempt', {
            timestamp: new Date().toISOString(),
            userAgent: navigator.userAgent,
            url: window.location.href
        });

        // Clear clipboard
        this.clearClipboard();
    }

    handleSuspiciousActivity() {
        this.logSecurityEvent('suspicious_activity', {
            timestamp: new Date().toISOString(),
            userAgent: navigator.userAgent,
            url: window.location.href,
            activity: 'Multiple copy attempts detected'
        });

        // Optional: Lock the page or redirect
        document.body.innerHTML = `
            <div style="
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100vh;
                font-family: Arial;
                text-align: center;
                background: #f5f5f5;
            ">
                <div>
                    <h1 style="color: #d32f2f;">Security Alert</h1>
                    <p>Suspicious activity detected. Access has been temporarily restricted.</p>
                    <p>Please contact your administrator if you believe this is an error.</p>
                </div>
            </div>
        `;
    }

    logSecurityEvent(eventType, data) {
        // Log to server
        fetch('/core/api/security-log.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                event_type: eventType,
                data: data,
                session_id: this.getSessionId(),
                user_id: this.getUserId()
            })
        }).catch(() => {
            // Silent fail to avoid detection
        });
    }

    getSessionId() {
        return sessionStorage.getItem('session_id') || 'anonymous';
    }

    getUserId() {
        return localStorage.getItem('user_id') || 'anonymous';
    }
}

// Initialize copy protection
document.addEventListener('DOMContentLoaded', () => {
    new CopyProtection();
});

// Additional protection for dynamic content
const observer = new MutationObserver(() => {
    // Re-apply protection if DOM changes
    new CopyProtection();
});

observer.observe(document.body, {
    childList: true,
    subtree: true
});

// Export for external use
window.CopyProtection = CopyProtection;
