@extends('layouts.admin')

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title">Add New Product</h4>
                </div>
                <div class="card-body">
                    <form action="{{ route('admin.products.store') }}" method="POST" enctype="multipart/form-data">
                        @csrf
                        <div class="row">
                            <div class="col-md-8">
                                <div class="mb-3">
                                    <label for="name" class="form-label">Product Name</label>
                                    <input type="text" class="form-control @error('name') is-invalid @enderror" 
                                           id="name" name="name" value="{{ old('name') }}">
                                    @error('name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="mb-3">
                                    <label for="sku" class="form-label">SKU (Auto-generated)</label>
                                    <input type="text" class="form-control" 
                                           id="sku" name="sku" readonly>
                                </div>

                                <div class="mb-3">
                                    <label for="short_description" class="form-label">Short Description</label>
                                    <textarea class="form-control @error('short_description') is-invalid @enderror" 
                                              id="short_description" name="short_description" rows="2">{{ old('short_description') }}</textarea>
                                    @error('short_description')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="mb-3">
                                    <label for="description" class="form-label">Full Description</label>
                                    <textarea class="form-control @error('description') is-invalid @enderror" 
                                              id="description" name="description" rows="4">{{ old('description') }}</textarea>
                                    @error('description')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="col-12">
                                    <div class="mb-3">
                                        <label for="images" class="form-label">Product Images</label>
                                        <div class="input-group">
                                            <input type="file" class="form-control @error('images') is-invalid @enderror" 
                                                   id="images" name="images[]" multiple accept="image/*">
                                            <button class="btn btn-outline-secondary" type="button" id="clearImages">Clear</button>
                                        </div>
                                        @error('images')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                        <div id="imagePreview" class="mt-2 d-flex flex-wrap gap-2"></div>
                                    </div>
    
                                    <div class="mb-3">
                                        <label for="tags" class="form-label">Tags (comma separated)</label>
                                        <input type="text" class="form-control @error('tags') is-invalid @enderror" 
                                               id="tags" name="tags" value="{{ old('tags') }}">
                                        @error('tags')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>


                                <div class="card-header">
                                    <h4 class="mb-0">Product Dimensions (Optional)</h4>
                                </div>
                                            <div class="row mt-2">
                                                <div class="col-4">
                                            <div class="mb-3">
                                                <label for="color" class="form-label">Color</label>
                                                <input type="text" class="form-control @error('color') is-invalid @enderror" 
                                                       id="color" name="color" value="{{ old('color') }}" 
                                                       placeholder="e.g., Red, Blue, Multi-color">
                                                @error('color')
                                                    <div class="invalid-feedback">{{ $message }}</div>
                                                @enderror

                                            </div>
                                                </div>
                                            
                                                <div class="col-4">
                                                <div class="mb-3">
                                                    <label for="weight" class="form-label">Weight (kg)</label>
                                                    <input type="number" step="0.01" class="form-control @error('weight') is-invalid @enderror" 
                                                        id="weight" name="weight" value="{{ old('weight') }}">
                                                    @error('weight')
                                                        <div class="invalid-feedback">{{ $message }}</div>
                                                    @enderror
                                                </div>
                                                </div>
                                            
                                                <div class="col-4">
                                                <div class="mb-3">
                                                    <label for="size" class="form-label">Size </label>
                                                    <input type="text"  class="form-control @error('size') is-invalid @enderror" 
                                                    id="size" name="size" value="{{ old('size') }}" 
                                                    placeholder="e.g., Bid, Medium, Small">
                                                    @error('size')
                                                        <div class="invalid-feedback">{{ $message }}</div>
                                                    @enderror
                                                </div>
                                            </div>
                                            
                                      
                                            
                                            
                                            </div>
                                        <hr>

                            </div>

                            
                                 

                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="category_id" class="form-label">Category</label>
                                    <select class="form-select @error('category_id') is-invalid @enderror" 
                                            id="category_id" name="category_id">
                                        <option value="">Select Category</option>
                                        @foreach($categories as $category)
                                            <option value="{{ $category->id }}" 
                                                    {{ old('category_id') == $category->id ? 'selected' : '' }}>
                                                {{ $category->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('category_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                                
                                <div class="mb-3">
                                    <label for="subcategory_id" class="form-label">Subcategory</label>
                                    <select class="form-select @error('subcategory_id') is-invalid @enderror" 
                                            id="subcategory_id" name="subcategory_id" disabled>
                                        <option value="">Select Subcategory</option>
                                    </select>
                                    @error('subcategory_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="mb-3">
                                    <label for="brand_id" class="form-label">Brand</label>
                                    <select class="form-select @error('brand_id') is-invalid @enderror" 
                                            id="brand_id" name="brand_id">
                                        <option value="">Select Brand</option>
                                        @foreach($brands as $brand)
                                            <option value="{{ $brand->id }}" 
                                                    {{ old('brand_id') == $brand->id ? 'selected' : '' }}>
                                                {{ $brand->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('brand_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="mb-3">
                                    <label for="purchase_price" class="form-label">Purchase Price</label>
                                    <input type="number" step="0.01" class="form-control @error('purchase_price') is-invalid @enderror" 
                                           id="purchase_price" name="purchase_price" value="{{ old('purchase_price') }}">
                                    @error('purchase_price')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="mb-3">
                                    <label for="price" class="form-label">Regular Price</label>
                                    <input type="number" step="0.01" class="form-control @error('price') is-invalid @enderror" 
                                           id="price" name="price" value="{{ old('price') }}">
                                    @error('price')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="mb-3">
                                    <label for="sale_price" class="form-label">Sale Price</label>
                                    <input type="number" step="0.01" class="form-control @error('sale_price') is-invalid @enderror" 
                                           id="sale_price" name="sale_price" value="{{ old('sale_price') }}">
                                    @error('sale_price')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="row">
                                    <div class="col-6">
                                        <div class="mb-3">
                                            <label for="sale_price_start_date" class="form-label">
                                                Sale Start Date (Optional)
                                            </label>
                                            <input type="datetime-local" 
                                                   class="form-control @error('sale_price_start_date') is-invalid @enderror" 
                                                   id="sale_price_start_date" 
                                                   name="sale_price_start_date" 
                                                   value="{{ old('sale_price_start_date') }}">
                                            @error('sale_price_start_date')
                                                <div class="invalid-feedback">{{ $message }}</div>
                                            @enderror
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="mb-3">
                                            <label for="sale_price_end_date" class="form-label">
                                                Sale End Date (Optional)
                                            </label>
                                            <input type="datetime-local" 
                                                   class="form-control @error('sale_price_end_date') is-invalid @enderror" 
                                                   id="sale_price_end_date" 
                                                   name="sale_price_end_date" 
                                                   value="{{ old('sale_price_end_date') }}">
                                            @error('sale_price_end_date')
                                                <div class="invalid-feedback">{{ $message }}</div>
                                            @enderror
                                        </div>
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <label for="stock_quantity" class="form-label">Stock Quantity</label>
                                    <input type="number" class="form-control @error('stock_quantity') is-invalid @enderror" 
                                           id="stock_quantity" name="stock_quantity" value="{{ old('stock_quantity', 0) }}">
                                    @error('stock_quantity')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="mb-3">
                                    <label for="low_stock_threshold" class="form-label">Low Stock Threshold</label>
                                    <input type="number" class="form-control @error('low_stock_threshold') is-invalid @enderror" 
                                           id="low_stock_threshold" name="low_stock_threshold" value="{{ old('low_stock_threshold', 5) }}">
                                    @error('low_stock_threshold')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <!-- Add Product Dimensions -->
                               


                                <div class="mb-3">
                                    <div class="form-check">
                                        <input type="checkbox" class="form-check-input" id="is_featured" name="is_featured" value="1" 
                                               {{ old('is_featured') ? 'checked' : '' }}>
                                        <label class="form-check-label" for="is_featured">Featured Product</label>
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <div class="form-check">
                                        <input type="checkbox" class="form-check-input" id="is_active" name="is_active" value="1" 
                                               {{ old('is_active', 1) ? 'checked' : '' }}>
                                        <label class="form-check-label" for="is_active">Active</label>
                                    </div>
                                </div>
                            </div>

                            
                        </div>

                        <div class="text-end mt-4">
                            <button type="submit" class="btn btn-primary">Create Product</button>
                            <a href="{{ route('admin.products.index') }}" class="btn btn-secondary">Cancel</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>


<script>
   document.getElementById('name').addEventListener('input', function(e) {
        const name = e.target.value;
        const timestamp = Date.now().toString().slice(-4);
        const randomStr = Math.random().toString(36).substring(2, 5).toUpperCase();
        const sku = `${name.slice(0, 3).toUpperCase()}-${timestamp}-${randomStr}`;
        document.getElementById('sku').value = sku;
    });

    // Load subcategories when category changes
    document.getElementById('category_id').addEventListener('change', function(e) {
    const categoryId = e.target.value;
    const subcategorySelect = document.getElementById('subcategory_id');
    
    if (categoryId) {
            fetch(`/admin/categories/${categoryId}/subcategories`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(response => {
                    subcategorySelect.innerHTML = '<option value="">Select Subcategory</option>';
                    if (response.data && Array.isArray(response.data)) {
                        response.data.forEach(subcategory => {
                            subcategorySelect.innerHTML += `
                                <option value="${subcategory.id}">${subcategory.name}</option>
                            `;
                        });
                        subcategorySelect.disabled = false;
                    } else {
                        throw new Error('Invalid data format');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    subcategorySelect.innerHTML = '<option value="">No subcategories available</option>';
                    subcategorySelect.disabled = true;
                });
        } else {
            subcategorySelect.innerHTML = '<option value="">Select Subcategory</option>';
            subcategorySelect.disabled = true;
        }
    });

    // Enhanced image preview with remove functionality
    document.getElementById('images').addEventListener('change', function(e) {
        const preview = document.getElementById('imagePreview');
        preview.innerHTML = '';
        
        [...e.target.files].forEach((file, index) => {
            const reader = new FileReader();
            reader.onload = function(e) {
                const wrapper = document.createElement('div');
                wrapper.className = 'position-relative';
                
                const img = document.createElement('img');
                img.src = e.target.result;
                img.className = 'rounded';
                img.style.width = '100px';
                img.style.height = '100px';
                img.style.objectFit = 'cover';
                
                const removeBtn = document.createElement('button');
                removeBtn.type = 'button';
                removeBtn.className = 'btn btn-danger btn-sm position-absolute top-0 end-0';
                removeBtn.innerHTML = '×';
                removeBtn.onclick = function() {
                    wrapper.remove();
                };
                
                wrapper.appendChild(img);
                wrapper.appendChild(removeBtn);
                preview.appendChild(wrapper);
            }
            reader.readAsDataURL(file);
        });
    });

    // Clear all images
    document.getElementById('clearImages').addEventListener('click', function() {
        document.getElementById('images').value = '';
        document.getElementById('imagePreview').innerHTML = '';
    });
</script>

@endsection