@extends('layouts.admin')

@section('title', 'Add New Product')

@section('content')
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
    <!-- Header -->
    <div class="flex items-center justify-between mb-6">
        <div>
            <h1 class="text-3xl font-bold text-gray-900">Add New Product</h1>
            <p class="text-gray-600 mt-1">Create a new fish product for your store</p>
        </div>
        <a href="{{ route('admin.products.index') }}" 
           class="bg-gray-600 hover:bg-gray-700 text-white font-medium py-2 px-4 rounded-lg transition duration-200">
            <svg class="w-5 h-5 inline-block mr-2" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd"/>
            </svg>
            Back to Products
        </a>
    </div>

    <!-- Error Messages -->
    @if($errors->any())
        <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">
            <ul class="list-disc list-inside">
                @foreach($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <!-- Product Form -->
    <form method="POST" action="{{ route('admin.products.store') }}" enctype="multipart/form-data" class="space-y-6">
        @csrf
        
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Main Content -->
            <div class="lg:col-span-2 space-y-6">
                <!-- Basic Information -->
                <div class="bg-white rounded-lg shadow-sm border p-6">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">Basic Information</h3>
                    
                    <!-- Product Name -->
                    <div class="mb-4">
                        <label for="name" class="block text-sm font-medium text-gray-700 mb-2">Product Name *</label>
                        <input type="text" id="name" name="name" value="{{ old('name') }}" required
                               class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                               placeholder="e.g., Fresh Rohu Fish">
                    </div>

                    <!-- Short Description -->
                    <div class="mb-4">
                        <label for="short_description" class="block text-sm font-medium text-gray-700 mb-2">Short Description</label>
                        <div id="short-description-editor" style="height: 150px;">{!! old('short_description') !!}</div>
                        <textarea id="short_description" name="short_description" style="display: none;">{!! old('short_description') !!}</textarea>
                    </div>

                    <!-- Full Description -->
                    <div class="mb-4">
                        <label for="description" class="block text-sm font-medium text-gray-700 mb-2">Full Description *</label>
                        <div id="full-description-editor" style="height: 300px;">{!! old('description') !!}</div>
                        <textarea id="description" name="description" style="display: none;" required>{!! old('description') !!}</textarea>
                    </div>
                </div>

                <!-- Product Variants / Weight Pricing -->
                <div class="bg-white rounded-lg shadow-sm border p-6">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-medium text-gray-900">Product Variants / Weight Pricing</h3>
                        <button type="button" id="addVariantBtn"
                                class="bg-blue-600 hover:bg-blue-700 text-white font-medium py-1.5 px-3 rounded-md text-sm transition duration-200">
                            + Add Variant
                        </button>
                    </div>

                    <p class="text-sm text-gray-500 mb-4">
                        Define each size/weight option and its pricing below. The first variant is used as the
                        product's primary price shown on catalog, cart and checkout.
                    </p>

                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200" id="variantsTable">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">Variant Label</th>
                                    <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">Unit</th>
                                    <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">Base Unit Rate</th>
                                    <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">Final Selling Price</th>
                                    <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">Sale Price</th>
                                    <th class="px-3 py-2 text-right text-xs font-medium text-gray-500 uppercase">Action</th>
                                </tr>
                            </thead>
                            <tbody id="variantsTbody" class="bg-white divide-y divide-gray-200">
                                @forelse(old('variants', []) as $index => $variant)
                                    @include('admin.products.partials._variant_row', ['variant' => $variant, 'index' => $index])
                                @empty
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Sidebar -->
            <div class="space-y-6">
                <!-- Product Images -->
                <div class="bg-white rounded-lg shadow-sm border p-6">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">Product Images</h3>
                    
                    <div class="space-y-4">
                        <div>
                            <label for="images" class="block text-sm font-medium text-gray-700 mb-2">Upload Images</label>
                            <input type="file" id="images" name="images[]" multiple accept="image/*"
                                   class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <p class="text-sm text-gray-500 mt-1">Maximum 5 images. Supported: JPEG, PNG, GIF (max 2MB each)</p>
                        </div>
                        
                        <!-- Image Preview -->
                        <div id="imagePreview" class="grid grid-cols-2 gap-2 mt-4"></div>
                    </div>
                </div>

                <!-- Category -->
                <div class="bg-white rounded-lg shadow-sm border p-6">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">Category</h3>
                    
                    <div>
                        <label for="category_id" class="block text-sm font-medium text-gray-700 mb-2">Product Category *</label>
                        <select id="category_id" name="category_id" required
                                class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">Select Category</option>
                            @foreach($categories as $category)
                                <option value="{{ $category->id }}" {{ old('category_id') == $category->id ? 'selected' : '' }}>
                                    {{ $category->name }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                </div>

                <!-- Services -->
                <div class="bg-white rounded-lg shadow-sm border p-6">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">Services</h3>
                    <div class="space-y-3">
                        @foreach($services as $service)
                            <div class="border border-gray-200 rounded-md p-3">
                                <div class="flex items-center">
                                    <input type="checkbox" id="service_{{ $service->id }}" name="services[]" value="{{ $service->id }}"
                                           {{ in_array($service->id, old('services', [])) ? 'checked' : '' }}
                                           onchange="toggleServiceFields(this, 'service-fields-{{ $service->id }}')"
                                           class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                                    <label for="service_{{ $service->id }}" class="ml-2 text-sm font-medium text-gray-700">
                                        {{ $service->name }}
                                    </label>
                                </div>
                                <div id="service-fields-{{ $service->id }}" class="{{ in_array($service->id, old('services', [])) ? '' : 'hidden' }} mt-3 ml-6 space-y-2">
                                    <div>
                                        <label class="block text-xs font-medium text-gray-500 mb-1">Override Price (৳)</label>
                                        <input type="number" step="0.01" name="service_override_price[{{ $service->id }}]" value="{{ old("service_override_price.{$service->id}") }}" placeholder="Leave empty for default"
                                               class="w-full border border-gray-300 rounded-md px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                                    </div>
                                    <div class="flex items-center">
                                        <input type="checkbox" id="service_enabled_{{ $service->id }}" name="service_enabled[{{ $service->id }}]" value="1"
                                               {{ old("service_enabled.{$service->id}", true) ? 'checked' : '' }}
                                               class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                                        <label for="service_enabled_{{ $service->id }}" class="ml-2 text-sm text-gray-700">
                                            Enabled
                                        </label>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>

                <!-- Product Status -->
                <div class="bg-white rounded-lg shadow-sm border p-6">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">Product Status</h3>
                    
                    <div class="space-y-4">
                        <!-- Active Status -->
                        <label class="flex items-center">
                            <input type="checkbox" name="is_active" value="1" {{ old('is_active', true) ? 'checked' : '' }}
                                   class="rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50">
                            <span class="ml-2 text-sm text-gray-700">Active (visible to customers)</span>
                        </label>

                        <!-- Featured Status -->
                        <label class="flex items-center">
                            <input type="checkbox" name="is_featured" value="1" {{ old('is_featured') ? 'checked' : '' }}
                                   class="rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50">
                            <span class="ml-2 text-sm text-gray-700">Featured product</span>
                        </label>
                    </div>
                </div>

                <!-- Submit Button -->
                <div class="bg-white rounded-lg shadow-sm border p-6">
                    <button type="submit" 
                            class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-4 rounded-lg transition duration-200">
                        Create Product
                    </button>
                </div>
            </div>
        </div>
    </form>
</div>

<!-- Quill.js - Free Rich Text Editor -->
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>

<script>
    var shortDescQuill = new Quill('#short-description-editor', {
        theme: 'snow',
        modules: {
            toolbar: [
                ['bold', 'italic', 'underline', 'strike'],
                [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                ['link', 'clean']
            ]
        }
    });

    var fullDescQuill = new Quill('#full-description-editor', {
        theme: 'snow',
        modules: {
            toolbar: [
                [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                [{ 'font': [] }],
                [{ 'size': ['small', false, 'large', 'huge'] }],
                ['bold', 'italic', 'underline', 'strike'],
                [{ 'color': [] }, { 'background': [] }],
                [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                [{ 'indent': '-1' }, { 'indent': '+1' }],
                [{ 'direction': 'rtl' }],
                [{ 'align': [] }],
                ['link', 'image', 'video'],
                ['blockquote', 'code-block'],
                ['clean']
            ]
        }
    });

    shortDescQuill.on('text-change', function() {
        document.querySelector('#short_description').value = shortDescQuill.root.innerHTML;
    });

    fullDescQuill.on('text-change', function() {
        document.querySelector('#description').value = fullDescQuill.root.innerHTML;
    });

    document.querySelector('form').onsubmit = function() {
        document.querySelector('#short_description').value = shortDescQuill.root.innerHTML;
        document.querySelector('#description').value = fullDescQuill.root.innerHTML;
    };
</script>

<style>
    #short-description-editor, #full-description-editor {
        background: #fff;
    }
    .ql-editor {
        min-height: 150px;
        font-size: 15px;
        line-height: 1.6;
    }
    #full-description-editor .ql-editor {
        min-height: 250px;
    }
    .ql-toolbar {
        border-top: 1px solid #ccc;
        border-left: 1px solid #ccc;
        border-right: 1px solid #ccc;
    }
    .ql-container {
        border-bottom: 1px solid #ccc;
        border-left: 1px solid #ccc;
        border-right: 1px solid #ccc;
    }
</style>

<script>
function toggleServiceFields(checkbox, fieldsId) {
    const fields = document.getElementById(fieldsId);
    if (checkbox.checked) {
        fields.classList.remove('hidden');
    } else {
        fields.classList.add('hidden');
    }
}

document.getElementById('images').addEventListener('change', function(e) {
    const preview = document.getElementById('imagePreview');
    preview.innerHTML = '';
    
    for (let i = 0; i < e.target.files.length && i < 5; i++) {
        const file = e.target.files[i];
        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-24 object-cover rounded border">
                <div class="absolute top-1 right-1 bg-gray-800 text-white text-xs px-1 rounded">${i + 1}</div>
            `;
            preview.appendChild(div);
        };
        
        reader.readAsDataURL(file);
    }
});

let variantCounter = document.querySelectorAll('#variantsTbody tr.variant-row').length;

function variantRowHtml(index) {
    return `<tr class="variant-row">
        <td class="px-3 py-2">
            <input type="text" name="variants[${index}][label]" value="" required
                   class="w-full border border-gray-300 rounded-md px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                   placeholder="e.g. 1100–1190 gm (Per Piece)">
        </td>
        <td class="px-3 py-2">
            <select name="variants[${index}][unit]"
                    class="w-full border border-gray-300 rounded-md px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                <option value="kg">kg</option>
                <option value="gm">gm</option>
                <option value="pcs">pcs</option>
            </select>
        </td>
        <td class="px-3 py-2">
            <input type="number" name="variants[${index}][base_unit_price]" value="" required step="0.01" min="0"
                   class="w-full border border-gray-300 rounded-md px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                   placeholder="0.00">
        </td>
        <td class="px-3 py-2">
            <input type="number" name="variants[${index}][final_price]" value="" required step="0.01" min="0"
                   class="w-full border border-gray-300 rounded-md px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                   placeholder="0.00">
        </td>
        <td class="px-3 py-2">
            <input type="number" name="variants[${index}][sale_price]" value="" step="0.01" min="0"
                   class="w-full border border-gray-300 rounded-md px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                   placeholder="0.00">
        </td>
        <td class="px-3 py-2 text-right">
            <button type="button" onclick="removeVariantRow(this)"
                    class="text-red-600 hover:text-red-800 font-medium text-sm">🗑️</button>
        </td>
    </tr>`;
}

function addVariantRow() {
    document.getElementById('variantsTbody').insertAdjacentHTML('beforeend', variantRowHtml(variantCounter++));
}

function removeVariantRow(btn) {
    btn.closest('tr').remove();
}

document.getElementById('addVariantBtn').addEventListener('click', addVariantRow);

// Ensure at least one variant row exists on load (e.g. after validation errors)
if (variantCounter === 0) {
    addVariantRow();
}
</script>
@endsection
