/**
 * Global jQuery FileUpload CSRF Token Fix
 * This script automatically adds CSRF tokens to all jQuery fileupload requests
 */

$(document).ready(function() {
    'use strict';
    
    // Global variable to store PHP upload configuration
    var phpUploadConfig = null;
    
    // Fetch PHP upload configuration
    function loadUploadConfig() {
        $.ajax({
            url: '/api/v1/files/config',
            method: 'GET',
            success: function(response) {
                if (response.success && response.data) {
                    phpUploadConfig = response.data;
                    // Make config globally available for directive
                    window.phpUploadConfig = phpUploadConfig;
                    console.log('[FileUpload] PHP upload config loaded:', phpUploadConfig);
                } else {
                    console.warn('[FileUpload] Failed to load PHP config, using defaults');
                }
            },
            error: function(xhr, status, error) {
                console.warn('[FileUpload] Error loading PHP config:', error, '- using defaults');
            }
        });
    }
    
    // Load config immediately
    loadUploadConfig();
    
    // Handle server-side errors for file uploads
    $(document).ajaxError(function(event, xhr, settings) {
        if (settings.url && settings.url.indexOf('files/upload') !== -1) {
            var errorMessage = '';
            
            switch(xhr.status) {
                case 413:
                    var maxSizeText = '10MB'; // Default fallback
                    if (phpUploadConfig && phpUploadConfig.effective_max_filesize_mb) {
                        maxSizeText = phpUploadConfig.effective_max_filesize_mb + 'MB';
                    }
                    errorMessage = 'File is too large. Maximum size allowed is ' + maxSizeText + '.';
                    break;
                case 415:
                    errorMessage = 'This file type is not allowed.';
                    break;
                case 422:
                    errorMessage = 'Invalid file. Please try a different file.';
                    break;
                case 419:
                    errorMessage = 'Session expired. Please refresh the page and try again.';
                    break;
                default:
                    if (xhr.responseJSON && xhr.responseJSON.error) {
                        errorMessage = xhr.responseJSON.error;
                    } else {
                        errorMessage = 'Upload failed. Please try again.';
                    }
            }
            
            // Show persistent error message
            if (window.Messenger) {
                try {
                    Messenger().post({
                        message: errorMessage,
                        hideAfter: 0,
                        type: 'error',
                        showCloseButton: true,
                        theme: 'air',
                        extraClasses: 'messenger-fixed messenger-on-top messenger-on-right'
                    });
                } catch(e) {
                    Messenger(errorMessage, 'error');
                }
            }
            
            console.log('[FileUpload] Server error:', xhr.status, errorMessage);
        }
    });
    
    // Override jQuery fileupload globally to add CSRF token and related parameters
    $(document).ajaxSend(function(event, xhr, options) {
        // Only target file upload requests
        if (options.url && options.url.indexOf('files/upload') !== -1) {
            console.log('[FileUpload CSRF] Intercepting file upload request');
            
            // Add CSRF token to headers
            var token = window.CSRFManager ? window.CSRFManager.getToken() : $('meta[name="csrf-token"]').attr('content');
            if (token) {
                xhr.setRequestHeader('X-CSRF-TOKEN', token);
                console.log('[FileUpload CSRF] Added CSRF token to headers');
            }
            
            // Modify FormData directly if it exists
            if (options.data && options.data instanceof FormData) {
                console.log('[FileUpload CSRF] Found FormData, adding CSRF token and related params');
                
                // Add CSRF token to FormData
                if (token) {
                    options.data.append('_token', token);
                    console.log('[FileUpload CSRF] Added _token to FormData');
                }
                
                // Find the file input element to get related_id and related_type
                var $fileInput = $('input[type="file"][fileupload]');
                if ($fileInput.length > 0) {
                    var relatedId = $fileInput.attr('data-related-id');
                    var relatedType = $fileInput.attr('data-related-type');
                    
                    if (relatedId) {
                        options.data.append('related_id', relatedId);
                        console.log('[FileUpload CSRF] Added related_id to FormData:', relatedId);
                    }
                    
                    if (relatedType) {
                        options.data.append('related_type', relatedType);
                        console.log('[FileUpload CSRF] Added related_type to FormData:', relatedType);
                    }
                }
            }
        }
    });
    
    // File type validation
    function validateFileType(file) {
        // Define allowed file types (safe files only)
        var allowedExtensions = [
            // Images
            'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg',
            // Documents
            'pdf', 'txt', 'rtf', 'xml',
            // Microsoft Office
            'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx',
            // OpenOffice/LibreOffice
            'odt', 'ods', 'odp',
            // Archives (be cautious)
            'zip', 'rar', '7z'
        ];
        
        // Blocked dangerous extensions
        var blockedExtensions = [
            // Executables
            'exe', 'bat', 'cmd', 'com', 'scr', 'msi', 'dll',
            // Scripts
            'js', 'vbs', 'vb', 'wsf', 'wsh', 'ps1', 'ps2',
            // Server-side scripts
            'php', 'php3', 'php4', 'php5', 'phtml', 'asp', 'aspx', 'jsp', 'py', 'rb', 'pl', 'cgi',
            // System files
            'sys', 'ini', 'cfg', 'conf',
            // Mac executables
            'app', 'dmg', 'pkg',
            // Linux executables
            'sh', 'run', 'deb', 'rpm'
        ];
        
        var fileName = file.name.toLowerCase();
        var extension = fileName.split('.').pop();
        
        // Check if file has blocked extension
        if (blockedExtensions.indexOf(extension) !== -1) {
            return {
                valid: false,
                message: 'This file type is not allowed for security reasons.'
            };
        }
        
        // Check if file has allowed extension
        if (allowedExtensions.indexOf(extension) === -1) {
            return {
                valid: false,
                message: 'This file type is not allowed. Please use images, PDF, text, or Office documents.'
            };
        }
        
        // Additional checks for file size using dynamic PHP configuration
        var maxSize = 10 * 1024 * 1024; // Default fallback: 10MB
        var maxSizeText = '10MB';
        
        // Use dynamic PHP config if available
        if (phpUploadConfig && phpUploadConfig.effective_max_filesize_bytes) {
            maxSize = phpUploadConfig.effective_max_filesize_bytes;
            maxSizeText = phpUploadConfig.effective_max_filesize_mb + 'MB';
        }
        
        if (file.size > maxSize) {
            return {
                valid: false,
                message: 'File is too large. Maximum size allowed is ' + maxSizeText + '.'
            };
        }
        
        return { valid: true };
    }
    
    // Override fileupload widget to add ONLY progress tracking
    // DISABLED: Too complex, try direct approach
    if (false && $.fn.fileupload) {
        var originalFileupload = $.fn.fileupload;
        
        $.fn.fileupload = function(options) {
            if (typeof options === 'object') {
                var $element = this;
                
                // Add file validation - intercept BEFORE any UI updates
                var originalAdd = options.add;
                options.add = function(e, data) {
                    // Validate each file first, before any UI changes
                    var validFiles = [];
                    var invalidCount = 0;
                    
                    $.each(data.files, function(index, file) {
                        var validation = validateFileType(file);
                        if (validation.valid) {
                            validFiles.push(file);
                        } else {
                            invalidCount++;
                            // Show error message immediately
                            if (window.Messenger) {
                                try {
                                    Messenger().post({
                                        message: validation.message,
                                        hideAfter: 0,
                                        type: 'error',
                                        showCloseButton: true,
                                        theme: 'air',
                                        extraClasses: 'messenger-fixed messenger-on-top messenger-on-right'
                                    });
                                } catch(e) {
                                    // Fallback to simple Messenger call
                                    Messenger(validation.message, 'error');
                                }
                            } else {
                                alert(validation.message);
                            }
                            console.log('[FileUpload] File validation failed:', file.name, validation.message);
                        }
                    });
                    
                    // If no valid files, completely prevent the add operation
                    if (validFiles.length === 0) {
                        console.log('[FileUpload] No valid files, completely preventing upload operation');
                        // Don't call original add function at all - this prevents UI updates
                        return false;
                    }
                    
                    // Only proceed if we have valid files
                    if (validFiles.length > 0) {
                        // Create new data object with only valid files
                        var newData = $.extend({}, data, {
                            files: validFiles
                        });
                        
                        console.log('[FileUpload] Proceeding with', validFiles.length, 'valid files (rejected', invalidCount, 'invalid files)');
                        
                        // Call original add function with filtered files
                        if (typeof originalAdd === 'function') {
                            return originalAdd.call(this, e, newData);
                        }
                        
                        // If no original add function, we need to handle it ourselves
                        // This shouldn't happen in normal fileupload widgets
                        console.warn('[FileUpload] No original add function found');
                    }
                };
                
                // Add our custom formData function that includes related_id and related_type
                var originalFormData = options.formData;
                options.formData = function(form) {
                    var data = [];
                    
                    // Include original formData if it exists
                    if (typeof originalFormData === 'function') {
                        data = originalFormData.call(this, form) || [];
                    } else if (Array.isArray(originalFormData)) {
                        data = originalFormData.slice();
                    }
                    
                    // Add CSRF token
                    var token = window.CSRFManager ? window.CSRFManager.getToken() : $('meta[name="csrf-token"]').attr('content');
                    if (token) {
                        data.push({name: '_token', value: token});
                    }
                    
                    // Add related_id and related_type from input attributes
                    var relatedId = $element.attr('data-related-id') || $element.data('relatedId');
                    var relatedType = $element.attr('data-related-type') || $element.data('relatedType');
                    
                    if (relatedId) {
                        data.push({name: 'related_id', value: relatedId});
                        console.log('[FileUpload CSRF] Added related_id:', relatedId);
                    }
                    
                    if (relatedType) {
                        data.push({name: 'related_type', value: relatedType});
                        console.log('[FileUpload CSRF] Added related_type:', relatedType);
                    }
                    
                    console.log('[FileUpload CSRF] Final formData:', data);
                    return data;
                };
            }
            
            return originalFileupload.call(this, options);
        };
        
        // Copy over any static properties
        $.extend($.fn.fileupload, originalFileupload);
    }
    
    // Direct file input validation to prevent invalid files from even starting the upload process
    // TEMPORARILY DISABLED to check if causing 400 errors
    if (false) $(document).on('change', 'input[type="file"][fileupload]', function(e) {
        var $input = $(this);
        var files = e.target.files;
        
        if (!files || files.length === 0) {
            return;
        }
        
        console.log('[FileUpload] Direct change event triggered for', files.length, 'files');
        
        var validFiles = [];
        var hasInvalidFiles = false;
        
        // Validate each selected file
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            var validation = validateFileType(file);
            
            if (!validation.valid) {
                hasInvalidFiles = true;
                // Show error message
                if (window.Messenger) {
                    try {
                        Messenger().post({
                            message: validation.message,
                            hideAfter: 0,
                            type: 'error',
                            showCloseButton: true,
                            theme: 'air',
                            extraClasses: 'messenger-fixed messenger-on-top messenger-on-right'
                        });
                    } catch(err) {
                        Messenger(validation.message, 'error');
                    }
                }
                console.log('[FileUpload] Direct validation failed:', file.name, validation.message);
            } else {
                validFiles.push(file);
            }
        }
        
        // If ANY files are invalid, clear the input and prevent all uploads
        if (hasInvalidFiles) {
            console.log('[FileUpload] Clearing file input due to validation failures');
            
            // Clear the input immediately and synchronously
            $input.val('');
            
            // Also clear any files that might have been added to Angular scope
            var $scope = $input.scope();
            if ($scope && $scope.files && Array.isArray($scope.files)) {
                // Remove any files that were just added
                $scope.$apply(function() {
                    // Clear all files that were added in this operation
                    var originalLength = $scope.files.length;
                    $scope.files = $scope.files.filter(function(file) {
                        // Remove files that don't have an ID (newly added)
                        return file.id;
                    });
                    
                    if ($scope.files.length < originalLength) {
                        console.log('[FileUpload] Removed', (originalLength - $scope.files.length), 'invalid files from scope');
                    }
                });
            }
            
            // Prevent the event from continuing
            e.preventDefault();
            e.stopPropagation();
            e.stopImmediatePropagation();
            return false;
        }
    });
    
    // Track upload progress and handle responses
    var uploadingFiles = {}; // Track files being uploaded
    
    console.log('[FileUpload] Progress tracking system initialized');
    
    // Listen for upload start and add progress tracking with XHR events
    $(document).ajaxSend(function(event, xhr, settings) {
        if (settings.url && settings.url.indexOf('files/upload') !== -1) {
            console.log('[FileUpload] Upload starting, adding progress tracking');
            
            // Find the file input and add progress file to scope
            $('input[type="file"][fileupload]').each(function() {
                var $input = $(this);
                var $scope = $input.scope();
                var files = $input[0].files;
                
                if ($scope && $scope.files && Array.isArray($scope.files) && files && files.length > 0) {
                    var file = files[0];
                    var progressFile = {
                        name: file.name,
                        size: file.size,
                        progress: 1 // Start with 1% to ensure progress bar appears
                    };
                    
                    // Add to scope for progress display
                    $scope.$apply(function() {
                        $scope.files.push(progressFile);
                        console.log('[FileUpload] Added progress file to scope:', file.name);
                    });
                    
                    // Track this upload
                    uploadingFiles[file.name] = progressFile;
                    
                    // Add progress tracking to XHR
                    if (xhr.upload) {
                        xhr.upload.addEventListener('progress', function(e) {
                            if (e.lengthComputable) {
                                var percentComplete = Math.round((e.loaded / e.total) * 100);
                                
                                // Update progress file object
                                progressFile.progress = percentComplete;
                                
                                console.log('[FileUpload] Progress update:', file.name, percentComplete + '%', 'progress object:', progressFile);
                                
                                // Force Angular scope update
                                try {
                                    if (!$scope.$$phase) {
                                        $scope.$apply();
                                    }
                                } catch (e) {
                                    // Ignore apply errors
                                    console.log('[FileUpload] $apply error (safe to ignore):', e);
                                }
                            }
                        }, false);
                        
                        console.log('[FileUpload] XHR progress listener attached for:', file.name);
                    } else {
                        console.log('[FileUpload] No xhr.upload available for progress tracking');
                    }
                }
            });
        }
    });
    
    // Listen for successful upload responses and update Angular scope
    $(document).ajaxSuccess(function(event, xhr, settings) {
        if (settings.url && settings.url.indexOf('files/upload') !== -1) {
            console.log('[FileUpload] Successful upload detected, checking response');
            try {
                var response = JSON.parse(xhr.responseText);
                if (response && response.id) {
                    console.log('[FileUpload] File uploaded successfully:', response);
                    
                    // Find and replace the progress file with the real file
                    $('input[type="file"][fileupload]').each(function() {
                        var $input = $(this);
                        var $scope = $input.scope();
                        
                        if ($scope && $scope.files && Array.isArray($scope.files)) {
                            $scope.$apply(function() {
                                // Find the progress file and replace it
                                var progressFile = uploadingFiles[response.name];
                                if (progressFile) {
                                    var index = $scope.files.indexOf(progressFile);
                                    if (index !== -1) {
                                        $scope.files[index] = response;
                                        console.log('[FileUpload] Replaced progress file with real file:', response.name);
                                    } else {
                                        $scope.files.push(response);
                                        console.log('[FileUpload] Added file to Angular scope:', response.name);
                                    }
                                    delete uploadingFiles[response.name];
                                } else {
                                    $scope.files.push(response);
                                    console.log('[FileUpload] Added file to Angular scope:', response.name);
                                }
                            });
                        }
                    });
                }
            } catch (e) {
                console.log('[FileUpload] Could not parse upload response:', e);
            }
        }
    });
    
    // Simple cleanup function to remove only "Unknown" failed files
    setInterval(function() {
        $('input[type="file"][fileupload]').each(function() {
            var $input = $(this);
            var $scope = $input.scope();
            
            if ($scope && $scope.files && Array.isArray($scope.files)) {
                // Only remove files that are clearly failed (have name "Unknown" or similar patterns)
                var originalLength = $scope.files.length;
                $scope.files = $scope.files.filter(function(file) {
                    // Keep files with ID (successfully uploaded)
                    if (file.id) {
                        return true;
                    }
                    
                    // Keep files that have active progress (currently uploading)
                    if (file.progress && file.progress > 0 && file.progress < 100) {
                        return true;
                    }
                    
                    // Remove files with generic "Unknown" name (clearly failed)
                    if (file.name === 'Unknown' || !file.name) {
                        console.log('[FileUpload] Cleanup: Removing failed upload with unknown name:', file);
                        return false;
                    }
                    
                    // Keep everything else (don't be too aggressive)
                    console.log('[FileUpload] Cleanup: Keeping file:', file.name, 'ID:', file.id, 'Progress:', file.progress);
                    return true;
                });
                
                if ($scope.files.length < originalLength) {
                    try {
                        if (!$scope.$$phase) {
                            $scope.$apply();
                        }
                    } catch(e) {
                        // Ignore $apply errors
                    }
                }
            }
        });
    }, 3000); // Run every 3 seconds (much less frequent)
    
    // Direct approach: Configure existing fileupload widgets
    $(document).ready(function() {
        $('input[type="file"][fileupload]').each(function() {
            var $input = $(this);
            var $scope = $input.scope();
            
            if ($scope) {
                
                // Try to reconfigure the existing fileupload widget
                try {
                    $input.fileupload({
                        add: function(e, data) {
                            if ($scope && $scope.files) {
                                var file = data.files[0];
                                var _file = {
                                    name: file.name, 
                                    size: file.size, 
                                    progress: 1,
                                    creator: {
                                        name: 'Uploading...'
                                    }
                                };
                                
                                $scope.$apply(function() {
                                    $scope.files.push(_file);
                                });
                                
                                data._file = _file;
                            }
                            
                            data.submit();
                        },
                        progress: function(e, data) {
                            if (data._file) {
                                var progress = parseInt(data.loaded / data.total * 100, 10);
                                data._file.progress = progress;
                                
                                if ($scope && !$scope.$$phase) {
                                    $scope.$apply();
                                }
                            }
                        },
                        done: function(e, data) {
                            // Remove progress file, let success handler add real file
                            if (data._file && $scope && $scope.files) {
                                $scope.$apply(function() {
                                    var index = $scope.files.indexOf(data._file);
                                    if (index !== -1) {
                                        $scope.files.splice(index, 1);
                                    }
                                });
                            }
                        },
                        fail: function(e, data) {
                            // Remove progress file when upload fails
                            if (data._file && $scope && $scope.files) {
                                $scope.$apply(function() {
                                    var index = $scope.files.indexOf(data._file);
                                    if (index !== -1) {
                                        $scope.files.splice(index, 1);
                                    }
                                });
                            }
                        }
                    });
                } catch (e) {
                    console.log('[FileUpload] Error configuring fileupload widget:', e);
                }
            }
        });
    });
    
    console.log('[FileUpload CSRF] Global CSRF token handlers initialized');
});