<?php if (isset($component)) { $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54 = $attributes; } ?>
<?php $component = App\View\Components\AppLayout::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('app-layout'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\App\View\Components\AppLayout::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes([]); ?>
     <?php $__env->slot('header', null, []); ?> 
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            <?php echo e(__('Product Details Extractor')); ?>

        </h2>
     <?php $__env->endSlot(); ?>

    <style>
        .spinner {
            border-top-color: #3498db;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        .form-container {
            transition: opacity 0.5s ease-out, transform 0.5s ease-out;
        }
        .form-container.approved {
            opacity: 0;
            transform: scale(0.95);
        }
    </style>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 text-gray-900">
                    
                    <header class="text-center mb-8">
                        <h1 class="text-3xl md:text-4xl font-bold text-gray-700">Product Details Extractor</h1>
                        <p class="text-gray-500 mt-2">Upload an image or PDF to automatically extract product information.</p>
                    </header>
            
                    <!-- Main Card content (simplified structure since we are inside a card now) -->
                    <div class="">
                        
                        <!-- Upload Form -->
                        <div id="upload-section">
                            <form id="upload-form" class="space-y-6">
                                <div class="flex items-center" style="margin-bottom: 1rem;">
                                    <label class="inline-flex items-center cursor-pointer">
                                        <input type="radio" class="form-radio text-indigo-600" name="extraction_method" value="document" checked>
                                        <span class="ml-2 text-gray-700">Upload Document</span>
                                    </label>
                                    <label class="inline-flex items-center cursor-pointer" style="margin-left: 2rem;">
                                        <input type="radio" class="form-radio text-indigo-600" name="extraction_method" value="link">
                                        <span class="ml-2 text-gray-700">Extract via Link</span>
                                    </label>
                                </div>

                                <div id="document-upload-container">
                                    <label for="document-upload" class="block text-sm font-medium text-gray-600 mb-2">Product Document</label>
                                    <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md">
                                        <div class="space-y-1 text-center">
                                            <svg class="mx-auto h-12 w-12 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48" aria-hidden="true">
                                                <path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                                            </svg>
                                            <div class="flex text-sm text-gray-600">
                                                <label for="document-upload" class="relative cursor-pointer bg-white rounded-md font-medium text-indigo-600 hover:text-indigo-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-indigo-500">
                                                    <span>Upload a file</span>
                                                    <input id="document-upload" name="document" type="file" class="sr-only" accept=".jpg,.jpeg,.png,.pdf">
                                                </label>
                                                <p class="pl-1">or drag and drop</p>
                                            </div>
                                            <p class="text-xs text-gray-500" id="file-name">PNG, JPG, PDF up to 10MB</p>
                                        </div>
                                    </div>
                                </div>

                                <div id="link-upload-container" class="hidden">
                                    <label for="product-link" class="block text-sm font-medium text-gray-600 mb-2">Product Link</label>
                                    <input type="url" name="product_link" id="product-link" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm" placeholder="https://example.com/product-page">
                                </div>
                                <button type="submit" class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-4 rounded-lg focus:outline-none focus:shadow-outline transition duration-300">
                                    Extract Product Details
                                </button>
                            </form>
                        </div>
            
                        <!-- Spinner/Loading State -->
                        <div id="loading-section" class="hidden text-center py-12">
                            <div class="spinner w-16 h-16 border-4 rounded-full mx-auto"></div>
                            <p class="mt-4 text-lg font-semibold text-gray-600">Analyzing Document...</p>
                            <p class="text-gray-500">Extracting details with AI. Please wait.</p>
                        </div>
            
                        <!-- Error Display -->
                        <div id="error-section" class="hidden bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg relative" role="alert">
                            <strong class="font-bold">Error:</strong>
                            <span class="block sm:inline" id="error-message"></span>
                        </div>
            
                        <!-- Results Section -->
                        <div id="results-section" class="space-y-6">
                            <!-- Product forms will be injected here -->
                        </div>
            
                    </div>
                </div>
            </div>
        </div>
    </div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const uploadForm = document.getElementById('upload-form');
        const uploadSection = document.getElementById('upload-section');
        const loadingSection = document.getElementById('loading-section');
        const errorSection = document.getElementById('error-section');
        const errorMessage = document.getElementById('error-message');
        const resultsSection = document.getElementById('results-section');
        const fileInput = document.getElementById('document-upload');
        const fileNameDisplay = document.getElementById('file-name');
        
        const methodRadios = document.querySelectorAll('input[name="extraction_method"]');
        const documentContainer = document.getElementById('document-upload-container');
        const linkContainer = document.getElementById('link-upload-container');

        methodRadios.forEach(radio => {
            radio.addEventListener('change', (e) => {
                if (e.target.value === 'document') {
                    documentContainer.classList.remove('hidden');
                    linkContainer.classList.add('hidden');
                } else {
                    documentContainer.classList.add('hidden');
                    linkContainer.classList.remove('hidden');
                }
            });
        });

        if (fileInput) {
            fileInput.addEventListener('change', () => {
                if (fileInput.files.length > 0) {
                    fileNameDisplay.textContent = fileInput.files[0].name;
                } else {
                    fileNameDisplay.textContent = 'PNG, JPG, PDF up to 10MB';
                }
            });
        }
        
        if (uploadForm) {
            uploadForm.addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const formData = new FormData(this);
                const method = formData.get('extraction_method');

                if (method === 'document' && (!formData.get('document') || formData.get('document').size === 0)) {
                    showError('Please select a file to upload.');
                    return;
                } else if (method === 'link' && !formData.get('product_link')) {
                    showError('Please enter a product link.');
                    return;
                }

                // UI transition
                uploadSection.classList.add('hidden');
                errorSection.classList.add('hidden');
                loadingSection.classList.remove('hidden');
                resultsSection.innerHTML = '';

                try {
                    const response = await fetch("<?php echo e(route('upload')); ?>", {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
                            'Accept': 'application/json',
                        },
                    });

                    if (!response.ok) {
                        let errorText = `HTTP error! Status: ${response.status}`;
                        try {
                            const errorJson = await response.json();
                            errorText = errorJson.error || errorJson.message || 'An unknown error occurred.';
                        } catch (jsonError) {
                             errorText = await response.text();
                             console.error("Non-JSON response from server:", errorText);
                             errorText = 'A server error occurred. Please check the console.';
                        }
                        throw new Error(errorText);
                    }

                    const products = await response.json();
                    loadingSection.classList.add('hidden');
                    displayProducts(products);

                } catch (error) {
                    console.error('Upload error:', error);
                    showError(error.message);
                    loadingSection.classList.add('hidden');
                    uploadSection.classList.remove('hidden');
                }
            });
        }

        function displayProducts(products) {
            resultsSection.innerHTML = '';
            if (products.length === 0) {
                resultsSection.innerHTML = '<p class="text-center text-gray-500">No products could be extracted from the document.</p>';
                return;
            }

            const categories = <?php echo json_encode($categories ?? [], 15, 512) ?>;
            const brands = <?php echo json_encode($brands ?? [], 15, 512) ?>;
            const attributes = <?php echo json_encode($attributes ?? [], 15, 512) ?>;

            products.forEach((product, index) => {
                const formId = `product-form-${index}`;
                
                // 1. Try to match Category
                let selectedCategoryId = '';
                if (product.category) {
                     const lowerCat = product.category.toLowerCase();
                     const match = categories.find(c => c.name.toLowerCase().includes(lowerCat) || lowerCat.includes(c.name.toLowerCase()));
                     if (match) selectedCategoryId = match.id;
                }

                // 2. Try to match Brand
                let selectedBrandId = '';
                if (product.brand) {
                     const lowerBrand = product.brand.toLowerCase();
                     const match = brands.find(b => b.name.toLowerCase().includes(lowerBrand) || lowerBrand.includes(b.name.toLowerCase()));
                     if (match) selectedBrandId = match.id;
                }

                const productHtml = `
                    <div id="form-container-${index}" class="form-container bg-gray-50 p-6 rounded-lg border border-gray-200">
                        <form id="${formId}" data-index="${index}">
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                                <div class="md:col-span-1">
                                    <label class="block text-sm font-medium text-gray-600 mb-2">Product Image</label>
                                    <img id="image-preview-${index}" src="${product.image_url}" alt="Product image for ${product.product_name}" class="w-full h-auto object-cover rounded-lg aspect-square bg-white border">
                                    <div class="mt-2">
                                        <label for="image-upload-${index}" class="text-sm text-green-600 hover:text-green-800 cursor-pointer">Change Image</label>
                                        <input type="file" id="image-upload-${index}" class="hidden image-upload-input" accept="image/*">
                                        <input type="hidden" name="image_data" class="resized-image-data">
                                        <input type="hidden" name="image_url" value="${product.image_url}">
                                    </div>
                                </div>
                                <div class="md:col-span-2 grid grid-cols-1 sm:grid-cols-2 gap-4">
                                    ${createInputField('Product Name', 'product_name', product.product_name, 'text', 'sm:col-span-2')}
                                    ${createSelectField('Brand', 'brand', brands, selectedBrandId)}
                                    ${createSelectField('Category', 'category', categories, selectedCategoryId)}
                                    ${createInputField('Normal Price', 'normal_price', product.normal_price, 'number', '', 'step="0.01"')}
                                    ${createInputField('Sale Price', 'sale_price', product.sale_price, 'number', '', 'step="0.01"')}
                                    ${createAttributeNameField('Attribute', 'attribute_name', attributes)}
                                    <div class="">
                                        <label class="block text-sm font-medium text-gray-700">Attribute Value</label>
                                        <select name="attribute_value" class="attribute-value-select mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm" disabled>
                                            <option value="">Select a Value</option>
                                        </select>
                                    </div>
                                    <div class="sm:col-span-2">
                                        <label class="block text-sm font-medium text-gray-700">Description</label>
                                        <textarea name="product_description" rows="4" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm">${product.product_description || ''}</textarea>
                                    </div>
                                    <div class="sm:col-span-2">
                                        <label class="block text-sm font-medium text-gray-700">Keywords</label>
                                        <textarea name="product_keywords" rows="4" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm">${product.product_keywords || ''}</textarea>
                                    </div>
                                </div>
                            </div>
                            <div class="mt-6 flex justify-end">
                                <button type="submit" class="approve-btn bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-6 rounded-lg transition duration-300">
                                    Approve
                                </button>
                            </div>
                        </form>
                    </div>
                `;
                resultsSection.insertAdjacentHTML('beforeend', productHtml);
            });
        }

        function createInputField(label, name, value, type = 'text', extraClasses = '', extraAttrs = '') {
            return `
                <div class="${extraClasses}">
                    <label class="block text-sm font-medium text-gray-700">${label}</label>
                    <input type="${type}" name="${name}" value="${value || ''}" ${extraAttrs} class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm">
                </div>
            `;
        }

        function createSelectField(label, name, options, selectedValue, extraClasses = '') {
            let optionsHtml = '<option value="">Select a Category</option>'; // Default text, might need adjustment for Brand
            if (label === 'Brand') optionsHtml = '<option value="">Select a Brand</option>';

            options.forEach(opt => {
                const isSelected = opt.id == selectedValue ? 'selected' : '';
                optionsHtml += `<option value="${opt.id}" ${isSelected}>${opt.name}</option>`;
            });

            return `
                <div class="${extraClasses}">
                    <label class="block text-sm font-medium text-gray-700">${label}</label>
                    <select name="${name}" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm">
                        ${optionsHtml}
                    </select>
                </div>
            `;
        }

        function createAttributeNameField(label, name, options, extraClasses = '') {
            let optionsHtml = '<option value="">Select an Attribute</option>';
            options.forEach(opt => {
                optionsHtml += `<option value="${opt.id}">${opt.name}</option>`;
            });

            return `
                <div class="${extraClasses}">
                    <label class="block text-sm font-medium text-gray-700">${label}</label>
                    <select name="${name}" class="attribute-name-select mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm">
                        ${optionsHtml}
                    </select>
                </div>
            `;
        }

        // Event delegation for approve buttons and image uploads
        document.body.addEventListener('submit', function(e) {
            if (e.target.matches('[id^="product-form-"]')) {
                e.preventDefault();
                approveProduct(e.target);
            }
        });

        document.body.addEventListener('change', async function(e) {
            if (e.target.matches('.image-upload-input')) {
                handleImageUpload(e.target);
            } else if (e.target.matches('.attribute-name-select')) {
                const attrId = e.target.value;
                const form = e.target.closest('form');
                const valueSelect = form.querySelector('.attribute-value-select');
                
                valueSelect.innerHTML = '<option value="">Select a Value</option>';
                valueSelect.disabled = true;
                
                if (attrId) {
                    try {
                        valueSelect.innerHTML = '<option value="">Loading...</option>';
                        const termsUrl = "<?php echo e(route('attributes.terms', ['id' => ':id'])); ?>".replace(':id', attrId);
                        const response = await fetch(termsUrl);
                        if (response.ok) {
                            const terms = await response.json();
                            valueSelect.innerHTML = '<option value="">Select a Value</option>';
                            terms.forEach(term => {
                                valueSelect.innerHTML += `<option value="${term.name}">${term.name}</option>`;
                            });
                            valueSelect.disabled = false;
                        } else {
                            valueSelect.innerHTML = '<option value="">Error loading terms</option>';
                        }
                    } catch (error) {
                        console.error("Failed to fetch attribute terms", error);
                        valueSelect.innerHTML = '<option value="">Error loading terms</option>';
                    }
                }
            }
        });

        function handleImageUpload(input) {
            const file = input.files[0];
            if (!file) return;

            const form = input.closest('form');
            const preview = form.querySelector('img');
            const hiddenInput = form.querySelector('.resized-image-data');
            
            const reader = new FileReader();
            reader.onload = function(e) {
                const img = new Image();
                img.onload = function() {
                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');
                    
                    canvas.width = 500;
                    canvas.height = 500;
                    
                    // Simple center crop logic
                    const sourceX = img.width > img.height ? (img.width - img.height) / 2 : 0;
                    const sourceY = img.height > img.width ? (img.height - img.width) / 2 : 0;
                    const sourceWidth = Math.min(img.width, img.height);
                    const sourceHeight = sourceWidth;

                    ctx.drawImage(img, sourceX, sourceY, sourceWidth, sourceHeight, 0, 0, 500, 500);
                    
                    const dataUrl = canvas.toDataURL('image/jpeg', 0.9); // 90% quality
                    preview.src = dataUrl;
                    hiddenInput.value = dataUrl;
                }
                img.src = e.target.result;
            }
            reader.readAsDataURL(file);
        }

        async function approveProduct(form) {
            const index = form.dataset.index;
            const container = document.getElementById(`form-container-${index}`);
            const approveBtn = form.querySelector('.approve-btn');
            approveBtn.disabled = true;
            approveBtn.textContent = 'Approving...';

            const formData = new FormData(form);
            
            try {
                const response = await fetch("<?php echo e(route('approve')); ?>", {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
                        //'Accept': 'application/json',
                    }
                });
                
                if (!response.ok) {
                    const errorJson = await response.json();
                    throw new Error(errorJson.error || 'Approval failed.');
                }
                
                const result = await response.json();
                
                // Animate out and replace with success message
                container.classList.add('approved');
                setTimeout(() => {
                    container.innerHTML = `
                        <div class="text-center p-8 bg-green-50 border-2 border-green-200 rounded-lg">
                            <h3 class="text-xl font-bold text-green-800">Success!</h3>
                            <p class="text-green-600 mt-2">${result.message || 'Product was approved successfully.'}</p>
                        </div>
                    `;
                    container.classList.remove('approved'); // Reset for fade-in effect
                }, 500);


            } catch (error) {
                console.error('Approval Error:', error);
                alert(`Error: ${error.message}`);
                approveBtn.disabled = false;
                approveBtn.textContent = 'Approve';
            }
        }
        
        function showError(message) {
            errorMessage.textContent = message;
            errorSection.classList.remove('hidden');
        }
    });
</script>
 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $attributes = $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $component = $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>

<?php /**PATH C:\xampp\htdocs\projects\nine\bd_product_master\bd_product_master\resources\views/welcome.blade.php ENDPATH**/ ?>