<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Import Products - Octopus</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
</head>
<body class="bg-gray-50">
    <div class="min-h-screen py-12 px-4">
        <div class="max-w-2xl mx-auto">
            <div class="bg-white rounded-lg shadow-md p-8">
                <h1 class="text-3xl font-bold text-gray-900 mb-2">Import Products</h1>
                <p class="text-gray-600 mb-8">Upload an Excel file to import products into the system</p>

                @if(session('success'))
                    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-6">
                        {{ session('success') }}
                    </div>
                @endif

                @if(session('error'))
                    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">
                        {{ session('error') }}
                    </div>
                @endif

                @if($errors->any())
                    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">
                        <ul class="list-disc list-inside">
                            @foreach($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif

                <form id="importForm">
                    @csrf

                    <div class="mb-4">
                        <label for="category_id" class="block text-sm font-medium text-gray-700 mb-2">
                            Category <span class="text-red-600">*</span>
                        </label>
                        <select
                            name="category_id"
                            id="category_id"
                            required
                            class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm px-3 py-2 border"
                        >
                            <option value="">Select a category</option>
                            @foreach($categories as $category)
                                <option value="{{ $category->id }}">{{ $category->name_en }} ({{ $category->name_ar }})</option>
                            @endforeach
                        </select>
                    </div>

                    <div class="mb-4">
                        <label for="source" class="block text-sm font-medium text-gray-700 mb-2">
                            Source <span class="text-red-600">*</span>
                        </label>
                        <select
                            name="source"
                            id="source"
                            required
                            class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm px-3 py-2 border"
                        >
                            <option value="">Select a source</option>
                            <option value="aliexpress">AliExpress</option>
                            <option value="amazon">Amazon</option>
                            <option value="noon">Noon</option>
                        </select>
                    </div>

                    <div class="mb-6">
                        <label for="fileInput" class="block text-sm font-medium text-gray-700 mb-2">
                            Excel File (.xlsx, .xls, .csv) <span class="text-red-600">*</span>
                        </label>
                        <input
                            type="file"
                            name="file"
                            id="fileInput"
                            accept=".xlsx,.xls,.csv"
                            required
                            class="block w-full text-sm text-gray-500
                                file:mr-4 file:py-2 file:px-4
                                file:rounded-md file:border-0
                                file:text-sm file:font-semibold
                                file:bg-blue-50 file:text-blue-700
                                hover:file:bg-blue-100
                                cursor-pointer"
                        >
                        <p class="mt-2 text-sm text-gray-500">Maximum file size: 10MB</p>
                    </div>

                    <div id="previewInfo" class="hidden mb-4 p-4 bg-blue-50 rounded-md">
                        <p class="text-sm text-blue-700">
                            <strong>Preview:</strong> <span id="previewCount">0</span> products found in file
                        </p>
                    </div>

                    <div id="loadingIndicator" class="hidden mb-4">
                        <div class="flex items-center justify-center">
                            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                            <span class="ml-3 text-blue-600">Importing products...</span>
                        </div>
                        <div class="mt-2 text-sm text-gray-600">
                            <span id="importProgress">0</span> / <span id="importTotal">0</span> imported
                        </div>
                    </div>

                    <button
                        type="submit"
                        id="submitBtn"
                        class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-4 rounded-md transition duration-150 ease-in-out disabled:bg-gray-400 disabled:cursor-not-allowed"
                    >
                        Import Products
                    </button>
                </form>

                <div class="mt-8 pt-8 border-t border-gray-200">
                    <h2 class="text-lg font-semibold text-gray-900 mb-4">Excel File Format</h2>
                    <div class="bg-gray-50 rounded-md p-4">
                        <p class="text-sm text-gray-700 mb-3">Your Excel file should include the following columns (with headers):</p>
                        <div class="grid grid-cols-2 gap-2 text-xs text-gray-600">
                            <div>ProductId</div>
                            <div>Image Url</div>
                            <div>Video Url</div>
                            <div>Product Desc</div>
                            <div>Origin Price</div>
                            <div>Discount Price</div>
                            <div>Discount</div>
                            <div>Currency</div>
                            <div>Direct linking commission rate (%)</div>
                            <div>Estimated direct linking commission</div>
                            <div>Indirect linking commission rate (%)</div>
                            <div>Estimated indirect linking commission</div>
                            <div>Sales180Day</div>
                            <div>Positive Feedback</div>
                            <div>Promotion Url</div>
                            <div>Code Name</div>
                            <div>Code Start Time</div>
                            <div>Code End Time</div>
                            <div>Code Value</div>
                            <div>Code Quantity</div>
                            <div>Code Minimum Spend</div>
                        </div>
                    </div>
                </div>

                <div class="mt-6">
                    <a href="{{ url('/') }}" class="text-blue-600 hover:text-blue-800 text-sm font-medium">
                        ← Back to Home
                    </a>
                </div>
            </div>
        </div>
    </div>

    <script>
        let productsData = [];

        document.getElementById('fileInput').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (!file) return;

            const reader = new FileReader();
            reader.onload = function(evt) {
                const data = evt.target.result;
                const workbook = XLSX.read(data, {type: 'binary'});
                const firstSheet = workbook.SheetNames[0];
                productsData = XLSX.utils.sheet_to_json(workbook.Sheets[firstSheet]);

                // Debug: Log the first product to see what columns we're getting
                if (productsData.length > 0) {
                    console.log('First product data:', productsData[0]);
                    console.log('Available columns:', Object.keys(productsData[0]));
                }

                document.getElementById('previewCount').textContent = productsData.length;
                document.getElementById('previewInfo').classList.remove('hidden');
                document.getElementById('importTotal').textContent = productsData.length;
            };
            reader.readAsBinaryString(file);
        });

        document.getElementById('importForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const categoryId = document.getElementById('category_id').value;
            const source = document.getElementById('source').value;

            if (!categoryId || !source) {
                alert('Please select category and source');
                return;
            }

            if (productsData.length === 0) {
                alert('Please select an Excel file first');
                return;
            }

            // Show loading
            document.getElementById('loadingIndicator').classList.remove('hidden');
            document.getElementById('submitBtn').disabled = true;

            const batchSize = 50;
            let imported = 0;

            for (let i = 0; i < productsData.length; i += batchSize) {
                const batch = productsData.slice(i, i + batchSize);

                try {
                    const response = await fetch('{{ route('products.import.store') }}', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '{{ csrf_token() }}'
                        },
                        body: JSON.stringify({
                            category_id: categoryId,
                            source: source,
                            products: batch
                        })
                    });

                    if (!response.ok) {
                        const error = await response.json();
                        throw new Error(error.message || 'Import failed');
                    }

                    imported += batch.length;
                    document.getElementById('importProgress').textContent = imported;

                } catch (error) {
                    alert('Error importing batch: ' + error.message);
                    document.getElementById('loadingIndicator').classList.add('hidden');
                    document.getElementById('submitBtn').disabled = false;
                    return;
                }
            }

            // Success - redirect
            window.location.href = '{{ route('products.import') }}?success=' + encodeURIComponent('Successfully imported ' + imported + ' products!');
        });
    </script>
</body>
</html>
