<?php
// Configuration for large files
$upload_dir = "upload";
$max_file_size = 1024 * 1024 * 1024 * 10; // 10GB to start
$allowed_types = array(
    'jpg', 'jpeg', 'png', 'gif', 'pdf', 'txt', 
    'doc', 'docx', 'zip', 'rar', 'mp4', 'mp3', 'avi', 'mkv',
    'mov', 'wmv', 'flv', 'webm', 'm4v', '3gp', 'ogg', 'wav',
    'flac', 'aac', 'wma', 'm4a', 'psd', 'ai', 'eps', 'svg',
    'iso', 'dmg', 'exe', 'msi', 'tar', 'gz', '7z', 'bz2'
);

// Set longer execution time for this script
set_time_limit(7200); // 2 hours
ignore_user_abort(true);

// Create upload directory if it doesn't exist
if (!file_exists($upload_dir)) {
    @mkdir($upload_dir, 0755, true);
}

// Handle file upload
$upload_message = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['file'])) {
    // Simple check to see if we're dealing with a large file
    if ($_FILES['file']['size'] > 100 * 1024 * 1024) { // 100MB+
        $upload_message = handleLargeFileUpload($upload_dir, $max_file_size, $allowed_types);
    } else {
        $upload_message = handleFileUpload($upload_dir, $max_file_size, $allowed_types);
    }
}

// Handle file deletion
if (isset($_GET['delete'])) {
    $delete_message = handleFileDelete($upload_dir, $_GET['delete']);
    if ($delete_message) {
        $upload_message = $delete_message;
    }
}

// Get list of files
$files = getFileList($upload_dir);

function handleLargeFileUpload($upload_dir, $max_size, $allowed_types) {
    $file = $_FILES['file'];
    
    // Immediate error check
    if ($file['error'] !== UPLOAD_ERR_OK) {
        return getUploadError($file['error']);
    }
    
    // Check file size
    if ($file['size'] > $max_size) {
        return "Error: File is too large. Maximum size is " . formatFileSize($max_size);
    }
    
    // Check file type
    $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($file_extension, $allowed_types)) {
        return "Error: File type not allowed.";
    }
    
    // Sanitize filename
    $filename = preg_replace("/[^a-zA-Z0-9\._-]/", "_", $file['name']);
    $filepath = $upload_dir . '/' . $filename;
    
    // For large files, try to move immediately
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        return "Success: Large file uploaded successfully!";
    } else {
        // If move fails, check for common issues
        if (!is_writable($upload_dir)) {
            return "Error: Upload directory is not writable.";
        }
        return "Error: Failed to upload large file. This might be a server timeout.";
    }
}

function handleFileUpload($upload_dir, $max_size, $allowed_types) {
    $file = $_FILES['file'];
    
    // Check for upload errors
    if ($file['error'] !== UPLOAD_ERR_OK) {
        return getUploadError($file['error']);
    }
    
    // Check file size
    if ($file['size'] > $max_size) {
        return "Error: File is too large. Maximum size is " . formatFileSize($max_size);
    }
    
    // Check file type
    $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($file_extension, $allowed_types)) {
        return "Error: File type not allowed.";
    }
    
    // Sanitize filename
    $filename = preg_replace("/[^a-zA-Z0-9\._-]/", "_", $file['name']);
    $filepath = $upload_dir . '/' . $filename;
    
    // Move uploaded file
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        return "Success: File uploaded successfully!";
    } else {
        return "Error: Failed to upload file.";
    }
}

function handleFileDelete($upload_dir, $filename) {
    $filename = basename($filename);
    $filepath = $upload_dir . '/' . $filename;
    
    if (file_exists($filepath) && is_file($filepath)) {
        if (unlink($filepath)) {
            return "Success: File deleted successfully!";
        } else {
            return "Error: Could not delete file.";
        }
    }
    return "Error: File not found.";
}

function getFileList($upload_dir) {
    $files = array();
    if (is_dir($upload_dir)) {
        $items = scandir($upload_dir);
        foreach ($items as $item) {
            if ($item != '.' && $item != '..' && is_file($upload_dir . '/' . $item)) {
                $filepath = $upload_dir . '/' . $item;
                $files[] = array(
                    'name' => $item,
                    'size' => filesize($filepath),
                    'modified' => filemtime($filepath)
                );
            }
        }
    }
    return $files;
}

function getUploadError($error_code) {
    $errors = array(
        UPLOAD_ERR_INI_SIZE => 'File exceeds upload_max_filesize directive in php.ini',
        UPLOAD_ERR_FORM_SIZE => 'File exceeds MAX_FILE_SIZE directive in HTML form',
        UPLOAD_ERR_PARTIAL => 'File was only partially uploaded',
        UPLOAD_ERR_NO_FILE => 'No file was uploaded',
        UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary folder',
        UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
        UPLOAD_ERR_EXTENSION => 'File upload stopped by extension'
    );
    return isset($errors[$error_code]) ? "Error: " . $errors[$error_code] : "Unknown upload error";
}

function formatFileSize($bytes) {
    if ($bytes >= 1099511627776) {
        return number_format($bytes / 1099511627776, 2) . ' TB';
    } elseif ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } else {
        return $bytes . ' bytes';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload Manager - Large File Support</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f4f4f4;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        
        h1 {
            text-align: center;
            margin-bottom: 30px;
            color: #2c3e50;
        }
        
        .upload-section {
            background: #f8f9fa;
            padding: 25px;
            border-radius: 8px;
            margin-bottom: 30px;
            border: 2px dashed #dee2e6;
        }
        
        .server-info {
            background: #e7f3ff;
            border-left: 4px solid #007bff;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 4px;
        }
        
        .server-info ul {
            margin: 10px 0;
            padding-left: 20px;
        }
        
        .server-info li {
            margin-bottom: 5px;
        }
        
        .large-file-warning {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 4px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #495057;
        }
        
        input[type="file"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background: white;
        }
        
        .btn {
            display: inline-block;
            padding: 12px 24px;
            background: #007bff;
            color: white;
            text-decoration: none;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background 0.3s;
        }
        
        .btn:hover {
            background: #0056b3;
        }
        
        .btn-danger {
            background: #dc3545;
        }
        
        .btn-danger:hover {
            background: #c82333;
        }
        
        .btn-success {
            background: #28a745;
        }
        
        .btn-success:hover {
            background: #218838;
        }
        
        .message {
            padding: 12px;
            margin: 15px 0;
            border-radius: 4px;
            text-align: center;
        }
        
        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .files-section h2 {
            margin-bottom: 20px;
            color: #2c3e50;
        }
        
        .file-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
        }
        
        .file-item {
            background: white;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .file-name {
            font-weight: bold;
            margin-bottom: 10px;
            word-break: break-word;
        }
        
        .file-info {
            color: #6c757d;
            font-size: 14px;
            margin-bottom: 15px;
        }
        
        .file-actions {
            display: flex;
            gap: 10px;
        }
        
        .file-actions .btn {
            flex: 1;
            text-align: center;
            padding: 8px 16px;
            font-size: 14px;
        }
        
        .progress-bar {
            width: 100%;
            height: 20px;
            background: #e9ecef;
            border-radius: 10px;
            margin: 10px 0;
            overflow: hidden;
            display: none;
        }
        
        .progress {
            height: 100%;
            background: #007bff;
            width: 0%;
            transition: width 0.3s;
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }
            
            .file-list {
                grid-template-columns: 1fr;
            }
            
            .file-actions {
                flex-direction: column;
            }
            
            .btn {
                width: 100%;
                margin-bottom: 5px;
            }
        }
        
        @media (max-width: 480px) {
            body {
                padding: 10px;
            }
            
            .container {
                padding: 10px;
            }
            
            .upload-section {
                padding: 15px;
            }
            
            h1 {
                font-size: 24px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>File Upload Manager - Large File Support</h1>
        
        <div class="upload-section">
            <h2>Upload File (Max: 10GB)</h2>
            
            <div class="server-info">
                <p><strong>Server Limits:</strong></p>
                <ul>
                    <li>Max Upload Size: <?php echo ini_get('upload_max_filesize'); ?></li>
                    <li>Max Post Size: <?php echo ini_get('post_max_size'); ?></li>
                    <li>Execution Time: <?php echo ini_get('max_execution_time'); ?> seconds</li>
                </ul>
            </div>
            
            <div class="large-file-warning">
                <p><strong>For Large Files (100MB+):</strong></p>
                <ul>
                    <li>Keep this browser tab open during upload</li>
                    <li>Do not navigate away from this page</li>
                    <li>Uploads may take several minutes</li>
                    <li>Stable internet connection required</li>
                </ul>
            </div>
            
            <?php if ($upload_message): ?>
                <div class="message <?php echo strpos($upload_message, 'Success') !== false ? 'success' : 'error'; ?>">
                    <?php echo htmlspecialchars($upload_message); ?>
                </div>
            <?php endif; ?>
            
            <form action="" method="post" enctype="multipart/form-data" id="uploadForm">
                <div class="form-group">
                    <label for="file">Choose file to upload (Max: 10GB):</label>
                    <input type="file" name="file" id="file" required>
                </div>
                
                <div class="progress-bar" id="progressBar">
                    <div class="progress" id="progress"></div>
                </div>
                
                <button type="submit" class="btn" id="uploadBtn">Upload File</button>
            </form>
        </div>
        
        <div class="files-section">
            <h2>Uploaded Files</h2>
            
            <?php if (empty($files)): ?>
                <p>No files uploaded yet.</p>
            <?php else: ?>
                <div class="file-list">
                    <?php foreach ($files as $file): ?>
                        <div class="file-item">
                            <div class="file-name"><?php echo htmlspecialchars($file['name']); ?></div>
                            <div class="file-info">
                                Size: <?php echo formatFileSize($file['size']); ?><br>
                                Modified: <?php echo date('Y-m-d H:i:s', $file['modified']); ?>
                            </div>
                            <div class="file-actions">
                                <a href="<?php echo $upload_dir . '/' . urlencode($file['name']); ?>" 
                                   class="btn btn-success" download>Download</a>
                                <a href="?delete=<?php echo urlencode($file['name']); ?>" 
                                   class="btn btn-danger" 
                                   onclick="return confirm('Are you sure you want to delete <?php echo htmlspecialchars($file['name']); ?>?')">Delete</a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        document.getElementById('uploadForm').addEventListener('submit', function() {
            var progressBar = document.getElementById('progressBar');
            var progress = document.getElementById('progress');
            var uploadBtn = document.getElementById('uploadBtn');
            var fileInput = document.getElementById('file');
            
            // Show file size info
            var fileSize = fileInput.files[0].size;
            var fileSizeMB = (fileSize / (1024 * 1024)).toFixed(2);
            
            progressBar.style.display = 'block';
            uploadBtn.disabled = true;
            uploadBtn.textContent = 'Uploading ' + fileSizeMB + ' MB...';
            
            // Better progress simulation for large files
            var width = 0;
            var interval = setInterval(function() {
                if (width >= 95) {
                    clearInterval(interval);
                } else {
                    width += 1;
                    progress.style.width = width + '%';
                }
            }, 100);
        });
    </script>
</body>
</html>