@extends('layouts.admin')

@section('title', 'Edit Variant - ' . $variant->sku)

@section('content')
<div class="admin-page-header">
    <h1>Edit Variant: {{ $variant->sku }}</h1>
    <a href="{{ route('admin.products.variants.index', $variant->parent_id) }}" class="btn btn-secondary">Back</a>
</div>

<div class="admin-card">
    <div class="card-body">
        <form action="{{ route('admin.products.variants.update', $variant->id) }}" method="POST" enctype="multipart/form-data">
            @csrf
            @method('PUT')

            <div class="admin-section-header mb-3">
                <h5><i class="bi bi-tags"></i> Variant Attributes</h5>
            </div>

            <div class="row mb-4">
                <div class="col-md-12 mb-3">
                    <label class="admin-form-label">Selected Attributes</label>
                    <div class="border rounded p-3">
                        @if($variant->attributeValues->isNotEmpty())
                            @foreach($variant->attributeValues as $attrValue)
                                <span class="badge bg-primary me-2 mb-2">
                                    {{ $attrValue->attribute->name }}: {{ $attrValue->value }}
                                </span>
                            @endforeach
                        @else
                            <span class="text-muted">No attributes assigned</span>
                        @endif
                    </div>
                </div>

                <div class="col-md-6 mb-3">
                    <label class="admin-form-label">Select Variation</label>
                    <select name="attribute_id" id="attributeSelect" class="form-select" onchange="loadAttributeValues()">
                        <option value="">Select Variation...</option>
                        @php
                            $firstAttributeId = $variant->attributeValues->first()?->attribute_id;
                        @endphp
                        @foreach($attributes as $attribute)
                            <option value="{{ $attribute->id }}" {{ $attribute->id == $firstAttributeId ? 'selected' : '' }}>{{ $attribute->name }}</option>
                        @endforeach
                    </select>
                </div>

                <div class="col-md-6 mb-3">
                    <label class="admin-form-label">Select Variant Value</label>
                    <select name="attribute_value_ids[]" id="attributeValueSelect" class="form-select">
                        <option value="">Select Variant Value...</option>
                    </select>
                    <small class="text-muted">Current selections are preserved.</small>
                </div>
            </div>

            <div class="admin-section-header mb-3">
                <h5><i class="bi bi-info-circle"></i> Variant Details</h5>
            </div>

            <div class="row">
                <div class="col-md-4 mb-3">
                    <label class="admin-form-label">Image</label>
                    @if($variant->image_path || $variant->image)
                        <div class="mb-2">
                            <x-product-image :product="$variant" context="detail" style="max-width: 100px; max-height: 100px;" />
                        </div>
                    @endif
                    <input type="file" name="image" class="form-control" accept="image/jpeg,image/png,image/jpg,image/webp">
                </div>

                <div class="col-md-4 mb-3">
                    <label class="admin-form-label">SKU</label>
                    <input type="text" name="sku" class="form-control" value="{{ old('sku', $variant->sku) }}">
                </div>

                <div class="col-md-3 mb-3">
                    <label class="admin-form-label">Purchase Price (₹)</label>
                    <input type="number" step="0.01" name="purchase_price" class="form-control" value="{{ old('purchase_price', $variant->purchase_price) }}">
                </div>

                <div class="col-md-3 mb-3">
                    <label class="admin-form-label">Sales Price (₹) *</label>
                    <input type="number" step="0.01" name="price" class="form-control" value="{{ old('price', $variant->price) }}" required>
                </div>

                <div class="col-md-3 mb-3">
                    <label class="admin-form-label">MRP (₹)</label>
                    <input type="number" step="0.01" name="mrp" class="form-control" value="{{ old('mrp', $variant->mrp) }}">
                </div>

                <div class="col-md-3 mb-3">
                    <label class="admin-form-label">Wholesale Price (₹)</label>
                    <input type="number" step="0.01" name="wholesale_price" class="form-control" value="{{ old('wholesale_price', $variant->wholesale_price) }}">
                </div>

                <div class="col-md-3 mb-3">
                    <label class="admin-form-label">Barcode</label>
                    <div class="input-group">
                        <input type="text"
                               name="barcode"
                               id="barcode"
                               class="admin-form-control form-control"
                               value="{{ old('barcode', $variant->barcode ?? '') }}"
                               readonly
                               style="background-color: #f8f9fa; font-weight: 600; font-family: 'Courier New', monospace;">
                    </div>
                    <small class="form-text text-muted">Cannot be changed after creation</small>
                </div>

                <div class="col-md-3 mb-3">
                    <label class="admin-form-label">HSN Code</label>
                    <input type="text" name="hsn_code" class="form-control" value="{{ old('hsn_code', $variant->hsn_code) }}">
                </div>

                <div class="col-md-3 mb-3">
                    <label class="admin-form-label">Warranty (Months)</label>
                    <input type="number" name="warranty_months" class="form-control" value="{{ old('warranty_months', $variant->warranty_months) }}" min="0">
                </div>

                <div class="col-md-3 mb-3">
                    <label class="admin-form-label">Shipping Days</label>
                    <input type="number" name="shipping_days" class="form-control" value="{{ old('shipping_days', $variant->shipping_days ?? $variant->parent?->shipping_days ?? \App\Models\Setting::get('default_shipping_days')) }}" min="0" placeholder="e.g. 3">
                </div>

                <div class="col-md-3 mb-3">
                    <label class="admin-form-label">Current Stock</label>
                    <input type="text" class="form-control" value="{{ $variant->current_stock }}" readonly style="background-color: #f8f9fa;">
                    <small class="text-muted">Stock is managed through stock movements</small>
                </div>

                <div class="col-md-12 mb-3">
                    <div class="form-check">
                        <input type="hidden" name="is_verified" value="0">
                        <input class="form-check-input" type="checkbox" name="is_verified" id="is_verified" value="1" {{ old('is_verified', $variant->is_verified) ? 'checked' : '' }}>
                        <label class="form-check-label me-3" for="is_verified">
                            Verified
                        </label>
                        <input class="form-check-input" type="checkbox" name="is_active" id="is_active" value="1" {{ old('is_active', $variant->is_active) ? 'checked' : '' }}>
                        <label class="form-check-label" for="is_active">
                            Active
                        </label>
                    </div>
                </div>

                <div class="col-md-12 mb-3">
                    <label class="admin-form-label">Show Product In *</label>
                    <div class="d-flex flex-wrap gap-3 mt-1">
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="channel_visibility" id="channelBoth" value="both" {{ old('channel_visibility', $variant->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', $variant->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', $variant->channel_visibility) === 'pos_only' ? 'checked' : '' }}>
                            <label class="form-check-label" for="channelPosOnly">Only POS</label>
                        </div>
                    </div>
                </div>
            </div>

            <div class="mt-4">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-check-circle"></i> Update Variant
                </button>
                <a href="{{ route('admin.products.variants.index', $variant->parent_id) }}" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script>
const attributes = @json($attributes->mapWithKeys(function($attr) {
    return [$attr->id => $attr->activeValues->map(function($val) {
        return ['id' => $val->id, 'value' => $val->value];
    })];
}));

const currentAttributeValueIds = @json($variant->attributeValues->pluck('id')->toArray());

function loadAttributeValues() {
    const attributeId = document.getElementById('attributeSelect').value;
    const valueSelect = document.getElementById('attributeValueSelect');
    
    // Clear existing options except current selections
    valueSelect.innerHTML = '';
    
    if (attributeId && attributes[attributeId]) {
        attributes[attributeId].forEach(function(value) {
            const option = document.createElement('option');
            option.value = value.id;
            option.textContent = value.value;
            if (currentAttributeValueIds.includes(value.id)) {
                option.selected = true;
            }
            valueSelect.appendChild(option);
        });
    }
}

// Pre-select current attribute values on page load
document.addEventListener('DOMContentLoaded', function() {
    // Get the first attribute that has values assigned to this variant
    const attributeSelect = document.getElementById('attributeSelect');
    const firstAttributeWithValues = @json($variant->attributeValues->first()?->attribute_id);
    
    if (firstAttributeWithValues) {
        attributeSelect.value = firstAttributeWithValues;
        loadAttributeValues();
    } else {
        // Fallback: manually add current values if no attribute is selected
        const valueSelect = document.getElementById('attributeValueSelect');
        @foreach($variant->attributeValues as $attrValue)
            const option{{ $attrValue->id }} = document.createElement('option');
            option{{ $attrValue->id }}.value = {{ $attrValue->id }};
            option{{ $attrValue->id }}.textContent = '{{ $attrValue->attribute->name }}: {{ $attrValue->value }}';
            option{{ $attrValue->id }}.selected = true;
            valueSelect.appendChild(option{{ $attrValue->id }});
        @endforeach
    }
});
</script>
@endsection
