<?php $__env->startSection('title', 'Edit Product'); ?>
<?php $__env->startSection('page-title', 'Edit Product'); ?>

<?php $__env->startSection('content'); ?>
<div class="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-lg p-6">
    <div class="mb-6 pb-4 border-b border-gray-200 dark:border-gray-800">
        <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-1">Edit Product</h3>
        <p class="text-sm text-gray-500 dark:text-gray-400">Update the product information below</p>
    </div>
    
    <form method="POST" action="<?php echo e(route('admin.products.update', $product)); ?>" enctype="multipart/form-data">
        <?php echo csrf_field(); ?>
        <?php echo method_field('PUT'); ?>

        <?php echo $__env->make('admin.products._form', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
    </form>
</div>

<script>
let selectedGalleryImages = [];

function previewFeaturedImage(input) {
    const file = input.files && input.files[0] ? input.files[0] : null;
    if (!file || !file.type.startsWith('image/')) {
        return;
    }

    const reader = new FileReader();
    reader.onload = function(e) {
        document.getElementById('featured_preview_img').src = e.target.result;
        document.getElementById('featured_preview').classList.remove('hidden');
    };
    reader.readAsDataURL(file);
}

function clearFeaturedPreview() {
    const input = document.getElementById('image_profile_upload');
    input.value = '';
    document.getElementById('featured_preview_img').src = '';
    document.getElementById('featured_preview').classList.add('hidden');
}

function previewGalleryImages(input) {
    const files = Array.from(input.files || []);
    const gallery = document.getElementById('gallery_new_preview');
    gallery.innerHTML = '';
    selectedGalleryImages = [];

    files.forEach((file, index) => {
        if (!file || !file.type.startsWith('image/')) {
            return;
        }

        const reader = new FileReader();
        reader.onload = function(e) {
            const imageDiv = document.createElement('div');
            imageDiv.className = 'relative group';
            imageDiv.innerHTML = `
                <div class="relative">
                    <img src="${e.target.result}" alt="New Preview ${index + 1}" class="w-full h-32 object-cover rounded-lg border-2 border-green-300 shadow-md">
                    <button type="button" onclick="removeNewGalleryImage(${index})"
                            class="absolute -top-2 -right-2 bg-red-500 text-white rounded-full w-7 h-7 flex items-center justify-center text-xs hover:bg-red-600 shadow-lg transition-colors">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            `;
            gallery.appendChild(imageDiv);
            selectedGalleryImages.push({ file: file });
        };
        reader.readAsDataURL(file);
    });
}

function removeNewGalleryImage(index) {
    const input = document.getElementById('image_gallery_upload');
    const dt = new DataTransfer();

    Array.from(input.files).forEach((file, i) => {
        if (i !== index) {
            dt.items.add(file);
        }
    });

    input.files = dt.files;
    previewGalleryImages(input);
}

function removeExistingImage(index) {
    const imageInput = document.getElementById('existing_image_' + index);
    if (imageInput) {
        imageInput.remove();
    }
    const container = document.getElementById('existing_image_container_' + index);
    if (container) {
        container.remove();
    }
}

// Category and Subcategory handling
document.addEventListener('DOMContentLoaded', function() {
    const mainCategorySelect = document.getElementById('main_category');
    const subcategorySelect = document.getElementById('subcategory');
    const finalCategoryInput = document.getElementById('final_category_id');
    
    // Store all categories data
    const categoriesData = {};
    <?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
        categoriesData[<?php echo e($category->id); ?>] = <?php echo json_encode($category->subcategories, 15, 512) ?>;
    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
    
    // Handle main category change
    mainCategorySelect.addEventListener('change', function() {
        const categoryId = this.value;
        const subcategories = categoriesData[categoryId] || [];
        
        // Clear and populate subcategory select
        subcategorySelect.innerHTML = '<option value="">Select Subcategory</option>';
        
        if (subcategories.length > 0) {
            subcategorySelect.disabled = false;
            subcategories.forEach(function(subcategory) {
                const option = document.createElement('option');
                option.value = subcategory.id;
                option.textContent = subcategory.name;
                subcategorySelect.appendChild(option);
            });
        } else {
            subcategorySelect.disabled = true;
            // If no subcategories, use main category
            finalCategoryInput.value = categoryId;
        }
        
        // Reset subcategory selection if main category changed
        if (subcategorySelect.value && !subcategories.find(s => s.id == subcategorySelect.value)) {
            subcategorySelect.value = '';
            finalCategoryInput.value = categoryId;
        }
    });
    
    // Handle subcategory change
    subcategorySelect.addEventListener('change', function() {
        if (this.value) {
            finalCategoryInput.value = this.value;
        } else {
            // If no subcategory selected, use main category
            finalCategoryInput.value = mainCategorySelect.value || '';
        }
    });
    
    // Initialize on page load
    const currentCategoryId = <?php echo e($product->category_id ?? 'null'); ?>;
    if (currentCategoryId) {
        // Find which category this belongs to
        let foundCategory = null;
        let isSubcategory = false;
        
        <?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            if (<?php echo e($category->id); ?> == currentCategoryId) {
                foundCategory = <?php echo e($category->id); ?>;
                isSubcategory = false;
            }
            <?php $__currentLoopData = $category->subcategories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $subcategory): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                if (<?php echo e($subcategory->id); ?> == currentCategoryId) {
                    foundCategory = <?php echo e($category->id); ?>;
                    isSubcategory = true;
                }
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        
        if (foundCategory) {
            mainCategorySelect.value = foundCategory;
            mainCategorySelect.dispatchEvent(new Event('change'));
            
            if (isSubcategory) {
                setTimeout(() => {
                    subcategorySelect.value = currentCategoryId;
                    finalCategoryInput.value = currentCategoryId;
                }, 100);
            } else {
                finalCategoryInput.value = currentCategoryId;
            }
        }
    }
});

function switchLanguageTab(lang) {
    const enBtn = document.getElementById('en-tab-btn');
    const kmBtn = document.getElementById('km-tab-btn');
    const enContent = document.getElementById('en-tab-content');
    const kmContent = document.getElementById('km-tab-content');
    
    if (lang === 'en') {
        enBtn.classList.add('text-blue-600', 'border-blue-600', 'dark:text-blue-500', 'dark:border-blue-500');
        enBtn.classList.remove('border-transparent');
        kmBtn.classList.remove('text-blue-600', 'border-blue-600', 'dark:text-blue-500', 'dark:border-blue-500');
        kmBtn.classList.add('border-transparent');
        enContent.classList.remove('hidden');
        kmContent.classList.add('hidden');
    } else {
        kmBtn.classList.add('text-blue-600', 'border-blue-600', 'dark:text-blue-500', 'dark:border-blue-500');
        kmBtn.classList.remove('border-transparent');
        enBtn.classList.remove('text-blue-600', 'border-blue-600', 'dark:text-blue-500', 'dark:border-blue-500');
        enBtn.classList.add('border-transparent');
        kmContent.classList.remove('hidden');
        enContent.classList.add('hidden');
    }
}
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('admin.layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /Users/mac/Documents/e-com/resources/views/admin/products/edit.blade.php ENDPATH**/ ?>