<div class="row">
    <div class="col-lg-10 mx-auto">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-box-open me-2"></i>Import Produktów</h2>
            <a href="/samanta_crm/migration" class="btn btn-secondary">
                <i class="fas fa-arrow-left me-2"></i>Powrót
            </a>
        </div>

        <!-- Instructions -->
        <div class="alert alert-info">
            <h5><i class="fas fa-info-circle me-2"></i>Import Bazy Produktów</h5>
            <p class="mb-2">Importuj produkty z pliku CSV <code>produkty-baza-produktów-*.csv</code></p>
            <ul class="mb-0">
                <li><strong>Krok 1:</strong> Wybierz plik z bazą produktów</li>
                <li><strong>Krok 2:</strong> Sprawdź mapowanie kolumn w podglądzie</li>
                <li><strong>Krok 3:</strong> Potwierdź import do bazy danych</li>
            </ul>
            <p class="mb-0 mt-2">
                <i class="fas fa-lightbulb text-warning me-1"></i>
                <small><strong>Tip:</strong> Import zamówień z produktami jest dostępny w sekcji "Zamówienia Regularne"</small>
            </p>
        </div>

        <!-- File Selection Form -->
        <div class="card shadow-sm mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><i class="fas fa-upload me-2"></i>Wybierz Pliki CSV</h5>
            </div>
            <div class="card-body">
                <!-- File Source Selection -->
                <div class="mb-4">
                    <label class="form-label fw-bold">Źródło plików:</label>
                    <div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="file_source" id="source_upload" value="upload" checked>
                            <label class="form-check-label" for="source_upload">
                                <i class="fas fa-cloud-upload-alt me-1"></i>Upload plików
                            </label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="file_source" id="source_server" value="server">
                            <label class="form-check-label" for="source_server">
                                <i class="fas fa-server me-1"></i>Wybierz z serwera (migration_data/)
                            </label>
                        </div>
                    </div>
                </div>

                <form id="productMigrationForm">
                    <!-- Upload Mode -->
                    <div id="uploadMode">
                        <div class="mb-3">
                            <label for="products_base_file" class="form-label">
                                <i class="fas fa-database me-1"></i>Plik Bazy Produktów CSV
                                <span class="badge bg-primary">Wymagany</span>
                            </label>
                            <input type="file" class="form-control" id="products_base_file" name="products_base_file" accept=".csv">
                            <div class="form-text">
                                <strong>Kolumny:</strong> Nazwa, Kategoria, Kod, Cena, Za ceną, Status, Produkcja, ID pozycji, etc.
                                <br><strong>Przykład:</strong> <code>produkty-baza-produktów-2025-11-29.csv</code>
                            </div>
                        </div>
                    </div>

                    <!-- Server Mode -->
                    <div id="serverMode" style="display: none;">
                        <div class="mb-3">
                            <label for="products_base_path" class="form-label">
                                <i class="fas fa-database me-1"></i>Plik Bazy Produktów
                                <span class="badge bg-primary">Wymagany</span>
                            </label>
                            <select class="form-select" id="products_base_path" name="products_base_path">
                                <option value="">-- Wybierz plik --</option>
                                <?php if (!empty($csvFiles)): ?>
                                    <?php foreach ($csvFiles as $file): ?>
                                        <?php if (stripos($file, 'baza') !== false || stripos($file, 'produkty') !== false): ?>
                                            <option value="<?= htmlspecialchars($file) ?>"><?= htmlspecialchars(basename($file)) ?></option>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                            <div class="form-text">
                                Wybierz plik <code>produkty-baza-produktów-*.csv</code> z katalogu migration_data
                            </div>
                        </div>
                    </div>

                    <!-- Preview Button -->
                    <div class="d-grid gap-2">
                        <button type="button" class="btn btn-primary btn-lg" id="btnPreview">
                            <i class="fas fa-eye me-2"></i>Podgląd i Mapowanie Kolumn
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Progress Section -->
        <div id="progressSection" style="display: none;">
            <div class="card border-info">
                <div class="card-body">
                    <h5><i class="fas fa-spinner fa-spin me-2"></i>Przetwarzanie...</h5>
                    <div class="progress">
                        <div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
                    </div>
                    <div id="progressText" class="mt-2 text-muted"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Preview Modal -->
<div class="modal fade" id="previewModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">
                    <i class="fas fa-table me-2"></i>Podgląd Mapowania Produktów
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="previewContent">
                <div class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Ładowanie...</span>
                    </div>
                    <p class="mt-3 text-muted">Analizowanie plików CSV...</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-2"></i>Anuluj
                </button>
                <button type="button" class="btn btn-success" id="btnConfirmImport">
                    <i class="fas fa-check me-2"></i>Potwierdź Import
                </button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const sourceRadios = document.querySelectorAll('input[name="file_source"]');
    const uploadMode = document.getElementById('uploadMode');
    const serverMode = document.getElementById('serverMode');
    const btnPreview = document.getElementById('btnPreview');
    const previewModal = new bootstrap.Modal(document.getElementById('previewModal'));
    
    // Store file/path for import
    let importFileSource = null;
    let importFile = null;
    let importPath = null;
    
    // Toggle between upload and server mode
    sourceRadios.forEach(radio => {
        radio.addEventListener('change', function() {
            if (this.value === 'upload') {
                uploadMode.style.display = 'block';
                serverMode.style.display = 'none';
            } else {
                uploadMode.style.display = 'none';
                serverMode.style.display = 'block';
            }
        });
    });
    
    // Preview button
    btnPreview.addEventListener('click', function() {
        const fileSource = document.querySelector('input[name="file_source"]:checked').value;
        const formData = new FormData();
        formData.append('file_source', fileSource);
        
        if (fileSource === 'upload') {
            const baseFile = document.getElementById('products_base_file').files[0];
            
            if (!baseFile) {
                alert('Wybierz plik bazy produktów');
                return;
            }
            
            // Store for later import
            importFileSource = 'upload';
            importFile = baseFile;
            importPath = null;
            
            formData.append('products_base_file', baseFile);
        } else {
            const basePath = document.getElementById('products_base_path').value;
            
            if (!basePath) {
                alert('Wybierz plik bazy produktów');
                return;
            }
            
            // Store for later import
            importFileSource = 'server';
            importFile = null;
            importPath = basePath;
            
            formData.append('products_base_path', basePath);
        }
        
        // Show modal with loading state
        previewModal.show();
        
        // Fetch preview
        fetch('/samanta_crm/migration/preview-products', {
            method: 'POST',
            body: formData
        })
        .then(response => response.text())
        .then(html => {
            document.getElementById('previewContent').innerHTML = html;
        })
        .catch(error => {
            document.getElementById('previewContent').innerHTML = 
                '<div class="alert alert-danger"><i class="fas fa-exclamation-triangle me-2"></i>Błąd: ' + error.message + '</div>';
        });
    });
    
    // Confirm import button
    document.getElementById('btnConfirmImport').addEventListener('click', function() {
        if (!importFileSource) {
            alert('Najpierw kliknij "Podgląd i Mapowanie Kolumn"');
            return;
        }
        
        if (!confirm('Rozpocząć import produktów do bazy danych? To może zająć kilka minut.')) {
            return;
        }
        
        const formData = new FormData();
        formData.append('file_source', importFileSource);
        formData.append('confirm', '1');
        
        if (importFileSource === 'upload') {
            if (!importFile) {
                alert('Brak pliku. Wybierz plik ponownie.');
                return;
            }
            formData.append('products_base_file', importFile);
        } else {
            if (!importPath) {
                alert('Brak ścieżki. Wybierz plik ponownie.');
                return;
            }
            formData.append('products_base_path', importPath);
        }
        
        // Hide modal, show progress
        previewModal.hide();
        document.getElementById('progressSection').style.display = 'block';
        document.getElementById('progressText').textContent = 'Importowanie produktów...';
        
        // Start import
        fetch('/samanta_crm/migration/import-products', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            console.log('Response status:', response.status);
            if (!response.ok) {
                throw new Error('HTTP error ' + response.status);
            }
            return response.json();
        })
        .then(result => {
            console.log('Import result:', result);
            document.getElementById('progressSection').style.display = 'none';
            
            if (result.success) {
                alert('Sukces! ' + result.message);
                window.location.href = '/samanta_crm/products';
            } else {
                alert('Błąd: ' + result.message);
            }
        })
        .catch(error => {
            console.error('Import error:', error);
            document.getElementById('progressSection').style.display = 'none';
            alert('Błąd importu: ' + error.message + '\n\nSprawdź konsolę przeglądarki (F12) aby zobaczyć szczegóły.');
        });
    });
});
</script>
