<?php $__env->startSection('title', 'Create Product'); ?>
<?php $__env->startSection('page-title', 'Create 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"><?php echo e(isset($duplicateProduct) ? 'Duplicate Product' : 'Create New Product'); ?></h3>
        <p class="text-sm text-gray-500 dark:text-gray-400"><?php echo e(isset($duplicateProduct) ? 'This form is pre-filled from an existing product' : 'Fill in the details below to create a new product'); ?></p>
    </div>
    
    <form method="POST" action="<?php echo e(route('admin.products.store')); ?>" enctype="multipart/form-data">
        <?php echo csrf_field(); ?>

        <div class="space-y-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Product Name <span class="text-red-500">*</span>
                    </label>
                    <input type="text" name="name" value="<?php echo e(old('name', $duplicateProduct->name ?? '')); ?>" required
                           placeholder="Enter product name"
                           class="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-lg text-sm text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 focus:border-transparent">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Product Name (Khmer)</label>
                    <input type="text" name="name_km" value="<?php echo e(old('name_km', $duplicateProduct->name_km ?? '')); ?>"
                           placeholder="Enter product name in Khmer"
                           class="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-lg text-sm text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 focus:border-transparent">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Price <span class="text-red-500">*</span>
                    </label>
                    <div class="relative">
                        <span class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500 dark:text-gray-400 text-sm">$</span>
                        <input type="number" step="0.01" name="price" value="<?php echo e(old('price', $duplicateProduct->price ?? '')); ?>" required
                               placeholder="0.00"
                               class="w-full pl-8 pr-3 py-2 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-lg text-sm text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 focus:border-transparent">
                    </div>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Original Price</label>
                    <div class="relative">
                        <span class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500 dark:text-gray-400 text-sm">$</span>
                        <input type="number" step="0.01" name="original_price" value="<?php echo e(old('original_price', $duplicateProduct->original_price ?? '')); ?>"
                               placeholder="0.00"
                               class="w-full pl-8 pr-3 py-2 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-lg text-sm text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 focus:border-transparent">
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Category</label>
                        <select id="main_category" name="main_category_id" class="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-lg text-sm text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 focus:border-transparent">
                            <option value="">Select Category</option>
                            <?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($category->id); ?>" 
                                        data-subcategories='<?php echo json_encode($category->subcategories, 15, 512) ?>'
                                        <?php echo e(old('main_category_id') == $category->id || (isset($duplicateProduct) && (($duplicateProduct->categoryRelation && $duplicateProduct->categoryRelation->parent_id === null && $duplicateProduct->categoryRelation->id == $category->id) || ($duplicateProduct->categoryRelation && $duplicateProduct->categoryRelation->parent_id == $category->id))) ? 'selected' : ''); ?>>
                                    <?php echo e($category->name); ?>

                                </option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Subcategory <span class="text-gray-400 dark:text-gray-600 text-xs">(Optional)</span></label>
                        <select id="subcategory" class="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-lg text-sm text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 focus:border-transparent" disabled>
                            <option value="">Select Subcategory</option>
                        </select>
                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                            Select a category first to see subcategories
                        </p>
                    </div>
                </div>
                <input type="hidden" id="final_category_id" name="category_id" value="<?php echo e(old('category_id', $duplicateProduct->category_id ?? '')); ?>">

                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Category Code (Legacy)</label>
                    <input type="text" name="category" value="<?php echo e(old('category', $duplicateProduct->category ?? '')); ?>"
                           placeholder="e.g., pillows, bedding"
                           class="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-lg text-sm text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 focus:border-transparent">
                </div>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Description</label>
                <textarea name="description" rows="4" placeholder="Enter product description..."
                          class="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-lg text-sm text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 focus:border-transparent resize-none"><?php echo e(old('description', $duplicateProduct->description ?? '')); ?></textarea>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Description (Khmer)</label>
                <textarea name="description_km" rows="4" placeholder="Enter product description in Khmer..."
                          class="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-lg text-sm text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 focus:border-transparent resize-none"><?php echo e(old('description_km', $duplicateProduct->description_km ?? '')); ?></textarea>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Short Description</label>
                    <input type="text" name="short_description" value="<?php echo e(old('short_description', $duplicateProduct->short_description ?? '')); ?>"
                           placeholder="Brief product description"
                           class="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-lg text-sm text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 focus:border-transparent">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Short Description (Khmer)</label>
                    <input type="text" name="short_description_km" value="<?php echo e(old('short_description_km', $duplicateProduct->short_description_km ?? '')); ?>"
                           placeholder="Brief description in Khmer"
                           class="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-lg text-sm text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 focus:border-transparent">
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-gray-50 dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800">
                <label class="flex items-center cursor-pointer">
                    <input type="checkbox" name="in_stock" value="1" <?php echo e(old('in_stock', $duplicateProduct->in_stock ?? true) ? 'checked' : ''); ?> 
                           class="w-4 h-4 text-blue-600 bg-white dark:bg-gray-800 border-gray-300 dark:border-gray-700 rounded focus:ring-blue-500 dark:focus:ring-blue-400">
                    <span class="ml-3 text-sm font-medium text-gray-700 dark:text-gray-300">
                        In Stock
                    </span>
                </label>
                <label class="flex items-center cursor-pointer">
                    <input type="checkbox" name="on_sale" value="1" <?php echo e(old('on_sale', $duplicateProduct->on_sale ?? false) ? 'checked' : ''); ?> 
                           class="w-4 h-4 text-blue-600 bg-white dark:bg-gray-800 border-gray-300 dark:border-gray-700 rounded focus:ring-blue-500 dark:focus:ring-blue-400">
                    <span class="ml-3 text-sm font-medium text-gray-700 dark:text-gray-300">
                        On Sale
                    </span>
                </label>
            </div>
            <?php
                $prefillImages = old('images', isset($duplicateProduct) ? ($duplicateProduct->images ?? []) : []);
                $prefillFeatured = is_array($prefillImages) && count($prefillImages) > 0 ? $prefillImages[0] : null;
                $prefillGallery = is_array($prefillImages) && count($prefillImages) > 1 ? array_slice($prefillImages, 1) : [];
            ?>

            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Product Images</label>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="p-6 bg-gray-50 dark:bg-gray-900 rounded-lg border-2 border-dashed border-gray-300 dark:border-gray-800 hover:border-blue-400 dark:hover:border-blue-600 transition-colors">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Featured Image</label>
                        <input type="file" name="image_profile_upload" id="image_profile_upload" accept="image/*"
                               class="block w-full text-sm text-gray-500 dark:text-gray-400 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-gray-900 dark:file:bg-white file:text-white dark:file:text-gray-900 hover:file:bg-gray-800 dark:hover:file:bg-gray-100 cursor-pointer"
                               onchange="previewFeaturedImage(this)">
                        <div class="mt-4">
                            <div id="featured_existing_container">
                                <?php if($prefillFeatured): ?>
                                    <div class="relative group" id="existing_image_container_0">
                                        <img src="<?php echo e($prefillFeatured); ?>" alt="Featured" class="w-full h-40 object-cover rounded-lg border border-gray-200 dark:border-gray-800">
                                        <button type="button" onclick="removeExistingImage(0)"
                                                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>
                                        <input type="hidden" name="images[]" value="<?php echo e($prefillFeatured); ?>" id="existing_image_0">
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div id="featured_preview" class="mt-4 hidden">
                                <div class="relative group">
                                    <img id="featured_preview_img" src="" alt="Featured Preview" class="w-full h-40 object-cover rounded-lg border border-green-300">
                                    <button type="button" onclick="clearFeaturedPreview()"
                                            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>
                            </div>
                        </div>
                    </div>

                    <div class="p-6 bg-gray-50 dark:bg-gray-900 rounded-lg border-2 border-dashed border-gray-300 dark:border-gray-800 hover:border-blue-400 dark:hover:border-blue-600 transition-colors">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Gallery Images</label>
                        <input type="file" name="image_gallery_upload[]" id="image_gallery_upload" accept="image/*" multiple
                               class="block w-full text-sm text-gray-500 dark:text-gray-400 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-gray-900 dark:file:bg-white file:text-white dark:file:text-gray-900 hover:file:bg-gray-800 dark:hover:file:bg-gray-100 cursor-pointer"
                               onchange="previewGalleryImages(this)">
                        <div id="gallery_existing_preview" class="grid grid-cols-2 md:grid-cols-4 gap-4 mt-4">
                            <?php $__currentLoopData = $prefillGallery; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $image): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <?php $realIndex = $index + 1; ?>
                                <div class="relative group" id="existing_image_container_<?php echo e($realIndex); ?>">
                                    <img src="<?php echo e($image); ?>" alt="Gallery <?php echo e($realIndex); ?>" class="w-full h-32 object-cover rounded-lg border border-gray-200 dark:border-gray-800">
                                    <button type="button" onclick="removeExistingImage(<?php echo e($realIndex); ?>)"
                                            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>
                                    <input type="hidden" name="images[]" value="<?php echo e($image); ?>" id="existing_image_<?php echo e($realIndex); ?>">
                                </div>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </div>
                        <div id="gallery_new_preview" class="grid grid-cols-2 md:grid-cols-4 gap-4 mt-4"></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="mt-8 flex flex-col sm:flex-row items-stretch sm:items-center justify-end gap-3 pt-6 border-t border-gray-200 dark:border-gray-800">
            <a href="<?php echo e(route('admin.products.index')); ?>" 
               class="px-4 md:px-6 py-2.5 md:py-3 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300 font-semibold rounded-lg transition-colors text-center">
                <i class="fas fa-times mr-2"></i>Cancel
            </a>
            <button type="submit" 
                    class="btn-primary text-white font-semibold py-2.5 md:py-3 px-6 md:px-8 rounded-lg shadow-lg hover:shadow-xl transition-all duration-200">
                <i class="fas fa-save mr-2"></i><?php echo e(isset($duplicateProduct) ? 'Create Duplicate' : 'Create Product'); ?>

            </button>
        </div>
    </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 border-green-300">
                    <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
        subcategorySelect.value = '';
    });
    
    // 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
    <?php
        $prefillCategoryId = old('category_id', $duplicateProduct->category_id ?? null);
    ?>
    <?php if($prefillCategoryId): ?>
        const oldCategoryId = <?php echo e($prefillCategoryId); ?>;
        // Find which category this belongs to
        let foundCategory = null;
        <?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            if (<?php echo e($category->id); ?> == oldCategoryId) {
                foundCategory = <?php echo e($category->id); ?>;
            }
            <?php $__currentLoopData = $category->subcategories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $subcategory): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                if (<?php echo e($subcategory->id); ?> == oldCategoryId) {
                    foundCategory = <?php echo e($category->id); ?>;
                }
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        
        if (foundCategory) {
            mainCategorySelect.value = foundCategory;
            mainCategorySelect.dispatchEvent(new Event('change'));
            setTimeout(() => {
                subcategorySelect.value = oldCategoryId;
                finalCategoryInput.value = oldCategoryId;
            }, 100);
        }
    <?php endif; ?>
});
</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/360monicaAPI/resources/views/admin/products/create.blade.php ENDPATH**/ ?>