@extends('layouts.admin')

@section('title', 'Install Plugin')

@section('content')
<div class="dashboard-header">
    <h1><i class="fas fa-download"></i> Install New Plugin</h1>
    <p>Upload and install new plugins to extend your application's functionality</p>
</div>

<div class="row">
    <div class="col-md-6">
        <!-- Upload Section -->
        <div class="dashboard-card">
            <div class="dashboard-card-header">
                <h3><i class="fas fa-cloud-upload-alt"></i> Upload Plugin</h3>
            </div>
            <div class="dashboard-card-body">
                <form id="pluginUploadForm" action="{{ route('admin.plugins.upload') }}" method="POST" enctype="multipart/form-data">
                    @csrf
                    <div class="plugin-upload-zone" id="uploadZone">
                        <div class="upload-zone-content">
                            <i class="fas fa-cloud-upload-alt upload-icon"></i>
                            <h4>Drag & Drop Plugin File Here</h4>
                            <p>or <button type="button" class="btn-link" id="browseBtn">browse for files</button></p>
                            <small class="text-muted">Supported format: ZIP files (max 10MB)</small>
                        </div>
                        <input type="file" id="pluginFile" name="plugin" accept=".zip" style="display: none;" required>
                    </div>
                    
                    <div class="upload-progress" id="uploadProgress" style="display: none;">
                        <div class="progress-bar">
                            <div class="progress-fill" id="progressFill"></div>
                        </div>
                        <div class="progress-text" id="progressText">Uploading...</div>
                    </div>
                    
                    <div class="upload-result" id="uploadResult" style="display: none;"></div>
                    
                    <div class="form-actions" style="display: none;" id="uploadActions">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-upload"></i> Install Plugin
                        </button>
                        <button type="button" class="btn btn-secondary" id="resetUpload">
                            <i class="fas fa-times"></i> Cancel
                        </button>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Installation Instructions -->
        <div class="dashboard-card">
            <div class="dashboard-card-header">
                <h3><i class="fas fa-info-circle"></i> Installation Requirements</h3>
            </div>
            <div class="dashboard-card-body">
                <div class="requirement-list">
                    <div class="requirement-item">
                        <i class="fas fa-check-circle text-success"></i>
                        <span>Plugin must be in ZIP format</span>
                    </div>
                    <div class="requirement-item">
                        <i class="fas fa-check-circle text-success"></i>
                        <span>Must contain a valid plugin.json manifest file</span>
                    </div>
                    <div class="requirement-item">
                        <i class="fas fa-check-circle text-success"></i>
                        <span>Must contain a Plugin.php main class file</span>
                    </div>
                    <div class="requirement-item">
                        <i class="fas fa-check-circle text-success"></i>
                        <span>File size must be under 10MB</span>
                    </div>
                </div>
                
                <div class="mt-4">
                    <h5>Plugin Structure Example:</h5>
                    <pre class="code-block"><code>MyPlugin.zip
├── plugin.json
├── Plugin.php
├── routes.php (optional)
├── Controllers/ (optional)
├── views/ (optional)
├── assets/ (optional)
└── migrations/ (optional)</code></pre>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-6">
        <!-- Quick Actions -->
        <div class="dashboard-card">
            <div class="dashboard-card-header">
                <h3><i class="fas fa-bolt"></i> Quick Actions</h3>
            </div>
            <div class="dashboard-card-body">
                <div class="quick-actions-list">
                    <a href="{{ route('admin.plugins.index') }}" class="quick-action-item">
                        <i class="fas fa-list"></i>
                        <span>View All Plugins</span>
                    </a>
                </div>
            </div>
        </div>
        
        <!-- Recent Installations -->
        <div class="dashboard-card">
            <div class="dashboard-card-header">
                <h3><i class="fas fa-history"></i> Recent Installations</h3>
            </div>
            <div class="dashboard-card-body">
                <div class="recent-installations">
                    @if(isset($recentInstallations) && count($recentInstallations) > 0)
                        @foreach($recentInstallations as $installation)
                        <div class="installation-item">
                            <div class="installation-icon">
                                <i class="fas fa-puzzle-piece"></i>
                            </div>
                            <div class="installation-info">
                                <div class="installation-name">{{ $installation['name'] }}</div>
                                <div class="installation-date">{{ $installation['date'] }}</div>
                            </div>
                            <div class="installation-status">
                                <span class="status-badge status-{{ $installation['status'] }}">
                                    {{ ucfirst($installation['status']) }}
                                </span>
                            </div>
                        </div>
                        @endforeach
                    @else
                        <div class="empty-recent">
                            <i class="fas fa-clock"></i>
                            <p>No recent installations</p>
                        </div>
                    @endif
                </div>
            </div>
        </div>
        
        <!-- Plugin Statistics -->
        <div class="dashboard-card">
            <div class="dashboard-card-header">
                <h3><i class="fas fa-chart-bar"></i> Plugin Statistics</h3>
            </div>
            <div class="dashboard-card-body">
                <div class="plugin-stats">
                    <div class="stat-row">
                        <span class="stat-label">Total Installed:</span>
                        <span class="stat-value">{{ $stats['total'] ?? 0 }}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">Currently Active:</span>
                        <span class="stat-value text-success">{{ $stats['active'] ?? 0 }}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">Updates Available:</span>
                        <span class="stat-value text-warning">{{ $stats['updates'] ?? 0 }}</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Success Modal -->
<div class="modal-backdrop" id="successModal">
    <div class="modal">
        <div class="modal-header">
            <h3><i class="fas fa-check-circle text-success"></i> Plugin Installed Successfully</h3>
            <button class="close-btn" type="button">&times;</button>
        </div>
        <div class="modal-body">
            <div class="success-content">
                <div class="plugin-success-info" id="successPluginInfo">
                    <!-- Plugin info will be populated here -->
                </div>
                <p class="mt-3">The plugin has been installed and is ready to use.</p>
            </div>
        </div>
        <div class="modal-footer">
            <a href="{{ route('admin.plugins.index') }}" class="btn btn-secondary">View All Plugins</a>
            <button class="btn btn-primary" id="configurePluginBtn">Configure Plugin</button>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const uploadZone = document.getElementById('uploadZone');
    const fileInput = document.getElementById('pluginFile');
    const browseBtn = document.getElementById('browseBtn');
    const uploadForm = document.getElementById('pluginUploadForm');
    const uploadProgress = document.getElementById('uploadProgress');
    const progressFill = document.getElementById('progressFill');
    const progressText = document.getElementById('progressText');
    const uploadResult = document.getElementById('uploadResult');
    const uploadActions = document.getElementById('uploadActions');
    const successModal = document.getElementById('successModal');
    const resetUploadBtn = document.getElementById('resetUpload');
    
    let currentUploadedPlugin = null;
    let droppedFile = null;
    
    // File input trigger
    browseBtn.addEventListener('click', (e) => {
        e.preventDefault();
        fileInput.click();
    });
    
    uploadZone.addEventListener('click', () => {
        if (!uploadZone.classList.contains('has-file')) {
            fileInput.click();
        }
    });
    
    // Drag and drop handlers
    uploadZone.addEventListener('dragover', handleDragOver);
    uploadZone.addEventListener('dragleave', handleDragLeave);
    uploadZone.addEventListener('drop', handleDrop);
    
    // File input change
    fileInput.addEventListener('change', function() {
        if (this.files.length > 0) {
            droppedFile = null; // Clear any dropped file
            handleFileSelection(this.files[0]);
        }
    });
    
    // Reset upload
    resetUploadBtn.addEventListener('click', function() {
        resetUploadForm();
    });
    
    function handleDragOver(e) {
        e.preventDefault();
        uploadZone.classList.add('drag-over');
    }
    
    function handleDragLeave(e) {
        e.preventDefault();
        uploadZone.classList.remove('drag-over');
    }
    
    function handleDrop(e) {
        e.preventDefault();
        uploadZone.classList.remove('drag-over');
        
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            droppedFile = files[0]; // Store the dropped file
            handleFileSelection(files[0]);
        }
    }
    
    function handleFileSelection(file) {
        // Validate file
        if (!file.name.toLowerCase().endsWith('.zip')) {
            showUploadResult('error', 'Please select a ZIP file.');
            return;
        }
        
        if (file.size > 10 * 1024 * 1024) { // 10MB
            showUploadResult('error', 'File size must be under 10MB.');
            return;
        }
        
        // Update upload zone to show file selected
        uploadZone.classList.add('has-file');
        uploadZone.innerHTML = `
            <div class="upload-zone-content">
                <i class="fas fa-file-archive upload-icon" style="color: #28a745;"></i>
                <h4>File Selected: ${file.name}</h4>
                <p>File size: ${(file.size / 1024 / 1024).toFixed(2)} MB</p>
                <small class="text-success">Ready to install</small>
            </div>
        `;
        
        uploadActions.style.display = 'flex';
        uploadResult.style.display = 'none';
    }
    
    // Form submission
    uploadForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        let fileToUpload = null;
        
        // Check if we have a dropped file or a selected file
        if (droppedFile) {
            fileToUpload = droppedFile;
            console.log('Using dropped file:', fileToUpload.name);
        } else if (fileInput.files.length > 0) {
            fileToUpload = fileInput.files[0];
            console.log('Using selected file:', fileToUpload.name);
        }
        
        if (!fileToUpload) {
            showUploadResult('error', 'Please select a file to upload.');
            return;
        }
        
        // Show progress
        uploadProgress.style.display = 'block';
        uploadResult.style.display = 'none';
        uploadZone.style.display = 'none';
        uploadActions.style.display = 'none';
        
        // Create FormData and add the file manually
        const formData = new FormData();
        formData.append('plugin', fileToUpload);
        formData.append('_token', document.querySelector('meta[name="csrf-token"]').content);
        
        // Upload with progress tracking
        const xhr = new XMLHttpRequest();
        
        xhr.upload.addEventListener('progress', function(e) {
            if (e.lengthComputable) {
                const percentComplete = (e.loaded / e.total) * 100;
                progressFill.style.width = percentComplete + '%';
                progressText.textContent = `Uploading... ${Math.round(percentComplete)}%`;
            }
        });
        
        xhr.addEventListener('load', function() {
            try {
                const response = JSON.parse(xhr.responseText);
                
                if (response.success) {
                    progressText.textContent = 'Installation complete!';
                    currentUploadedPlugin = response.plugin;
                    
                    setTimeout(() => {
                        uploadProgress.style.display = 'none';
                        showSuccessModal(response.plugin);
                    }, 1000);
                } else {
                    showUploadResult('error', response.message || 'Installation failed.');
                }
            } catch (e) {
                showUploadResult('error', 'An error occurred during upload.');
            }
        });
        
        xhr.addEventListener('error', function() {
            showUploadResult('error', 'Upload failed. Please try again.');
        });
        
        xhr.open('POST', uploadForm.action);
        xhr.setRequestHeader('X-CSRF-TOKEN', document.querySelector('meta[name="csrf-token"]').content);
        xhr.send(formData);
    });
    
    function showUploadResult(type, message) {
        uploadProgress.style.display = 'none';
        uploadZone.style.display = 'block';
        uploadResult.style.display = 'block';
        uploadActions.style.display = 'none';
        
        uploadResult.className = `upload-result alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible`;
        uploadResult.innerHTML = `
            <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i>
            ${message}
            <button type="button" class="alert-close" onclick="this.parentElement.style.display='none'">
                <i class="fas fa-times"></i>
            </button>
        `;
        
        // Reset progress
        progressFill.style.width = '0%';
        progressText.textContent = 'Uploading...';
        resetUploadForm();
    }
    
    function showSuccessModal(plugin) {
        const successPluginInfo = document.getElementById('successPluginInfo');
        const configureBtn = document.getElementById('configurePluginBtn');
        
        successPluginInfo.innerHTML = `
            <div class="plugin-success-card">
                <div class="plugin-icon">
                    ${plugin.icon ? `<img src="${plugin.icon}" alt="${plugin.display_name || plugin.name}">` : '<i class="fas fa-puzzle-piece"></i>'}
                </div>
                <div class="plugin-details">
                    <h4>${plugin.display_name || plugin.name}</h4>
                    <p>${plugin.description || 'No description available'}</p>
                    <div class="plugin-meta">
                        <span><strong>Version:</strong> ${plugin.version || '1.0.0'}</span>
                        <span><strong>Author:</strong> ${plugin.author || 'Unknown'}</span>
                    </div>
                </div>
            </div>
        `;
        
        configureBtn.onclick = () => {
            window.location.href = `{{ route('admin.plugins.show', '') }}/${plugin.name}`;
        };
        
        successModal.classList.add('active');
    }
    
    // Modal close handlers
    document.querySelectorAll('.close-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            successModal.classList.remove('active');
            resetUploadForm();
        });
    });
    
    // Close modal when clicking backdrop
    successModal.addEventListener('click', function(e) {
        if (e.target === this) {
            this.classList.remove('active');
            resetUploadForm();
        }
    });
    
    function resetUploadForm() {
        uploadProgress.style.display = 'none';
        uploadResult.style.display = 'none';
        uploadZone.style.display = 'block';
        uploadActions.style.display = 'none';
        uploadZone.classList.remove('has-file');
        fileInput.value = '';
        droppedFile = null;
        progressFill.style.width = '0%';
        progressText.textContent = 'Uploading...';
        
        // Reset upload zone content
        uploadZone.innerHTML = `
            <div class="upload-zone-content">
                <i class="fas fa-cloud-upload-alt upload-icon"></i>
                <h4>Drag & Drop Plugin File Here</h4>
                <p>or <button type="button" class="btn-link" id="browseBtn">browse for files</button></p>
                <small class="text-muted">Supported format: ZIP files (max 10MB)</small>
            </div>
        `;
        
        // Re-attach browse button event
        const newBrowseBtn = document.getElementById('browseBtn');
        if (newBrowseBtn) {
            newBrowseBtn.addEventListener('click', (e) => {
                e.preventDefault();
                fileInput.click();
            });
        }
    }
    
    // Quick actions
    document.getElementById('checkUpdatesBtn')?.addEventListener('click', function() {
        const btn = this;
        const originalContent = btn.innerHTML;
        
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i><span>Checking...</span>';
        btn.disabled = true;
        
        fetch('{{ route("admin.plugins.updates.check") }}')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('success', `Found ${data.updates.length} update(s) available.`);
            } else {
                showAlert('error', data.message);
            }
        })
        .catch(error => {
            showAlert('error', 'An error occurred while checking for updates.');
        })
        .finally(() => {
            btn.innerHTML = originalContent;
            btn.disabled = false;
        });
    });
    
    document.getElementById('downloadSampleBtn')?.addEventListener('click', function(e) {
        e.preventDefault();
        showAlert('info', 'Sample plugin download will be available soon.');
    });
    
    function showAlert(type, message) {
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type === 'success' ? 'success' : type === 'error' ? 'danger' : 'info'} alert-dismissible`;
        alertDiv.innerHTML = `
            <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
            ${message}
            <button type="button" class="alert-close" onclick="this.parentElement.remove()">
                <i class="fas fa-times"></i>
            </button>
        `;
        
        document.querySelector('.dashboard-header').insertAdjacentElement('afterend', alertDiv);
        
        setTimeout(() => {
            if (alertDiv.parentElement) {
                alertDiv.remove();
            }
        }, 5000);
    }
});
</script>
@endpush