<div class="row">
    <div class="col-lg-8 mx-auto">
        <div class="mb-4">
            <a href="/samanta_crm/migration" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left me-2"></i>Powrót do wyboru importu
            </a>
        </div>

        <h2 class="mb-4"><i class="fas fa-receipt me-2"></i>Import Zamówień Regularnych</h2>
        
        <!-- Regular Orders Import Card -->
        <div class="card">
            <div class="card-header bg-success text-white">
                <h4 class="mb-0"><i class="fas fa-file-import me-2"></i>Import z 2 Plików CSV</h4>
            </div>
            <div class="card-body">
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i>
                    <strong>Wymagane 2 pliki CSV:</strong>
                    <ul class="mb-0 mt-2">
                        <li><strong>Plik Zamówień:</strong> order_id, customer_name, customer_phone, customer_email, customer_address, order_date, order_time, delivery_date, order_type, status, notes, <code>ID pozycji</code></li>
                        <li><strong>Plik Produktów:</strong> <code>Parent Entry ID</code>, Nazwa, Ilość, Id (product ID)</li>
                        <li><strong>Połączenie:</strong> Parent Entry ID (produkty) = ID pozycji (zamówienia)</li>
                        <li>System automatycznie połączy zamówienia z produktami</li>
                        <li>Duplikaty (na podstawie Old Order ID) zostaną pominięte</li>
                    </ul>
                </div>

                <div class="alert alert-warning">
                    <i class="fas fa-book me-2"></i>
                    <strong>Potrzebujesz pomocy?</strong><br>
                    Zobacz plik: <code>migration_data/README_IMPORT_INSTRUCTIONS.md</code><br>
                    Szablon pliku zamówień: <code>migration_data/TEMPLATE_orders.csv</code>
                </div>

                <?php if (isset($_SESSION['migration_errors'])): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>Wystąpiły błędy podczas importu</strong>
                    <p class="mb-2">Liczba błędów: <?= count($_SESSION['migration_errors']) ?></p>
                    <a href="/samanta_crm/migration/download-report" class="btn btn-sm btn-danger">
                        <i class="fas fa-download me-1"></i>Pobierz raport błędów
                    </a>
                </div>
                <?php unset($_SESSION['migration_errors']); ?>
                <?php endif; ?>

                <form method="POST" action="/samanta_crm/migration/import-orders" enctype="multipart/form-data" class="mt-4">
                    <input type="hidden" name="offset" value="0">
                    
                    <!-- File Selection Method -->
                    <div class="mb-4">
                        <label class="form-label fw-bold">
                            <i class="fas fa-question-circle me-1"></i>Sposób wyboru plików
                        </label>
                        <div class="btn-group w-100" role="group">
                            <input type="radio" class="btn-check" name="file_method" id="method_upload" value="upload" checked>
                            <label class="btn btn-outline-primary" for="method_upload">
                                <i class="fas fa-upload me-1"></i>Prześlij pliki
                            </label>
                            
                            <input type="radio" class="btn-check" name="file_method" id="method_server" value="server">
                            <label class="btn btn-outline-success" for="method_server">
                                <i class="fas fa-folder me-1"></i>Wybierz z serwera (migration_data)
                            </label>
                        </div>
                    </div>

                    <!-- Upload Method -->
                    <div id="upload_section">
                        <div class="mb-4">
                            <label for="orders_file" class="form-label">
                                <i class="fas fa-file-csv me-1 text-primary"></i>
                                <strong>1. Plik CSV z zamówieniami (główny)</strong>
                            </label>
                            <input type="file" 
                                   class="form-control form-control-lg" 
                                   id="orders_file" 
                                   name="orders_file" 
                                   accept=".csv">
                            <div class="form-text">
                                Plik zawierający podstawowe informacje o zamówieniach (klient, daty, status)
                            </div>
                        </div>

                        <div class="mb-4">
                            <label for="items_file" class="form-label">
                                <i class="fas fa-file-csv me-1 text-success"></i>
                                <strong>2. Plik CSV z produktami w zamówieniach</strong>
                            </label>
                            <input type="file" 
                                   class="form-control form-control-lg" 
                                   id="items_file" 
                                   name="items_file" 
                                   accept=".csv">
                            <div class="form-text">
                                Plik z kolumną "Parent Entry ID" wskazującą na order_id z pierwszego pliku
                            </div>
                        </div>
                    </div>

                    <!-- Server Method -->
                    <div id="server_section" style="display: none;">
                        <div class="mb-4">
                            <label for="orders_file_server" class="form-label">
                                <i class="fas fa-file-csv me-1 text-primary"></i>
                                <strong>1. Plik CSV z zamówieniami (główny)</strong>
                            </label>
                            <select class="form-select form-select-lg" id="orders_file_server" name="orders_file_server">
                                <option value="">-- Wybierz plik zamówień --</option>
                                <?php
                                $migrationDir = __DIR__ . '/../../../migration_data/';
                                if (is_dir($migrationDir)) {
                                    $files = glob($migrationDir . '*.csv');
                                    foreach ($files as $file) {
                                        $filename = basename($file);
                                        echo '<option value="' . htmlspecialchars($filename) . '">' . htmlspecialchars($filename) . '</option>';
                                    }
                                }
                                ?>
                            </select>
                            <div class="form-text">
                                Wybierz plik z folderu migration_data/
                            </div>
                        </div>

                        <div class="mb-4">
                            <label for="items_file_server" class="form-label">
                                <i class="fas fa-file-csv me-1 text-success"></i>
                                <strong>2. Plik CSV z produktami w zamówieniach</strong>
                            </label>
                            <select class="form-select form-select-lg" id="items_file_server" name="items_file_server">
                                <option value="">-- Wybierz plik produktów --</option>
                                <?php
                                if (is_dir($migrationDir)) {
                                    $files = glob($migrationDir . '*.csv');
                                    foreach ($files as $file) {
                                        $filename = basename($file);
                                        echo '<option value="' . htmlspecialchars($filename) . '">' . htmlspecialchars($filename) . '</option>';
                                    }
                                }
                                ?>
                            </select>
                            <div class="form-text">
                                Wybierz plik z folderu migration_data/
                            </div>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label for="batch_size" class="form-label">
                            <i class="fas fa-layer-group me-1"></i>Rozmiar paczki
                        </label>
                        <select class="form-select" id="batch_size" name="batch_size">
                            <option value="25">25 rekordów</option>
                            <option value="50" selected>50 rekordów</option>
                            <option value="100">100 rekordów</option>
                            <option value="200">200 rekordów</option>
                        </select>
                        <div class="form-text">
                            Mniejsze paczki są bezpieczniejsze dla dużych plików
                        </div>
                    </div>

                    <div class="d-grid gap-2">
                        <button type="button" class="btn btn-info btn-lg mb-2" id="previewBtn">
                            <i class="fas fa-eye me-2"></i>Podgląd danych i mapowania
                        </button>
                        <button type="submit" class="btn btn-success btn-lg" id="submitBtn">
                            <i class="fas fa-upload me-2"></i>Rozpocznij Import Zamówień Regularnych
                        </button>
                    </div>
                </form>
            </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 bg-info text-white">
                        <h5 class="modal-title">
                            <i class="fas fa-eye me-2"></i>Podgląd danych i mapowania
                        </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">
                            <div class="spinner-border text-info" role="status">
                                <span class="visually-hidden">Ładowanie...</span>
                            </div>
                            <p class="mt-2">Analizowanie plików CSV...</p>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Zamknij</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Back Button -->
        <div class="text-center mt-4">
            <a href="/samanta_crm/dashboard" class="btn btn-secondary">
                <i class="fas fa-home me-2"></i>Powrót do Dashboard
            </a>
        </div>
    </div>
</div>

<script>
// Toggle between upload and server file selection
document.querySelectorAll('input[name="file_method"]').forEach(radio => {
    radio.addEventListener('change', function() {
        const uploadSection = document.getElementById('upload_section');
        const serverSection = document.getElementById('server_section');
        const ordersFile = document.getElementById('orders_file');
        const itemsFile = document.getElementById('items_file');
        const ordersFileServer = document.getElementById('orders_file_server');
        const itemsFileServer = document.getElementById('items_file_server');
        
        if (this.value === 'upload') {
            uploadSection.style.display = 'block';
            serverSection.style.display = 'none';
            ordersFile.required = true;
            itemsFile.required = true;
            ordersFileServer.required = false;
            itemsFileServer.required = false;
        } else {
            uploadSection.style.display = 'none';
            serverSection.style.display = 'block';
            ordersFile.required = false;
            itemsFile.required = false;
            ordersFileServer.required = true;
            itemsFileServer.required = true;
        }
    });
});

// Debug form submission
document.querySelector('form').addEventListener('submit', function(e) {
    const method = document.querySelector('input[name="file_method"]:checked').value;
    
    if (method === 'upload') {
        const ordersFile = document.getElementById('orders_file').files[0];
        const itemsFile = document.getElementById('items_file').files[0];
        
        console.log('Upload method - Orders file:', ordersFile ? ordersFile.name : 'NONE');
        console.log('Upload method - Items file:', itemsFile ? itemsFile.name : 'NONE');
        
        if (!ordersFile || !itemsFile) {
            e.preventDefault();
            alert('Proszę wybrać oba pliki CSV przed wysłaniem formularza!');
            return false;
        }
    } else {
        const ordersFile = document.getElementById('orders_file_server').value;
        const itemsFile = document.getElementById('items_file_server').value;
        
        console.log('Server method - Orders file:', ordersFile);
        console.log('Server method - Items file:', itemsFile);
        
        if (!ordersFile || !itemsFile) {
            e.preventDefault();
            alert('Proszę wybrać oba pliki CSV z serwera przed wysłaniem formularza!');
            return false;
        }
    }
    
    // Show loading state
    const btn = document.getElementById('submitBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Przetwarzanie...';
});

// File selection feedback
document.getElementById('orders_file').addEventListener('change', function(e) {
    if (this.files[0]) {
        console.log('Wybrano plik zamówień:', this.files[0].name, this.files[0].size, 'bytes');
    }
});

document.getElementById('items_file').addEventListener('change', function(e) {
    if (this.files[0]) {
        console.log('Wybrano plik produktów:', this.files[0].name, this.files[0].size, 'bytes');
    }
});

// Preview functionality
document.getElementById('previewBtn').addEventListener('click', async function() {
    const method = document.querySelector('input[name="file_method"]:checked').value;
    let ordersFile, itemsFile;
    
    if (method === 'upload') {
        ordersFile = document.getElementById('orders_file').files[0];
        itemsFile = document.getElementById('items_file').files[0];
        
        if (!ordersFile || !itemsFile) {
            alert('Proszę najpierw wybrać oba pliki CSV!');
            return;
        }
    } else {
        const ordersFilename = document.getElementById('orders_file_server').value;
        const itemsFilename = document.getElementById('items_file_server').value;
        
        if (!ordersFilename || !itemsFilename) {
            alert('Proszę najpierw wybrać oba pliki CSV z serwera!');
            return;
        }
    }
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('previewModal'));
    modal.show();
    
    // Send preview request
    const formData = new FormData();
    formData.append('file_method', method);
    
    if (method === 'upload') {
        formData.append('orders_file', ordersFile);
        formData.append('items_file', itemsFile);
    } else {
        formData.append('orders_file_server', document.getElementById('orders_file_server').value);
        formData.append('items_file_server', document.getElementById('items_file_server').value);
    }
    
    try {
        const response = await fetch('/samanta_crm/migration/preview-orders', {
            method: 'POST',
            body: formData
        });
        
        const html = await response.text();
        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 podczas ładowania podglądu: ${error.message}
            </div>
        `;
    }
});
</script>
