@extends('layouts.admin')

@section('title', 'Edit Product')


@section('content')
<div class="admin-page-header">
    <h1>Edit Product: {{ $product->name }}</h1>
    <a href="{{ route('admin.products.index') }}" class="admin-btn-primary">Back</a>
</div>

<div class="admin-card">
    <div class="card-body">
        <form action="{{ route('admin.products.update', $product->id) }}" method="POST" enctype="multipart/form-data">
            @csrf
            @method('PUT')

            <!-- Basic Information Section -->
            <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="{{ old('name', $product->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>
                        @foreach($categories as $category)
                            <option value="{{ $category->id }}" {{ $product->category_id == $category->id ? 'selected' : '' }}>
                                {{ $category->name }}
                            </option>
                        @endforeach
                    </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...">{{ old('tags', $product->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</label>
                    <input type="text"
                           name="barcode"
                           id="barcode"
                           class="admin-form-control form-control"
                           value="{{ old('barcode', $product->barcode ?? '') }}"
                           readonly
                           style="background-color: #f8f9fa; font-weight: 600; font-family: 'Courier New', monospace;">
                    <small class="form-text text-muted" style="font-size: 11px;">Cannot be changed after creation</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>
                        @foreach($brands as $brand)
                            <option value="{{ $brand->id }}" {{ old('brand_id', $product->brand_id) == $brand->id ? 'selected' : '' }}>
                                {{ $brand->name }}
                            </option>
                        @endforeach
                    </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 (₹)
                        @if(!$product->hasPurchasePrice())
                            <i class="bi bi-exclamation-triangle text-warning" title="Missing purchase price - affects profit calculations"></i>
                        @endif
                    </label>
                    <input type="number" step="0.01" name="purchase_price" class="admin-form-control form-control" value="{{ old('purchase_price', $product->purchase_price) }}" 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="{{ old('price', $product->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="{{ old('mrp', $product->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="{{ old('wholesale_price', $product->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">Current Profit</label>
                    <div class="admin-form-control form-control" style="background-color: #f8f9fa; display: flex; align-items: center; height: 32px;">
                        @if($product->hasPurchasePrice())
                            <span class="text-success" style="font-size: 13px;">
                                <strong>₹{{ $product->unit_profit ?? 0 }}</strong>
                                <small>({{ $product->profit_margin ?? 0 }}%)</small>
                            </span>
                        @else
                            <span class="text-warning" style="font-size: 13px;">
                                <i class="bi bi-exclamation-triangle"></i> Add purchase price
                            </span>
                        @endif
                    </div>
                    <small class="form-text text-muted" style="font-size: 11px;">Current profit per unit</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" class="admin-form-control form-control" value="{{ old('opening_stock', $product->opening_stock) }}" readonly style="background-color: #f8f9fa;">
                    <small class="form-text text-muted" style="font-size: 11px;">Cannot be changed after creation</small>
                </div>
                <div>
                    <label class="admin-form-label">Current Stock</label>
                    <input type="number" class="admin-form-control form-control" value="{{ $product->current_stock }}" readonly style="background-color: #f8f9fa;">
                    <small class="form-text text-muted" style="font-size: 11px;">Current available stock</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>
                        @foreach($units as $unit)
                            <option value="{{ $unit->id }}" {{ old('unit_id', $product->unit_id) == $unit->id ? 'selected' : '' }}>
                                {{ ucfirst($unit->name) }}
                            </option>
                        @endforeach
                    </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="{{ old('hsn_code', $product->hsn_code) }}" placeholder="Enter HSN Code" maxlength="50">
                    <small class="form-text text-muted" style="font-size: 11px;">For tax classification</small>
                </div>
            </div>
            <div class="admin-form-grid-4">
                <div>
                    <label class="admin-form-label">Tax</label>
                    <select name="tax_id" class="admin-form-control form-select">
                        <option value="">No Tax</option>
                        @foreach($taxes as $tax)
                            <option value="{{ $tax->id }}" {{ old('tax_id', $product->tax_id) == $tax->id ? 'selected' : '' }}>
                                {{ $tax->name }} ({{ number_format($tax->rate, 2) }}%)
                            </option>
                        @endforeach
                    </select>
                    <small class="form-text text-muted" style="font-size: 11px;">
                        Current snapshot: {{ $product->tax_rate_snapshot ? number_format($product->tax_rate_snapshot, 2) . '%' : 'N/A' }}
                    </small>
                </div>
                <div>
                    <label class="admin-form-label">Shipping Days</label>
                    <input type="number" name="shipping_days" class="admin-form-control form-control" value="{{ old('shipping_days', $product->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>
    </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>
            <input type="hidden" name="sync_product_media" value="1">
            <div id="delete-media-inputs"></div>
            <div class="admin-form-grid-2">
                <div>
                    <label class="admin-form-label">Product Image (Main)</label>
                    @if($product->image_path || $product->image)
                        <div class="mb-2">
                            <x-product-image :product="$product" context="detail" class="admin-image-preview img-thumbnail" style="max-width: 120px; max-height: 120px;" />
                        </div>
                    @endif
                    <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;">Leave empty to keep current image. Max 5MB. JPG, PNG, WebP.</small>
                </div>
                <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">
                        @php
                            $productImages = $product->media->where('type', 'image')->sortBy('display_order');
                        @endphp
                        @if($productImages && $productImages->count() > 0)
                            <div class="existing-images mb-2">
                                <small class="text-muted d-block mb-2">Existing Images:</small>
                                @foreach($productImages as $image)
                                    <div class="media-preview-item d-inline-block me-2 mb-2 position-relative" data-media-id="{{ $image->id }}">
                                        <img src="{{ storage_url($image->file_path, $image->updated_at ? (string) $image->updated_at->timestamp : null) }}" alt="Image" style="width: 80px; height: 80px; object-fit: cover; border-radius: 4px;" />
                                        <button type="button" class="btn btn-sm btn-danger remove-media" data-media-id="{{ $image->id }}" style="position: absolute; top: -5px; right: -5px; border-radius: 50%; width: 24px; height: 24px; padding: 0; font-size: 12px;">×</button>
                                        <input type="hidden" name="existing_images[]" value="{{ $image->id }}" />
                                    </div>
                                @endforeach
                            </div>
                        @endif
                    </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">
                        @php
                            $productVideos = $product->media->where('type', 'video')->sortBy('display_order');
                        @endphp
                        @if($productVideos && $productVideos->count() > 0)
                            <div class="existing-videos mb-2">
                                <small class="text-muted d-block mb-2">Existing Videos:</small>
                                @foreach($productVideos as $video)
                                    <div class="media-preview-item d-inline-block me-2 mb-2 position-relative" data-media-id="{{ $video->id }}">
                                        <video src="{{ asset('storage/' . $video->file_path) }}" style="width: 80px; height: 80px; object-fit: cover; border-radius: 4px;" controls></video>
                                        <button type="button" class="btn btn-sm btn-danger remove-media" data-media-id="{{ $video->id }}" style="position: absolute; top: -5px; right: -5px; border-radius: 50%; width: 24px; height: 24px; padding: 0; font-size: 12px;">×</button>
                                        <input type="hidden" name="existing_videos[]" value="{{ $video->id }}">
                                    </div>
                                @endforeach
                            </div>
                        @endif
                    </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">{{ old('short_desc', $product->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">{{ old('long_desc', $product->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" {{ old('is_active', $product->is_active) ? '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" {{ old('is_featured', $product->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" {{ old('is_verified', $product->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" {{ old('is_prebooking', $product->is_prebooking ?? false) ? '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" {{ old('channel_visibility', $product->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" {{ old('channel_visibility', $product->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" {{ old('channel_visibility', $product->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">Update Product</button>
            </div>
    </div>
            </div>
        </form>
  

@push('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>
@endpush

@push('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();
        }
    })();

    // 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>
@endpush

@push('scripts')
<script src="{{ asset('js/admin-product-media.js') }}"></script>
@endpush
@endsection
