<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Import Zamówień - Migration Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 2rem 0;
        }
        .container {
            max-width: 1200px;
        }
        .card {
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        .mapping-table th {
            background: #f8f9fa;
            position: sticky;
            top: 0;
        }
        .mapping-table select {
            width: 100%;
            min-width: 200px;
        }
        .section-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 10px 15px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        .preview-data {
            max-height: 300px;
            overflow-y: auto;
        }
        .stats-card {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <div class="d-flex justify-content-between align-items-center">
                    <h4 class="mb-0">
                        <i class="fas fa-shopping-cart"></i>
                        Import Zamówień
                    </h4>
                    <a href="/migration" class="btn btn-light btn-sm">
                        <i class="fas fa-arrow-left"></i> Powrót
                    </a>
                </div>
            </div>
            <div class="card-body">
                <!-- File Source Selection -->
                <div class="mb-4">
                    <h5>Wybierz źródło pliku:</h5>
                    <div class="btn-group w-100" role="group">
                        <input type="radio" class="btn-check" name="file_source" id="source_upload" value="upload" checked>
                        <label class="btn btn-outline-primary" for="source_upload">
                            <i class="fas fa-upload"></i> Prześlij plik
                        </label>
                        <input type="radio" class="btn-check" name="file_source" id="source_server" value="server">
                        <label class="btn btn-outline-primary" for="source_server">
                            <i class="fas fa-server"></i> Z serwera
                        </label>
                    </div>
                </div>

                <!-- Upload Mode -->
                <div id="upload_mode" class="file-mode">
                    <div class="mb-3">
                        <label class="form-label fw-bold">Plik CSV z zamówieniami:</label>
                        <input type="file" class="form-control" id="orders_file" accept=".csv">
                        <small class="text-muted">
                            Plik zawiera zarówno zamówienia jak i pozycje zamówień
                        </small>
                    </div>
                </div>

                <!-- Server Mode -->
                <div id="server_mode" class="file-mode" style="display: none;">
                    <div class="mb-3">
                        <label class="form-label fw-bold">Wybierz plik z serwera:</label>
                        <select class="form-select" id="orders_path">
                            <option value="">-- Wybierz plik --</option>
                            <?php foreach ($csvFiles as $file): ?>
                                <option value="<?= htmlspecialchars($file) ?>">
                                    <?= htmlspecialchars(basename($file)) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <!-- Action Buttons -->
                <div class="d-grid gap-2">
                    <button class="btn btn-info btn-lg" id="preview_btn">
                        <i class="fas fa-eye"></i> Podgląd i Mapowanie Kolumn
                    </button>
                    <button class="btn btn-success btn-lg" id="import_btn" style="display: none;">
                        <i class="fas fa-download"></i> Potwierdź Import
                    </button>
                </div>

                <!-- Progress Section -->
                <div id="progress_section" class="mt-4" style="display: none;">
                    <div class="alert alert-info">
                        <i class="fas fa-spinner fa-spin"></i> Importowanie danych...
                    </div>
                </div>

                <!-- Result Section -->
                <div id="result_section" class="mt-4" style="display: none;"></div>
            </div>
        </div>
    </div>

    <!-- Preview Modal -->
    <div class="modal fade" id="previewModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Podgląd i Mapowanie Kolumn</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="preview_content">
                    <!-- Preview content will be loaded here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Anuluj</button>
                    <button type="button" class="btn btn-success" id="confirm_mapping_btn">
                        <i class="fas fa-check"></i> Zatwierdź Mapowanie i Importuj
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let previewModal;
        let importFileSource = null;
        let importFile = null;
        let importPath = null;

        document.addEventListener('DOMContentLoaded', function() {
            previewModal = new bootstrap.Modal(document.getElementById('previewModal'));

            // Toggle file source
            document.querySelectorAll('input[name="file_source"]').forEach(radio => {
                radio.addEventListener('change', function() {
                    document.getElementById('upload_mode').style.display = 
                        this.value === 'upload' ? 'block' : 'none';
                    document.getElementById('server_mode').style.display = 
                        this.value === 'server' ? 'block' : 'none';
                });
            });

            // Preview button
            document.getElementById('preview_btn').addEventListener('click', async function() {
                const fileSource = document.querySelector('input[name="file_source"]:checked').value;
                const formData = new FormData();
                formData.append('file_source', fileSource);

                if (fileSource === 'upload') {
                    const file = document.getElementById('orders_file').files[0];
                    if (!file) {
                        alert('Wybierz plik CSV');
                        return;
                    }
                    formData.append('orders_file', file);
                    importFile = file;
                } else {
                    const path = document.getElementById('orders_path').value;
                    if (!path) {
                        alert('Wybierz plik z listy');
                        return;
                    }
                    formData.append('orders_path', path);
                    importPath = path;
                }

                importFileSource = fileSource;

                try {
                    const response = await fetch('/samanta_crm/migration/preview-orders', {
                        method: 'POST',
                        body: formData
                    });

                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }

                    const html = await response.text();
                    document.getElementById('preview_content').innerHTML = html;
                    previewModal.show();
                } catch (error) {
                    console.error('Preview error:', error);
                    alert('Błąd podczas wczytywania podglądu: ' + error.message);
                }
            });

            // Confirm mapping and import
            document.getElementById('confirm_mapping_btn').addEventListener('click', async function() {
                previewModal.hide();
                
                // Collect manual mapping
                const orderMapping = {};
                const itemMapping = {};
                
                document.querySelectorAll('select[name^="order_field_"]').forEach(select => {
                    const dbField = select.name.replace('order_field_', '');
                    if (select.value) {
                        orderMapping[dbField] = select.value;
                    }
                });
                
                document.querySelectorAll('select[name^="item_field_"]').forEach(select => {
                    const dbField = select.name.replace('item_field_', '');
                    if (select.value) {
                        itemMapping[dbField] = select.value;
                    }
                });

                const formData = new FormData();
                formData.append('file_source', importFileSource);
                formData.append('order_mapping', JSON.stringify(orderMapping));
                formData.append('item_mapping', JSON.stringify(itemMapping));

                if (importFileSource === 'upload') {
                    formData.append('orders_file', importFile);
                } else {
                    formData.append('orders_path', importPath);
                }

                document.getElementById('progress_section').style.display = 'block';
                document.getElementById('result_section').style.display = 'none';

                try {
                    const response = await fetch('/samanta_crm/migration/import-orders', {
                        method: 'POST',
                        body: formData
                    });

                    const result = await response.json();
                    
                    document.getElementById('progress_section').style.display = 'none';
                    document.getElementById('result_section').style.display = 'block';

                    if (result.success) {
                        document.getElementById('result_section').innerHTML = `
                            <div class="alert alert-success">
                                <h5><i class="fas fa-check-circle"></i> ${result.message}</h5>
                                <hr>
                                <p class="mb-0">
                                    <strong>Zamówienia:</strong> ${result.stats.orders_imported} zaimportowano, ${result.stats.orders_skipped} pominięto<br>
                                    <strong>Pozycje:</strong> ${result.stats.items_imported} zaimportowano, ${result.stats.items_skipped} pominięto
                                </p>
                                ${result.stats.errors.length > 0 ? `
                                    <hr>
                                    <strong>Błędy:</strong>
                                    <ul class="mb-0 small">
                                        ${result.stats.errors.slice(0, 10).map(err => `<li>${err}</li>`).join('')}
                                        ${result.stats.errors.length > 10 ? `<li>...i ${result.stats.errors.length - 10} więcej</li>` : ''}
                                    </ul>
                                ` : ''}
                            </div>
                        `;
                    } else {
                        document.getElementById('result_section').innerHTML = `
                            <div class="alert alert-danger">
                                <h5><i class="fas fa-exclamation-circle"></i> Błąd</h5>
                                <p>${result.message}</p>
                            </div>
                        `;
                    }
                } catch (error) {
                    console.error('Import error:', error);
                    document.getElementById('progress_section').style.display = 'none';
                    document.getElementById('result_section').style.display = 'block';
                    document.getElementById('result_section').innerHTML = `
                        <div class="alert alert-danger">
                            <h5><i class="fas fa-exclamation-circle"></i> Błąd importu</h5>
                            <p>${error.message}</p>
                        </div>
                    `;
                }
            });
        });
    </script>
</body>
</html>
