@extends('layouts.admin')

@section('title', 'Edit Variant - ' . $variant->sku)

@section('content')
<x-admin.form-page
    title="Edit Variant: {{ $variant->sku }}"
    :crumbs="[
        ['label' => 'Products', 'url' => route('admin.products.index')],
        ['label' => 'Variants', 'url' => route('admin.products.variants.index', $variant->parent_id)],
        'Edit',
    ]"
    :back-url="route('admin.products.variants.index', $variant->parent_id)"
    :action="route('admin.products.variants.update', $variant->id)"
    method="PUT"
    form-id="variantEditForm"
    submit-label="Update Variant"
    enctype="multipart/form-data"
    :wide="true"
>
    <section class="pp-card">
        <div class="pp-card__head">
            <span class="pp-card__icon"><i class="bi bi-tags"></i></span>
            <div>
                <h2 class="pp-card__title">Variant Attributes</h2>
                <p class="pp-card__sub">Current selections and attribute values</p>
            </div>
        </div>
        <div class="pp-card__body">
            <div class="pp-field">
                <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="pp-grid pp-grid--2 mt-3">
                <div class="pp-field">
                    <label for="attributeSelect">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="pp-field">
                    <label for="attributeValueSelect">Select Variant Value</label>
                    <select name="attribute_value_ids[]" id="attributeValueSelect" class="form-select">
                        <option value="">Select Variant Value...</option>
                    </select>
                    <span class="pp-hint">Current selections are preserved.</span>
                </div>
            </div>
        </div>
    </section>

    <section class="pp-card">
        <div class="pp-card__head">
            <span class="pp-card__icon"><i class="bi bi-info-circle"></i></span>
            <div>
                <h2 class="pp-card__title">Variant Details</h2>
                <p class="pp-card__sub">Pricing, stock and visibility</p>
            </div>
        </div>
        <div class="pp-card__body">
            <div class="pp-grid pp-grid--4">
                <div class="pp-field">
                    <label for="variant_image">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" id="variant_image" class="form-control" accept="image/jpeg,image/png,image/jpg,image/webp">
                </div>

                <div class="pp-field">
                    <label for="sku">SKU</label>
                    <input type="text" name="sku" id="sku" class="form-control" value="{{ old('sku', $variant->sku) }}">
                </div>

                <div class="pp-field">
                    <label for="purchase_price">Purchase Price (₹)</label>
                    <input type="number" step="0.01" name="purchase_price" id="purchase_price" class="form-control" value="{{ old('purchase_price', $variant->purchase_price) }}">
                </div>

                <div class="pp-field">
                    <label for="price">Sales Price (₹) <span class="pp-req">*</span></label>
                    <input type="number" step="0.01" name="price" id="price" class="form-control" value="{{ old('price', $variant->price) }}" required>
                </div>

                <div class="pp-field">
                    <label for="mrp">MRP (₹)</label>
                    <input type="number" step="0.01" name="mrp" id="mrp" class="form-control" value="{{ old('mrp', $variant->mrp) }}">
                </div>

                <div class="pp-field">
                    <label for="wholesale_price">Wholesale Price (₹)</label>
                    <input type="number" step="0.01" name="wholesale_price" id="wholesale_price" class="form-control" value="{{ old('wholesale_price', $variant->wholesale_price) }}">
                </div>

                <div class="pp-field">
                    <label for="barcode">Barcode</label>
                    <input type="text"
                           name="barcode"
                           id="barcode"
                           class="form-control"
                           value="{{ old('barcode', $variant->barcode ?? '') }}"
                           readonly
                           style="background-color: #f8f9fa; font-weight: 600; font-family: 'Courier New', monospace;">
                    <span class="pp-hint">Cannot be changed after creation</span>
                </div>

                <div class="pp-field">
                    <label for="hsn_code">HSN Code</label>
                    <input type="text" name="hsn_code" id="hsn_code" class="form-control" value="{{ old('hsn_code', $variant->hsn_code) }}">
                </div>

                <div class="pp-field">
                    <label for="warranty_months">Warranty (Months)</label>
                    <input type="number" name="warranty_months" id="warranty_months" class="form-control" value="{{ old('warranty_months', $variant->warranty_months) }}" min="0">
                </div>

                <div class="pp-field">
                    <label for="shipping_days">Shipping Days</label>
                    <input type="number" name="shipping_days" id="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="pp-field">
                    <label>Current Stock</label>
                    <input type="text" class="form-control" value="{{ $variant->current_stock }}" readonly style="background-color: #f8f9fa;">
                    <span class="pp-hint">Stock is managed through stock movements</span>
                </div>
            </div>

            <div class="pp-toggles mt-3">
                <input type="hidden" name="is_verified" value="0">
                <label class="pp-toggle" for="is_verified">
                    <input class="form-check-input" type="checkbox" name="is_verified" id="is_verified" value="1" {{ old('is_verified', $variant->is_verified) ? 'checked' : '' }}>
                    Verified
                </label>
                <label class="pp-toggle" for="is_active">
                    <input class="form-check-input" type="checkbox" name="is_active" id="is_active" value="1" {{ old('is_active', $variant->is_active) ? 'checked' : '' }}>
                    Active
                </label>
            </div>

            <div class="pp-field mt-3">
                <label>Show Product In <span class="pp-req">*</span></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>
    </section>
</x-admin.form-page>

@push('scripts')
<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');

    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);
        });
    }
}

document.addEventListener('DOMContentLoaded', function() {
    const attributeSelect = document.getElementById('attributeSelect');
    const firstAttributeWithValues = @json($variant->attributeValues->first()?->attribute_id);

    if (firstAttributeWithValues) {
        attributeSelect.value = firstAttributeWithValues;
        loadAttributeValues();
    } else {
        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>
@endpush
@endsection
