@extends('admin.layouts.app')

@section('title', 'Create Product')
@section('page-title', 'Create Product')

@section('content')
<form method="POST" action="{{ route('admin.products.store') }}" enctype="multipart/form-data" class="bg-white p-4 md:p-6 lg:p-8 rounded-2xl shadow-md border border-[#d1d5db]">
    @csrf
    
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
            <label for="name" class="block text-sm font-semibold mb-2 text-black">Product Name *</label>
            <input type="text" id="name" name="name" required value="{{ old('name') }}" 
                   class="w-full px-3 md:px-4 py-2 md:py-3 border-2 border-[#d1d5db] rounded-xl focus:ring-2 focus:ring-black focus:border-black transition-all outline-none text-black text-sm md:text-base">
            @error('name')<p class="text-red-500 text-sm mt-1">{{ $message }}</p>@enderror
        </div>
        
        <div>
            <label for="category_id" class="block text-sm font-semibold mb-2 text-black">Category *</label>
            <select id="category_id" name="category_id" required class="w-full px-3 md:px-4 py-2 md:py-3 border-2 border-[#d1d5db] rounded-xl focus:ring-2 focus:ring-black focus:border-black transition-all outline-none text-black bg-white text-sm md:text-base">
                <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')<p class="text-red-500 text-sm mt-1">{{ $message }}</p>@enderror
        </div>
        
        <div>
            <label for="price" class="block text-sm font-semibold mb-2 text-black">Price (R) *</label>
            <input type="number" id="price" name="price" step="0.01" min="0" required value="{{ old('price') }}" 
                   class="w-full px-3 md:px-4 py-2 md:py-3 border-2 border-[#d1d5db] rounded-xl focus:ring-2 focus:ring-black focus:border-black transition-all outline-none text-black text-sm md:text-base">
            @error('price')<p class="text-red-500 text-sm mt-1">{{ $message }}</p>@enderror
        </div>
        
        <div>
            <label for="sale_price" class="block text-sm font-semibold mb-2 text-black">Sale Price (R) <span class="text-black text-xs">(Optional)</span></label>
            <input type="number" id="sale_price" name="sale_price" step="0.01" min="0" value="{{ old('sale_price') }}" 
                   class="w-full px-3 md:px-4 py-2 md:py-3 border-2 border-[#d1d5db] rounded-xl focus:ring-2 focus:ring-black focus:border-black transition-all outline-none text-black text-sm md:text-base">
            <p class="text-xs text-gray-500 mt-1">Leave empty if not on sale. Must be less than regular price.</p>
            @error('sale_price')<p class="text-red-500 text-sm mt-1">{{ $message }}</p>@enderror
        </div>
        
        <div class="flex flex-col sm:flex-row sm:items-center gap-4 sm:gap-6">
            <label class="flex items-center cursor-pointer">
                <input type="checkbox" name="featured" value="1" {{ old('featured') ? 'checked' : '' }} class="w-4 h-4 text-black border-[#d1d5db] rounded focus:ring-black mr-2">
                <span class="text-sm md:text-base text-black">Featured Product</span>
            </label>
            <label class="flex items-center cursor-pointer">
                <input type="checkbox" name="availability" value="1" {{ old('availability', true) ? 'checked' : '' }} class="w-4 h-4 text-black border-[#d1d5db] rounded focus:ring-black mr-2">
                <span class="text-sm md:text-base text-black">Available</span>
            </label>
        </div>
        
        <div class="md:col-span-2">
            <label for="description" class="block text-sm font-semibold mb-2 text-black">Description</label>
            <textarea id="description" name="description" rows="4" 
                      class="w-full px-3 md:px-4 py-2 md:py-3 border-2 border-[#d1d5db] rounded-xl focus:ring-2 focus:ring-black focus:border-black transition-all outline-none text-black resize-none text-sm md:text-base">{{ old('description') }}</textarea>
            @error('description')<p class="text-red-500 text-sm mt-1">{{ $message }}</p>@enderror
        </div>
        
        <div class="md:col-span-2">
            <label for="images" class="block text-sm font-semibold mb-2 text-black">Product Images</label>
            <input type="file" id="images" name="images[]" multiple accept="image/*" 
                   class="w-full px-3 md:px-4 py-2 md:py-3 border-2 border-[#d1d5db] rounded-xl focus:ring-2 focus:ring-black focus:border-black transition-all outline-none text-black text-sm md:text-base"
                   onchange="previewImages(this)">
            <p class="text-xs md:text-sm text-black mt-2 bg-[#f3f4f6] p-2 md:p-3 rounded-lg border border-[#d1d5db]">
                <strong>💡 Tip:</strong> You can select multiple images at once. The first image will automatically be set as the primary (main) image.
            </p>
            <div id="image-preview" class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3 md:gap-4 mt-4"></div>
            @error('images.*')<p class="text-red-500 text-sm mt-1">{{ $message }}</p>@enderror
        </div>
        
        <div class="md:col-span-2">
            <label class="block text-sm font-semibold mb-2 text-black">
                Specifications
                <span class="text-black text-xs font-normal">(Optional)</span>
            </label>
            <div class="bg-[#f3f4f6] p-4 rounded-xl border border-[#d1d5db] mb-3">
                <p class="text-sm text-black mb-3"><strong>What are Specifications?</strong></p>
                <p class="text-xs text-black mb-2">Add additional product details that will be displayed on the product page. Examples: Size, Ingredients, Allergens, Storage instructions, etc.</p>
            </div>
            
            <div id="specifications-container" class="space-y-3 mb-3">
                <!-- Specifications will be added here dynamically -->
            </div>
            
            <button type="button" onclick="addSpecification()" class="bg-black text-white px-4 py-2 rounded-xl hover:bg-[#1a1a1a] transition-all font-medium text-sm flex items-center gap-2">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                </svg>
                Add Specification
            </button>
            
            <!-- Hidden input to store JSON -->
            <input type="hidden" id="specs" name="specs" value="{{ old('specs', '') }}">
        </div>
    </div>
    
    <div class="mt-6 md:mt-8 flex flex-col sm:flex-row gap-3 md:gap-4">
        <button type="submit" class="w-full sm:w-auto bg-black text-white px-6 md:px-8 py-2 md:py-3 rounded-full hover:bg-black transition-all font-semibold shadow-lg hover:shadow-xl transform hover:scale-105 text-sm md:text-base">
            Create Product
        </button>
        <a href="{{ route('admin.products.index') }}" class="w-full sm:w-auto bg-[#d1d5db] text-black px-6 md:px-8 py-2 md:py-3 rounded-full hover:bg-[#e6d5b8] transition-all font-semibold text-center text-sm md:text-base">
            Cancel
        </a>
    </div>
</form>
@endsection

@push('scripts')
<script>
let specCounter = 0;

function addSpecification(key = '', value = '') {
    const container = document.getElementById('specifications-container');
    const div = document.createElement('div');
    div.className = 'flex flex-col sm:flex-row gap-3 items-start bg-white p-3 md:p-4 rounded-xl border border-[#d1d5db]';
    div.id = `spec-${specCounter}`;
    
    div.innerHTML = `
        <div class="flex-1">
            <input type="text" 
                   placeholder="Specification name (e.g., Size, Ingredients, Allergens)" 
                   value="${key}"
                   class="spec-key w-full px-3 md:px-4 py-2 border-2 border-[#d1d5db] rounded-lg focus:ring-2 focus:ring-black focus:border-black transition-all outline-none text-black text-sm"
                   onchange="updateSpecsJSON()">
        </div>
        <div class="flex-1">
            <input type="text" 
                   placeholder="Value (e.g., Medium, Flour, Sugar, Eggs)" 
                   value="${value}"
                   class="spec-value w-full px-3 md:px-4 py-2 border-2 border-[#d1d5db] rounded-lg focus:ring-2 focus:ring-black focus:border-black transition-all outline-none text-black text-sm"
                   onchange="updateSpecsJSON()">
        </div>
        <button type="button" 
                onclick="removeSpecification(${specCounter})" 
                class="bg-black text-white px-3 py-2 rounded-lg hover:bg-[#1a1a1a] transition-all flex-shrink-0">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
        </button>
    `;
    
    container.appendChild(div);
    specCounter++;
    updateSpecsJSON();
}

function removeSpecification(id) {
    const element = document.getElementById(`spec-${id}`);
    if (element) {
        element.remove();
        updateSpecsJSON();
    }
}

function updateSpecsJSON() {
    const container = document.getElementById('specifications-container');
    const specs = {};
    
    container.querySelectorAll('[id^="spec-"]').forEach(specDiv => {
        const keyInput = specDiv.querySelector('.spec-key');
        const valueInput = specDiv.querySelector('.spec-value');
        
        if (keyInput && valueInput && keyInput.value.trim() && valueInput.value.trim()) {
            specs[keyInput.value.trim()] = valueInput.value.trim();
        }
    });
    
    document.getElementById('specs').value = Object.keys(specs).length > 0 ? JSON.stringify(specs) : '';
}

// Load existing specs if editing (for edit page)
@if(old('specs'))
    try {
        const existingSpecs = JSON.parse('{{ old('specs') }}');
        Object.entries(existingSpecs).forEach(([key, value]) => {
            addSpecification(key, value);
        });
    } catch(e) {
        console.error('Error parsing specs:', e);
    }
@endif

function previewImages(input) {
    const preview = document.getElementById('image-preview');
    preview.innerHTML = '';
    
    if (input.files) {
        Array.from(input.files).forEach((file, index) => {
            const reader = new FileReader();
            reader.onload = function(e) {
                const div = document.createElement('div');
                div.className = 'relative';
                div.innerHTML = `
                    <img src="${e.target.result}" class="w-full h-32 object-cover rounded-lg border border-[#d1d5db]">
                    ${index === 0 ? '<span class="absolute top-2 left-2 bg-black text-white text-xs px-2 py-1 rounded-full font-semibold">Primary</span>' : ''}
                `;
                preview.appendChild(div);
            };
            reader.readAsDataURL(file);
        });
    }
}
</script>
@endpush

