@extends('Admin.layout.app')

@section('content')
<div class="">
   <form method="POST"
      action="{{ $product ? route('admin.products.update', $product->id) : route('admin.products.store') }}"
      enctype="multipart/form-data">

        @csrf
        @if($product)
            @method('PUT')
        @endif

       <h4 class="mb-3">
        {{ $product ? 'Edit Product' : 'Add New Product' }}
      </h4>

        <div class="row">
            <div class="col-lg-8">
                 
                    <div class="mb-4">
                        <h6 class="mb-3">Product Information</h6>
                        <div class="row mb-3">
                            <label class="col-md-3 col-form-label">Product Name <span class="text-danger">*</span></label>
                            <div class="col-md-9">
                                <input type="text"
                                   name="name"
                                   class="form-control"
                                   value="{{ old('name', $product->name ?? '') }}">
                                <small class="text-muted">This name will appear on the product page</small>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <label class="col-md-3 col-form-label">Category <span class="text-danger">*</span></label>
                            <div class="col-md-9">
                                <select name="category_id" class="form-control">
                                   <option value="">Select Category</option>
                                   @foreach($categories as $category)
                                       <option value="{{ $category->id }}"
                                           {{ old('category_id', $product->category_id ?? '') == $category->id ? 'selected' : '' }}>
                                           {{ $category->name }}
                                       </option>
                                   @endforeach
                               </select>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <label class="col-md-3 col-form-label">Brand</label>
                            <div class="col-md-9">
                                <select class="form-select" name="brand_id" id="brand_id">
                                    <option value="">Select Brand</option>
                                    @foreach (\App\Models\Brand::all() as $brand)
                                        <option value="{{ $brand->id }}"
                                            {{ old('brand_id', $product->brand_id ?? '') == $brand->id ? 'selected' : '' }}>
                                            {{ $brand->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <label class="col-md-3 col-form-label">Unit</label>
                            <div class="col-md-9">
                                <input type="text"
                                   name="unit"
                                   class="form-control"
                                   value="{{ old('unit', $product->unit ?? '') }}" required>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <label class="col-md-3 col-form-label">Minimum Purchase Qty <span class="text-danger">*</span></label>
                            <div class="col-md-9">
                                <input type="number"
                                   name="min_qty"
                                   class="form-control"
                                   value="{{ old('min_qty', $product->min_qty ?? '') }}" required>
                            </div>
                        </div>
                    </div>

                    <div class="mb-4">
                     <h6 class="mb-3">Product Images</h6>

                        <div class="row mb-3">
                             <label class="col-md-3 col-form-label">Gallery Images <small>(600x600)</small></label>
                            <div class="col-md-9">
                              <button type="button"
                                  class="btn btn-outline-primary open-uploader"
                                  data-input="gallery_images_hidden"
                                  data-preview="gallery_preview_main"
                                  data-multiple="true">
                                 Choose Image
                              </button>

                              <div class="row mt-2 g-2" id="gallery_preview_main">
                                  @if(isset($product) && $product->photos)
                                    @php
                                        $galleryPhotos = [];
                                        if (!empty($product->photos)) {
                                            $galleryPhotos = is_array($product->photos)
                                                ? $product->photos
                                                : explode(',', $product->photos);
                                        }
                                    @endphp
                                    @foreach($galleryPhotos as $photo)
                                        <div class="col-auto">
                                            <img src="{{ asset('storage/'.$photo) }}"
                                                 class="img-thumbnail"
                                                 style="width:100px;height:100px;object-fit:cover;">
                                        </div>
                                    @endforeach
                                  @endif
                              </div>

                                <!-- Hidden Input -->
                                 <input type="hidden"
                                        name="photos"
                                        id="gallery_images_hidden"
                                        value="{{ old('photos', $product->photos ?? '') }}">

                                 <small class="text-muted">
                                     These images will appear in product gallery
                                 </small>
                            </div>
                        </div>

                       <div class="row mb-3">
                                <label class="col-md-3 col-form-label">Thumbnail Image <small>(300x300)</small></label>
                            <div class="col-md-9">

                                <button type="button"
                                     class="btn btn-outline-primary open-uploader"
                                     data-input="thumbnail_image_hidden"
                                     data-preview="thumbnail_preview_main"
                                     data-multiple="false">
                                      Upload Thumbnail
                                </button>

                                <!-- Hidden Input -->
                                  <input type="hidden"
                                         name="thumbnail_img"
                                         id="thumbnail_image_hidden"
                                         value="{{ old('thumbnail_img', $product->thumbnail_img ?? '') }}">

                                  <!-- Preview -->
                                  <div class="mt-2">
                                      <img id="thumbnail_preview_main"
                                           src="{{ isset($product) && $product->thumbnail_img ? asset('storage/'.$product->thumbnail_img) : '' }}"
                                           class="img-fluid {{ isset($product) && $product->thumbnail_img ? '' : 'd-none' }}"
                                           style="max-height:120px;">
                                  </div>

                                 <small class="text-muted">This image is visible in all product box. Use 300x300 sizes image. Keep some blank space around main object of your image as we had to crop some edge in different devices to make it responsive.</small>
                           </div>
                        </div> 
                   </div>

                   <div class="mb-4">
                     <h6 class="mb-3">Product Variation</h6>               

                     <div class="row mb-3 align-items-center">
                         <label class="col-md-3 col-form-label">Color</label>               
  
                         <div class="col-md-8">
                           <select
                               class="form-control"
                               data-live-search="true"
                               data-selected-text-format="count"
                               name="colors[]"
                               id="colors"
                               multiple
                               {{ isset($product) && $product->colors_active ? '' : 'disabled' }}>
                             @php
                                $selectedColors = old('colors', []);
                             
                                if(isset($product->colors) && !empty($product->colors)) {
                                    $decoded = json_decode($product->colors, true);
                                    if(is_array($decoded)) {
                                        $selectedColors = $decoded;
                                    }
                                }
                             @endphp

                              @foreach (\App\Models\Color::orderBy('name', 'asc')->get() as $color)
                                 <option value="{{ $color->code }}"
                                 {{ in_array($color->code, $selectedColors) ? 'selected' : '' }}
                                 style="display:block;  rounded border;width:30px;height:30px;background:{{ $color->code }};border:1px solid #ccc;">
                                   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {{ $color->name }}
                                   
                                  </option> 
                                @endforeach
                             
                            
                           </select>
                         </div>               
  
                         <div class="col-md-1 text-center">
                           <label class="custom-checkbox">
                               <input type="checkbox"
                                      name="colors_active"
                                      id="colors_active"
                                      value="1"
                                      {{ old('colors_active', $product->colors_active ?? 0) ? 'checked' : '' }}>
                               <span class="checkmark"></span>
                           </label>
                         </div>
                     </div>
                  </div>

                  <div class="mb-4">
                      <div class="row mb-3"> 
                          <label class="col-md-3 col-form-label">Attribute</label>
                          <div class="col-md-9"> 
                              <select name="choice_attributes[]" id="choice_attributes"
                                  class="form-control"
                                  data-selected-text-format="count"
                                  data-live-search="true"
                                  data-placeholder="Choose Attributes"
                                  >
                                  
                                  @php
                                      // Step 1: Get old input if validation fails
                                      $selectedAttrs = old('choice_attributes');

                                      // Step 2: If old input is empty, use product data
                                      if(empty($selectedAttrs)) {
                                          $selectedAttrs = $product->choice_attributes ?? $product->attributes ?? [];
                                      }

                                      // Step 3: Normalize to array
                                      if(is_string($selectedAttrs)) {
                                          $selectedAttrs = json_decode($selectedAttrs, true) ?? [];
                                      }
                                  @endphp

                                 @foreach (\App\Models\Attribute::all() as $attribute)
                                    <option value="{{ $attribute->id }}" 
                                        {{ in_array($attribute->id, $selectedAttrs) ? 'selected' : '' }}>
                                        {{ $attribute->name }}
                                    </option>
                                  @endforeach
                             </select>
                          </div>
                      </div>
                  </div>

                    <div class="customer_choice_options" id="customer_choice_options">
                            @foreach (json_decode($product->choice_options) as $key => $choice_option)
                            <div class="form-group row">
                                <div class="col-lg-3">
                                    <input type="hidden" name="choice_no[]" value="{{ $choice_option->attribute_id }}">
                                    <input type="text" class="form-control" name="choice[]" value="{{ optional(\App\Models\Attribute::find($choice_option->attribute_id))->name }}" placeholder="Choice Title" disabled>
                                </div>
                                <div class="col-lg-8">
                                    <select class="form-control attribute_choice" data-live-search="true" name="choice_options_{{ $choice_option->attribute_id }}[]" multiple>
                                        @foreach (\App\Models\AttributeValue::where('attribute_id', $choice_option->attribute_id)->get() as $row)
                                        <option value="{{ $row->value }}" @if( in_array($row->value, $choice_option->values)) selected @endif>
                                            {{ $row->value }}
                                        </option>
                                        @endforeach
                                    </select>
                                    {{-- <input type="text" class="form-control aiz-tag-input" name="choice_options_{{ $choice_option->attribute_id }}[]" placeholder="Enter choice values" value="{{ implode(',', $choice_option->values) }}" data-on-change="update_sku"> --}}
                                </div>
                            </div>
                            @endforeach
                    </div>
                      <br>
                    <div class="sku_combination" id="sku_combination">
                        
                    </div>


                    <div class="mb-4">
                        <h6 class="mb-3">Product price + stock</h6>
                        <div class="row mb-3">
                            <label class="col-md-3 col-form-label">Unit Price <span class="text-danger">*</span></label>
                            <div class="col-md-9">
                                 <input type="number"
                                   name="unit_price"
                                   class="form-control"
                                   min="0" step="0.01" 
                                   value="{{ old('unit_price', $product->unit_price ?? '') }}" required>
                                </div>
                        </div>

                        <div class="row mb-3">
                            <label class="col-md-3 col-form-label">Discount <span class="text-danger">*</span></label>
                            <div class="col-md-6">
                                 <input type="number"
                                   name="discount"
                                   class="form-control"
                                   min="0" step="0.01" 
                                   value="{{ old('discount', $product->discount ?? '') }}" >
                            </div>
                            <div class="col-md-3">
                               <select name="discount_type" class="form-select">
                                   <option value="amount" {{ old('discount_type', $product->discount_type ?? '') == 'amount' ? 'selected' : '' }}>Flat</option>
                                   <option value="percent" {{ old('discount_type', $product->discount_type ?? '') == 'percent' ? 'selected' : '' }}>Percent</option>
                               </select>
                           </div>
                        </div>

                        <div class="row mb-3">
                           <label class="col-md-3 col-form-label">SKU</label>
                            <div class="col-md-6">
                                <input type="text" name="sku" class="form-control"
                                value="{{ optional($product->stocks->first())->sku }}">
                            </div>
                        </div>

                        <div class="row mb-3">
                            <label class="col-md-3 col-form-label">External Link</label>
                            <div class="col-md-9">
                                <input type="text" name="external_link" class="form-control">
                                <small class="text-muted">Leave blank if not used</small>
                            </div>
                        </div>
                        
                    </div>


                    <div class="mb-4">
                        <h6 class="mb-3">Product Description</h6>
                        <div class="row mb-3">
                            <label class="col-md-3 col-form-label">Description</label>
                            <div class="col-md-9">
                                <textarea class="form-control" name="description" rows="6">
                                    {{ $product->description }}
                                </textarea>
                            </div>
                        </div>
                    </div>
                    
            </div>

            <div class="col-lg-4">
                <div class="mb-4">
                    <h5 class="mb-3">Shipping Configuration</h5>

                    <div class="mb-3">
                        <label class="col-form-label me-3">Shipping Type:</label>

                        @php
                            $shippingType = old('shipping_type', $product->shipping_type ?? 'free');
                        @endphp

                        <label class="switch">
                            <input type="radio" name="shipping_type" value="free" {{ $shippingType == 'free' ? 'checked' : '' }}>
                            <span class="slider">Free</span>
                        </label>

                        <label class="switch">
                            <input type="radio" name="shipping_type" value="flat_rate" {{ $shippingType == 'flat_rate' ? 'checked' : '' }}>
                            <span class="slider">Flat Rate</span>
                        </label>
                    </div>

                    <div class="mb-3" id="flatShippingDiv" style="{{ $shippingType == 'flat_rate' ? '' : 'display: none;' }}">
                        <label class="col-form-label">Shipping Cost</label>
                         <input type="number"
                                lang="en"
                                min="0"
                                step="0.50"
                                placeholder="Shipping cost"
                                name="shipping_cost"
                                id="shipping_cost"
                                class="form-control"
                                value="{{ old('shipping_cost', $product->shipping_cost ?? 0) }}">
                    </div>
                </div>
            </div>

            <div class="col-12">
            <div class="text-end">
                        <button type="submit" class="btn btn-primary">Update Product</button>
            </div>
          </div>



        </div>   

    </form>
</div>

@endsection

@push('script')
<meta name="csrf-token" content="{{ csrf_token() }}">

<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

<script>
    console.log('SCRIPT LOADED');
document.addEventListener('DOMContentLoaded', function() {

    // ---------- COLOR ENABLE/DISABLE ----------
    const colorsActiveCheckbox = document.getElementById('colors_active');
    const colorsSelect = document.getElementById('colors');

    if (colorsActiveCheckbox && colorsSelect) {
        colorsActiveCheckbox.addEventListener('change', function() {
            if (this.checked) {
                colorsSelect.removeAttribute('disabled');
            } else {
                colorsSelect.setAttribute('disabled', true);
                colorsSelect.value = null;
            }
        });
    }

    // ---------- SHIPPING TYPE ----------
    const shippingRadios = document.querySelectorAll('input[name="shipping_type"]');
    const flatDiv = document.getElementById('flatShippingDiv');

    shippingRadios.forEach(radio => {
        radio.addEventListener('change', function() {
            if (this.value === 'flat_rate') {
                flatDiv.style.display = '';
            } else {
                flatDiv.style.display = 'none';
            }
        });
    });

    // ---------- SKU UPDATE ----------
    const productId = @json($product->id ?? null);
    if (productId) {
        update_sku(productId);
    }

});

// ---------- SKU UPDATE FUNCTION ----------
function update_sku(productId) {
    if (!productId) return;

    $.ajax({
        type: "POST",
        url: "{{ route('admin.products.sku_combination_edit') }}",
        data: {
            _token: $('meta[name="csrf-token"]').attr('content'),
            id: productId
        },
        success: function(res) {
            $('#sku_combination').html(res);
            console.log('UPLOAD RESPONSE:', res);
        },
        error: function(xhr) {
            console.error(xhr.responseText);
        }
    });
}



</script>
@endpush

