@extends('Admin.layout.app')

@section('content')
<div class="aiz-titlebar text-left mt-2 mb-3">
    <div class="card-header">
                <h5>📦 Add New Product</h5>
    </div>

    <div class="">
      <form class="form form-horizontal mar-top" action="{{ route('admin.product.upload') }}" method="POST" id="choice_form" enctype="multipart/form-data">
        <div class="row">
          <div class="col-lg-8">
             @csrf
                    <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" class="form-control" name="name" placeholder="e.g. Cotton Bed Sheet" required>
                                <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 class="form-select" name="category_id" id="category_id" required>
                                    @foreach ($categories as $category)
                                        <option value="{{ $category->id }}">{{ $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 }}">{{ $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" class="form-control" name="unit" placeholder="Unit (e.g. KG, Pc etc)" 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" class="form-control" name="min_qty" value="1" min="1" 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"></div>
                               <input type="hidden" name="photos[]" id="gallery_images_hidden" class="d-none"  multiple>
                               <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>

                                <input type="hidden" name="thumbnail_img" id="thumbnail_image_hidden" class="d-none" accept="image/*">
                                    <div class="mt-2">
                                      <img id="thumbnail_preview_main" class="img-fluid 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">
                            <label class="col-md-3 col-form-label">Color </label>
                            <div class="col-md-8">
                                <select 
                                class="form-control aiz-selectpicker"
                                data-live-search="true"
                                data-selected-text-format="count"
                                name="colors[]" 
                                id="colors" 
                                multiple 
                                disabled>
                                  @foreach (\App\Models\Color::orderBy('name', 'asc')->get() as $color)
                                 <option value="{{ $color->code }}" 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">
                               <label class="custom-checkbox">
                                   <input type="checkbox" name="colors_active" id="colors_active">
                                   <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 aiz-selectpicker"
                                           data-selected-text-format="count"
                                           data-live-search="true"
                                           data-placeholder="Choose Attributes">
                                        @foreach (\App\Models\Attribute::all() as $attribute)
                                           <option value="{{ $attribute->id }}">{{ $attribute->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                    </div>
                    <div class="customer_choice_options" id="customer_choice_options">

                    </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="0" 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="0">
                            </div>
                            <div class="col-md-3">
                                <select name="discount_type" class="form-select">
                                    <option value="amount">Flat</option>
                                    <option value="percent">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">
                            </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"></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>
                       
                           <label class="switch">
                               <input type="radio" name="shipping_type" value="free" checked>
                               <span class="slider">Free</span>
                           </label>
                       
                           <label class="switch">
                               <input type="radio" name="shipping_type" value="flat_rate">
                               <span class="slider">Flat Rate</span>
                           </label>
                       </div>

                 <div class="mb-3" id="flatShippingDiv" style="display: none;">
                     <label class="col-form-label">Shipping Cost</label>
                     <input type="number" lang="en" min="0" value="0" step="0.50" placeholder="Shipping cost" name="flat_shipping_cost" class="form-control">
                 </div>
                </div>
          </div>

           


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

     </form>
    </div>
 </div>   

@endsection


@include('admin.modal.aizUploadModal')


@push('script')

<script>
 document.addEventListener('DOMContentLoaded', function () {
    const checkbox = document.getElementById('colors_active');
    const selectBox = document.getElementById('colors');

    checkbox.addEventListener('change', function () {
        selectBox.disabled = !this.checked;
        if (!this.checked) {
            // clear selection when unchecked
            Array.from(selectBox.options).forEach(option => option.selected = false);
        }
    });
 });
</script>


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

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


<script>
/* =====================================================
   GLOBAL FUNCTION: UPDATE SKU COMBINATION
===================================================== */

  function update_sku() {

    let data = {
        colors: $('#colors').val(),
        choice_no: [],
        _token: $('meta[name="csrf-token"]').attr('content')
    };

    $("input[name='choice_no[]']").each(function () {
        let choiceNo = $(this).val();
        data.choice_no.push(choiceNo);

        let values = $(`select[name="choice_options_${choiceNo}[]"]`).val();
        if (values) {
            data[`choice_options_${choiceNo}`] = values;
        }
    });

    $.ajax({
        type: "POST",
        url: "{{ route('admin.products.sku_combination') }}",
        data: data,
        success: function (res) {
            $('#sku_combination').html(res);
        },
        error: function (xhr) {
            console.error(xhr.responseText);
        }
    });
  }


/* =====================================================
   GLOBAL FUNCTION: LOAD ATTRIBUTE OPTIONS
===================================================== */
function add_more_customer_choice_option(i, name) {

    $.ajax({
        type: "POST",
        url: "{{ route('admin.product.add-more-choice-option') }}",
        data: {
            attribute_id: i,
            _token: $('meta[name="csrf-token"]').attr('content')
        },
        success: function (data) {

            $('#customer_choice_options').append(`
                <div class="form-group row mb-2">
                    <div class="col-md-3">
                        <input type="hidden" name="choice_no[]" value="${i}">
                        <label class="col-form-label">${name}</label>
                    </div>
                    <div class="col-md-8">
                        <select class="form-control aiz-selectpicker attribute_choice"
                                data-live-search="true"
                                multiple
                                name="choice_options_${i}[]">
                            ${data}
                        </select>
                    </div>
                </div>
            `);

            if (typeof AIZ !== 'undefined') {
                AIZ.plugins.bootstrapSelect('refresh');
            }
        }
    });
  }

  $(document).on("change", ".attribute_choice",function() {
        update_sku();
    });

/* =====================================================
   DOCUMENT READY
===================================================== */
   $(document).ready(function () {

    $.ajaxSetup({
        headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
    });

    $('#choice_attributes').on('change', function () {

        $('#customer_choice_options').html('');

        $('#choice_attributes option:selected').each(function () {
            add_more_customer_choice_option($(this).val(), $(this).text());
        });

        update_sku();
    });

    $(document).on('change', '.attribute_choice', function () {
        update_sku();
    });

    $('#colors_active').on('change', function () {
        $('#colors').prop('disabled', !this.checked);
        update_sku();
    });

    $('#colors').on('change', function () {
        update_sku();
    });
   });


</script>


 <script>
        document.addEventListener('DOMContentLoaded', function () {
        
            let currentInputId = null;     // ID of the hidden input
            let currentPreviewId = null;   // ID of the preview container or image
            let isMultiple = false;        // gallery or thumbnail
        
            // OPEN MODAL: set which input & preview we are updating
            document.querySelectorAll('.open-uploader').forEach(btn => {
        btn.addEventListener('click', function () {
            currentInputId = btn.dataset.input;
            currentPreviewId = btn.dataset.preview;
            isMultiple = btn.dataset.multiple === 'true';

            // Remove previous selections
            document.querySelectorAll('.aiz-file-item').forEach(f => f.classList.remove('selected'));
        });
            });
        
            // LOAD FILES WHEN MODAL OPENS
            const modalEl = document.getElementById('aizUploaderModal');
            modalEl.addEventListener('shown.bs.modal', function () {
                loadAizFiles();
            });
        
            // LOAD FILES VIA AJAX
            function loadAizFiles() {
        $.ajax({
            url: "{{ route('admin.all.files') }}",
            type: "GET",
            success: function (files) {
                let html = '';
                if (!files.length) {
                    html = `<div class="text-center w-100">No files found</div>`;
                } else {
                    files.forEach(file => {
                        html += `
                        <div class="col-md-2 col-4">
                            <div class="border p-1 aiz-file-item" data-path="${file.file_url}">
                                <img src="${file.file_url}" class="img-fluid" style="height:100px; object-fit:cover">
                                <div class="text-truncate">${file.file_original_name}</div>
                            </div>
                        </div>
                        `;
                    });
                }
                document.getElementById('aizFileList').innerHTML = html;
            },
            error: function(xhr, status, error) {
                console.error('AJAX ERROR:', status, error);
                console.log(xhr.responseText);
            }
        });
            }
        
            // CLICK FILE TO SELECT / TOGGLE
            document.addEventListener('click', function (e) {
        if (e.target.closest('.aiz-file-item')) {
            const item = e.target.closest('.aiz-file-item');

            if (!isMultiple) {
                // Single selection → remove other selections
                document.querySelectorAll('.aiz-file-item').forEach(f => f.classList.remove('selected'));
            }
             
            item.classList.toggle('selected');
        }
            });
        
            
        
            
        
            // ADD SELECTED FILES TO INPUT & PREVIEW
            $('#addFilesButton').on('click', function() {
            if (!currentInputId || !currentPreviewId) return;

        const inputEl = document.getElementById(currentInputId);
        const previewEl = document.getElementById(currentPreviewId);

        const selectedFiles = $('.aiz-file-item.selected');

         if (selectedFiles.length === 0) return;

          if (isMultiple) {
              // For gallery images
              let existing = inputEl.value ? inputEl.value.split(',') : [];
              selectedFiles.each(function() {
                  const fileUrl = $(this).data('path');
                  existing.push(fileUrl);

                  const div = document.createElement('div');
                  div.className = 'col-md-2 col-4 mb-2';
                  div.innerHTML = `<img src="${fileUrl}" class="img-fluid" style="height:100px;object-fit:cover">`;
                  previewEl.appendChild(div);
              });
              inputEl.value = existing.join(',');
          } else {
              // For single thumbnail
              const fileUrl = selectedFiles.first().data('path');
              previewEl.src = fileUrl;
              previewEl.classList.remove('d-none');
              inputEl.value = fileUrl;
          }

    
  

      const modalInstance = bootstrap.Modal.getOrCreateInstance(modalEl);
            modalInstance.hide();
        
        });
        
        
        document.querySelectorAll('.open-uploader').forEach(btn => {
    btn.addEventListener('click', function () {
        currentInputId = btn.dataset.input;
        currentPreviewId = btn.dataset.preview;
        isMultiple = btn.dataset.multiple === 'true';

        // Clear previous selections
        document.querySelectorAll('.aiz-file-item')
            .forEach(f => f.classList.remove('selected'));

        // ✅ OPEN MODAL THE RIGHT WAY
        const modal = bootstrap.Modal.getOrCreateInstance(
            document.getElementById('aizUploaderModal')
        );
        modal.show();
    });
        });
        
        
        document.querySelectorAll('.open-uploader-sku').forEach(btn => {
    btn.addEventListener('click', function () {
        const inputId = btn.dataset.input;
        const previewId = btn.dataset.preview;

        // Clear previous selection
        document.querySelectorAll('.aiz-file-item').forEach(f => f.classList.remove('selected'));

        // Open the modal
        const modal = bootstrap.Modal.getOrCreateInstance(
            document.getElementById('aizUploaderModal')
        );
        modal.show();

        // Set global variables for modal callback
        window.currentInputId = inputId;
        window.currentPreviewId = previewId;
        window.isMultiple = false; // SKU images are single
    });
        });
        
        $('#addFilesButton').on('click', function () {
    const inputEl = document.getElementById(window.currentInputId);
    const previewEl = document.getElementById(window.currentPreviewId);

    const selectedFiles = $('.aiz-file-item.selected');
    if (!selectedFiles.length) return;

    const fileUrl = selectedFiles.first().data('path');
    previewEl.src = fileUrl;
    previewEl.classList.remove('d-none');
    inputEl.value = fileUrl;

    // Close modal
    const modalInstance = bootstrap.Modal.getOrCreateInstance(modalEl);
    modalInstance.hide();
        });
        
        document.addEventListener('click', function(e){
    const btn = e.target.closest('.open-uploader-sku');
    if(!btn) return;

    const inputId = btn.dataset.input;
    const previewId = btn.dataset.preview;

    document.querySelectorAll('.aiz-file-item').forEach(f => f.classList.remove('selected'));

    const modal = bootstrap.Modal.getOrCreateInstance(
        document.getElementById('aizUploaderModal')
    );
    modal.show();

    window.currentInputId = inputId;
    window.currentPreviewId = previewId;
    window.isMultiple = false;
        });
        
    // UPLOAD NEW FILE
    document.getElementById('aizUploadForm')?.addEventListener('submit', function (e) {
        e.preventDefault();
        let formData = new FormData(this);

        $.ajax({
            url: "{{ route('admin.all.uploads') }}",
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            success: function (res) {
             alert('File uploaded successfully!');
                loadAizFiles();
                document.getElementById('aizUploadForm').reset();
            },
            error: function (xhr) {
                console.error('Upload error:', xhr.responseText);
            }
        });
    });

   });

   function updateSelectedCount() {
      $('.aiz-uploader-selected')
        .text($('.aiz-file-item.selected').length + ' File selected');
   }
</script>


<script>
    const shippingRadios = document.querySelectorAll('input[name="shipping_type"]');
    const flatShippingDiv = document.getElementById('flatShippingDiv');
    
    shippingRadios.forEach(radio => {
        radio.addEventListener('change', function() {
            if (this.value === 'flat_rate') {
                flatShippingDiv.style.display = 'block';
            } else {
                flatShippingDiv.style.display = 'none';
            }
        });
    });
    
    // Initialize on page load in case "Flat Rate" is pre-selected
    document.addEventListener('DOMContentLoaded', () => {
        const checkedRadio = document.querySelector('input[name="shipping_type"]:checked');
        flatShippingDiv.style.display = (checkedRadio.value === 'flat_rate') ? 'block' : 'none';
    });

</script>




@endpush







