

<?php $__env->startSection('title', 'Create Product'); ?>

<?php $__env->startSection('styles'); ?>
<style>
#profit-margin {
    font-weight: 600;
    color: #28a745;
}
</style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script>
// Auto-calculate profit margin
function calculateProfitMargin() {
    const purchasePrice = parseFloat(document.querySelector('input[name="purchase_price"]').value) || 0;
    const sellingPrice = parseFloat(document.querySelector('input[name="price"]').value) || 0;
    const profitMarginField = document.getElementById('profit-margin');
    
    if (purchasePrice > 0 && sellingPrice > 0) {
        const profit = sellingPrice - purchasePrice;
        const margin = ((profit / sellingPrice) * 100).toFixed(2);
        profitMarginField.value = `₹${profit.toFixed(2)} (${margin}%)`;
        profitMarginField.style.color = profit > 0 ? '#28a745' : '#dc3545';
    } else {
        profitMarginField.value = 'Enter prices to calculate';
        profitMarginField.style.color = '#6c757d';
    }
}

// Add event listeners
document.addEventListener('DOMContentLoaded', function() {
    const purchasePriceInput = document.querySelector('input[name="purchase_price"]');
    const sellingPriceInput = document.querySelector('input[name="price"]');
    
    if (purchasePriceInput && sellingPriceInput) {
        purchasePriceInput.addEventListener('input', calculateProfitMargin);
        sellingPriceInput.addEventListener('input', calculateProfitMargin);
        
        // Calculate on page load if values exist
        calculateProfitMargin();
    }
});
</script>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
<div class="admin-page-header">
    <h1>Create Product</h1> 
    <a href="<?php echo e(route('admin.products.index')); ?>" class="admin-btn-primary">Back</a>
</div>


 <form action="<?php echo e(route('admin.products.store')); ?>" method="POST" enctype="multipart/form-data">
            <?php echo csrf_field(); ?>

            <!-- Basic Information Section -->
 <div class="admin-card">
    <div class="card-body">
            <div class="admin-section-header">
                <h5><i class="bi bi-info-circle"></i> Basic Information</h5>
            </div>
            <div class="admin-form-grid-2">
                <div>
                    <label class="admin-form-label">Product Name *</label>
                    <input type="text" name="name" class="admin-form-control form-control" value="<?php echo e(old('name')); ?>" required placeholder="Enter product name">
                </div>
                <div>
                    <label class="admin-form-label">Category *</label>
                    <select name="category_id" class="admin-form-control form-select" required>
                        <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); ?>"><?php echo e($category->name); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>
            </div>

            <div class="admin-form-grid-3">
                <div>
                    <label class="admin-form-label">Product Tags</label>
                    <div class="tags-input-container">
                        <textarea
                            name="tags"
                            id="productTagsTextarea"
                            class="admin-form-control form-control tags-textarea"
                            rows="1"
                            placeholder="Type keywords and press Enter or comma..."><?php echo e(old('tags')); ?></textarea>
                        <div class="tags-display" id="tagsDisplay"></div>
                    </div>
                    <small class="form-text text-muted" style="font-size: 11px;">
                        <i class="bi bi-info-circle"></i> Press <strong>Enter</strong> or <strong>comma</strong> to add tags.
                    </small>
                </div>
                <div>
                    <label class="admin-form-label">Barcode <small class="text-muted">(Auto-generated)</small></label>
                    <div class="input-group">
                        <input type="text"
                               name="barcode"
                               id="barcode"
                               class="admin-form-control form-control"
                               value="<?php echo e(old('barcode')); ?>"
                               maxlength="8"
                               placeholder="Enter Barcode"
                               style="font-weight: 600; font-family: 'Courier New', monospace;">
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="generateNewBarcode()" title="Generate New Barcode">
                            <i class="bi bi-arrow-clockwise"></i>
                        </button>
                    </div>
                    <small class="form-text text-muted" style="font-size: 11px;">Auto-generated 8-digit barcode</small>
                </div>
                <div>
                    <label class="admin-form-label">Brand</label>
                    <select name="brand_id" class="admin-form-control form-select">
                        <option value="">Select Brand</option>
                        <?php $__currentLoopData = $brands; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $brand): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <?php
                                $isSelected = false;
                                if (old('brand_id')) {
                                    $isSelected = old('brand_id') == $brand->id;
                                } else {
                                    $isSelected = $loop->first;
                                }
                            ?>
                            <option value="<?php echo e($brand->id); ?>" <?php echo e($isSelected ? 'selected' : ''); ?>>
                                <?php echo e($brand->name); ?>

                            </option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>
            </div>

    </div>
  </div>

            <!-- Pricing Section -->
             <div class="admin-card mt-3">
    <div class="card-body">
            <div class="admin-section-header" style="margin-top: 1rem;">
                <h5><i class="bi bi-currency-rupee"></i> Pricing & Cost</h5>
            </div>
            <div class="admin-form-grid-4">
                <div>
                    <label class="admin-form-label">Purchase Price (₹) *</label>
                    <input type="number" step="0.01" name="purchase_price" class="admin-form-control form-control" value="<?php echo e(old('purchase_price')); ?>" required placeholder="Cost price">
                    <small class="form-text text-muted" style="font-size: 11px;">Your cost price</small>
                </div>
                <div>
                    <label class="admin-form-label">Selling Price (₹) *</label>
                    <input type="number" step="0.01" name="price" class="admin-form-control form-control" value="<?php echo e(old('price')); ?>" required placeholder="Selling price">
                    <small class="form-text text-muted" style="font-size: 11px;">Customer price</small>
                </div>
                <div>
                    <label class="admin-form-label">MRP (₹)</label>
                    <input type="number" step="0.01" name="mrp" class="admin-form-control form-control" value="<?php echo e(old('mrp')); ?>" placeholder="Maximum retail price">
                    <small class="form-text text-muted" style="font-size: 11px;">Optional maximum price</small>
                </div>
                <div>
                    <label class="admin-form-label">Wholesale Price (₹)</label>
                    <input type="number" step="0.01" name="wholesale_price" class="admin-form-control form-control" value="<?php echo e(old('wholesale_price')); ?>" placeholder="Wholesale price">
                    <small class="form-text text-muted" style="font-size: 11px;">Optional wholesale price</small>
                </div>
            </div>
            <div class="admin-form-grid-2" style="max-width: 50%;">
                <div>
                    <label class="admin-form-label">Profit Margin</label>
                    <input type="text" class="admin-form-control form-control" readonly style="background-color: #f8f9fa;" placeholder="Auto-calculated" id="profit-margin">
                    <small class="form-text text-muted" style="font-size: 11px;">Auto-calculated from prices</small>
                </div>
            </div>
    

            <!-- Inventory & Classification -->
            <div class="admin-section-header" style="margin-top: 1rem;">
                <h5><i class="bi bi-box"></i> Inventory & Classification</h5>
            </div>
            <div class="admin-form-grid-4">
                <div>
                    <label class="admin-form-label">Opening Stock *</label>
                    <input type="number" name="opening_stock" class="admin-form-control form-control" value="<?php echo e(old('opening_stock', 0)); ?>" required min="0" placeholder="Initial quantity">
                    <small class="form-text text-muted" style="font-size: 11px;">Initial stock quantity</small>
                </div>
                <div>
                    <label class="admin-form-label">Unit</label>
                    <select name="unit_id" class="admin-form-control form-select">
                        <option value="">Select Unit</option>
                        <?php $__currentLoopData = $units; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $unit): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($unit->id); ?>" <?php echo e(old('unit_id') == $unit->id ? 'selected' : ''); ?>>
                                <?php echo e(ucfirst($unit->name)); ?>

                            </option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                    <small class="form-text text-muted" style="font-size: 11px;">Measurement unit</small>
                </div>
                <div>
                    <label class="admin-form-label">HSN Code</label>
                    <input type="text" name="hsn_code" class="admin-form-control form-control" value="<?php echo e(old('hsn_code')); ?>" placeholder="Enter HSN Code" maxlength="50">
                    <small class="form-text text-muted" style="font-size: 11px;">For tax classification</small>
                </div>
                <div>
                    <label class="admin-form-label">Shipping Days</label>
                    <input type="number" name="shipping_days" class="admin-form-control form-control" value="<?php echo e(old('shipping_days', \App\Models\Setting::get('default_shipping_days'))); ?>" min="0" placeholder="e.g. 3">
                    <small class="form-text text-muted" style="font-size: 11px;">Estimated dispatch or delivery days</small>
                </div>
                <div>
                    <label class="admin-form-label">Tax</label>
                    <select name="tax_id" class="admin-form-control form-select">
                        <option value="">No Tax</option>
                         <?php $__currentLoopData = $taxes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $tax): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <?php
                                $isSelected = false;
                                if (old('tax_id')) {
                                    $isSelected = old('tax_id') == $tax->id;
                                } else {
                                    $isSelected = $loop->first;
                                }
                            ?>
                            <option value="<?php echo e($tax->id); ?>" <?php echo e($isSelected ? 'selected' : ''); ?>>
                                <?php echo e($tax->name); ?> (<?php echo e(number_format($tax->rate, 2)); ?>%)
                            </option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                    <small class="form-text text-muted" style="font-size: 11px;">Applicable tax rate</small>
                </div>
            </div>
    </div>
             </div>
           
    

            

            <!-- Additional Media Section -->
 <div class="admin-card mt-3">
    <div class="card-body">
            <div class="admin-section-header" style="margin-top: 1rem;">
                <h5><i class="bi bi-images"></i>Media</h5>
            </div>
             <div class="admin-form-grid-4">
                <div>
                    <label class="admin-form-label">Product Image (Main)</label>
                    <input type="file" name="image" id="product-image-input" class="admin-form-control form-control" accept="image/jpeg,image/png,image/jpg,image/webp">
                    <small class="form-text text-muted" style="font-size: 11px;">Main product image. Max 5MB. JPG, PNG, WebP.</small>
                </div>
            </div>
            <div class="admin-form-grid-2">
                <div>
                    <label class="admin-form-label">Additional Images (Max 5)</label>
                    <input type="file" name="additional_images[]" id="additional_images" class="admin-form-control form-control" accept="image/jpeg,image/png,image/jpg,image/gif,image/webp" multiple>
                    <small class="form-text text-muted" style="font-size: 11px;">Upload up to 5 additional images (Max 2MB each)</small>
                    <div id="image-preview-container" class="mt-2"></div>
                </div>
                <div>
                    <label class="admin-form-label">Videos (Max 2)</label>
                    <input type="file" name="videos[]" id="videos" class="admin-form-control form-control" accept="video/mp4,video/webm,video/quicktime,video/x-msvideo" multiple>
                    <small class="form-text text-muted" style="font-size: 11px;">Upload up to 2 videos (Max 50MB each)</small>
                    <div id="video-preview-container" class="mt-2"></div>
                </div>
            </div>

            <div class="admin-form-row-compact" style="margin-top: 1rem;">
                <label class="admin-form-label">Short Description</label>
                <textarea name="short_desc" class="admin-form-control form-control" rows="2"><?php echo e(old('short_desc')); ?></textarea>
            </div>

            <div class="admin-form-row-compact">
                <label class="admin-form-label">Long Description</label>
                <textarea name="long_desc" class="admin-form-control form-control" rows="4"><?php echo e(old('long_desc')); ?></textarea>
            </div>

            <div class="admin-form-grid-3" style="margin-top: 1rem;">
                <div>
                    <div class="form-check">
                        <input type="hidden" name="is_active" value="0">
                        <input type="checkbox" name="is_active" class="form-check-input" id="isActive" value="1" <?php echo e(old('is_active', true) ? 'checked' : ''); ?>>
                        <label class="form-check-label" for="isActive" style="font-size: 13px;">Active</label>
                    </div>
                </div>
                <div>
                    <div class="form-check">
                        <input type="hidden" name="is_featured" value="0">
                        <input type="checkbox" name="is_featured" class="form-check-input" id="isFeatured" value="1" <?php echo e(old('is_featured') ? 'checked' : ''); ?>>
                        <label class="form-check-label" for="isFeatured" style="font-size: 13px;">Featured</label>
                    </div>
                </div>
                <div>
                    <div class="form-check">
                        <input type="hidden" name="is_verified" value="0">
                        <input type="checkbox" name="is_verified" class="form-check-input" id="isVerified" value="1" <?php echo e(old('is_verified') ? 'checked' : ''); ?>>
                        <label class="form-check-label" for="isVerified" style="font-size: 13px;">Verified</label>
                    </div>
                </div>
                <div>
                    <div class="form-check">
                        <input type="checkbox" name="is_prebooking" class="form-check-input" id="isPrebooking" value="1" <?php echo e(old('is_prebooking') ? 'checked' : ''); ?>>
                        <label class="form-check-label" for="isPrebooking" style="font-size: 13px;">Pre Booking</label>
                    </div>
                </div>
            </div>

            <div class="admin-form-row-compact" style="margin-top: 0.75rem;">
                <label class="admin-form-label">Show Product In *</label>
                <div class="d-flex flex-wrap gap-3">
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="channel_visibility" id="channelBoth" value="both" <?php echo e(old('channel_visibility', 'both') === 'both' ? 'checked' : ''); ?>>
                        <label class="form-check-label" for="channelBoth">Both POS and Website</label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="channel_visibility" id="channelWebsiteOnly" value="website_only" <?php echo e(old('channel_visibility') === 'website_only' ? 'checked' : ''); ?>>
                        <label class="form-check-label" for="channelWebsiteOnly">Only Website</label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="channel_visibility" id="channelPosOnly" value="pos_only" <?php echo e(old('channel_visibility') === 'pos_only' ? 'checked' : ''); ?>>
                        <label class="form-check-label" for="channelPosOnly">Only POS</label>
                    </div>
                </div>
            </div>

            <div style="margin-top: 1rem;">
                <button type="submit" class="admin-btn-primary">Create Product</button>
            </div>
    </div>
              </div>
               </div>
        </div>
        </form>
       

       
   
<?php $__env->startPush('styles'); ?>
<style>
    /* Tags Input System */
    .tags-input-container {
        position: relative;
        margin-bottom: 0.5rem;
    }

    .tags-textarea {
        resize: vertical;
        min-height: 32px;
        height: 32px;
        padding: 0.375rem 0.75rem;
        border: 1px solid var(--admin-border-color);
        border-radius: 6px;
        transition: var(--admin-transition);
        font-size: 13px;
        line-height: 1.5;
    }

    .tags-textarea:focus {
        border-color: var(--admin-primary);
        box-shadow: 0 0 0 0.25rem rgba(15, 49, 58, 0.25);
        outline: none;
    }

    .tags-display {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
        margin-top: 0.75rem;
        /* min-height: 32px; */
    }
    .admin-main .btn-sm {
        height: 32px;
    }

    .tag-item {
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        background-color: #e9ecef;
        color: #495057;
        padding: 0.4rem 0.75rem;
        border-radius: 20px;
        font-size: 0.875rem;
        font-weight: 500;
        transition: all 0.2s ease;
        animation: tagSlideIn 0.3s ease;
    }

    @keyframes tagSlideIn {
        from {
            opacity: 0;
            transform: translateY(-10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .tag-item:hover {
        background-color: #dee2e6;
        transform: translateY(-1px);
    }

    .tag-text {
        user-select: none;
    }

    .tag-remove {
        background: none;
        border: none;
        color: #6c757d;
        cursor: pointer;
        padding: 0;
        width: 18px;
        height: 18px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        transition: all 0.2s ease;
        font-size: 0.875rem;
        line-height: 1;
        font-weight: 600;
    }

    .tag-remove:hover {
        background-color: #dc3545;
        color: #ffffff;
        transform: scale(1.1);
    }

    .tag-remove:focus {
        outline: none;
        box-shadow: 0 0 0 2px rgba(220, 53, 69, 0.25);
    }

    .tags-empty-message {
        color: #adb5bd;
        font-size: 0.875rem;
        font-style: italic;
        padding: 0.5rem 0;
    }

</style>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
    // Product Tags Management System
    (function() {
        const textarea = document.getElementById('productTagsTextarea');
        const tagsDisplay = document.getElementById('tagsDisplay');
        let tags = [];

        // Initialize tags from textarea value (for edit mode)
        function initTags() {
            const value = textarea.value.trim();
            if (value) {
                tags = value.split(',').map(tag => tag.trim()).filter(tag => tag.length > 0);
                renderTags();
            }
        }

        // Render tags below textarea
        function renderTags() {
            tagsDisplay.innerHTML = '';
            
            if (tags.length === 0) {
                return;
            }

            tags.forEach((tag, index) => {
                const tagElement = document.createElement('div');
                tagElement.className = 'tag-item';
                tagElement.innerHTML = `
                    <span class="tag-text">${escapeHtml(tag)}</span>
                    <button type="button" class="tag-remove" data-index="${index}" title="Remove tag">
                        <i class="bi bi-x"></i>
                    </button>
                `;
                tagsDisplay.appendChild(tagElement);
            });

            // Add remove event listeners
            tagsDisplay.querySelectorAll('.tag-remove').forEach(btn => {
                btn.addEventListener('click', function() {
                    const index = parseInt(this.getAttribute('data-index'));
                    removeTag(index);
                });
            });

            updateTextareaValue();
        }

        // Remove tag by index
        function removeTag(index) {
            tags.splice(index, 1);
            renderTags();
        }

        // Add tag
        function addTag(tag) {
            const trimmedTag = tag.trim();
            if (trimmedTag && !tags.includes(trimmedTag)) {
                tags.push(trimmedTag);
                renderTags();
                return true;
            }
            return false;
        }

        // Update textarea value with comma-separated tags
        function updateTextareaValue() {
            textarea.value = tags.join(', ');
        }

        // Escape HTML to prevent XSS
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // Handle textarea input
        textarea.addEventListener('keydown', function(e) {
            const value = textarea.value.trim();

            // Enter key or comma
            if (e.key === 'Enter' || e.key === ',') {
                e.preventDefault();
                
                // Get current cursor position
                const cursorPos = textarea.selectionStart;
                const textBeforeCursor = textarea.value.substring(0, cursorPos);
                const textAfterCursor = textarea.value.substring(cursorPos);
                
                // Find the last comma or newline before cursor
                const lastSeparator = Math.max(
                    textBeforeCursor.lastIndexOf(','),
                    textBeforeCursor.lastIndexOf('\n')
                );
                
                // Extract the tag
                const tagText = textBeforeCursor.substring(lastSeparator + 1).trim();
                
                if (tagText) {
                    if (addTag(tagText)) {
                        // Clear textarea and insert remaining text
                        textarea.value = textAfterCursor.trim();
                        textarea.setSelectionRange(0, 0);
                    }
                }
            }
        });

        // Handle paste events
        textarea.addEventListener('paste', function(e) {
            setTimeout(() => {
                const value = textarea.value;
                const lines = value.split(/[,\n]/);
                let added = false;
                
                lines.forEach(line => {
                    const trimmed = line.trim();
                    if (trimmed) {
                        if (addTag(trimmed)) {
                            added = true;
                        }
                    }
                });
                
                if (added) {
                    textarea.value = '';
                    textarea.setSelectionRange(0, 0);
                }
            }, 10);
        });

        // Handle blur - add any remaining text as tag
        textarea.addEventListener('blur', function() {
            const value = textarea.value.trim();
            if (value) {
                const parts = value.split(',');
                parts.forEach(part => {
                    const trimmed = part.trim();
                    if (trimmed) {
                        addTag(trimmed);
                    }
                });
                textarea.value = '';
            }
        });

        // Sync tags to textarea before form submit so tags are always sent
        const form = textarea.closest('form');
        if (form) {
            form.addEventListener('submit', function() {
                updateTextareaValue();
            });
        }

        // Initialize on page load
        document.addEventListener('DOMContentLoaded', function() {
            initTags();
        });

        // Also initialize immediately (in case DOMContentLoaded already fired)
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initTags);
        } else {
            initTags();
        }
    })();

    // Barcode functions
    function generateNewBarcode() {
        // Generate random 8-digit number
        const randomBarcode = Math.floor(Math.random() * 90000000 + 10000000).toString();
        document.getElementById('barcode').value = randomBarcode;
    }

    // Client-side product image validation: max 5MB, JPG/PNG/WebP
    (function() {
        const el = document.getElementById('product-image-input');
        if (!el) return;
        const maxBytes = 5 * 1024 * 1024;
        const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
        el.addEventListener('change', function() {
            const file = this.files[0];
            if (!file) return;
            if (file.size > maxBytes) {
                alert('Image must be 5MB or less.');
                this.value = '';
            } else if (!allowedTypes.includes(file.type)) {
                alert('Allowed types: JPG, PNG, WebP.');
                this.value = '';
            }
        });
    })();
</script>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('scripts'); ?>
<script src="<?php echo e(asset('js/admin-product-media.js')); ?>"></script>
<?php $__env->stopPush(); ?>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.admin', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /var/www/html/shaa_jewels/live/resources/views/admin/products/create.blade.php ENDPATH**/ ?>