@extends('layouts.app')
@section('title', __('Rack Details - Products'))

@section('content')
<!-- Content Header -->
<section class="content-header">
    <h1>@lang('Rack Details for Products')</h1>
</section>

<!-- Main content -->
<section class="content">
  <div class="box box-primary">
    <div class="box-header with-border">
      <h3 class="box-title">@lang('Edit Rack / Row / Position Details')</h3>
    </div>
    <div class="box-body">
      <!-- Search input -->
      <div class="row" style="margin-bottom: 15px;">
        <div class="col-md-4">
          <input type="text" id="search_input" class="form-control" placeholder="@lang('Search by product name or SKU')">
        </div>
      </div>
      <table class="table table-bordered" id="rack_table">
        <thead>
          <tr>
            <th>@lang('Product Image')</th>
            <th>@lang('Product')</th>
            <th>@lang('SKU')</th>
            <th>@lang('Current Stock')</th>
            <th>@lang('Locations')</th>
            <th>@lang('Actions')</th>
          </tr>
        </thead>
        <tbody>
          @foreach($products as $product)
            <tr>
              <!-- Product Image -->
              <td>
                @if(!empty($product->image_url))
                  <img src="{{ $product->image_url }}" alt="{{ $product->name }}" style="max-width:50px;">
                @else
                  --
                @endif
              </td>
              <!-- Product Name -->
              <td>{{ $product->name }}</td>
              <!-- SKU -->
              <td>{{ $product->sku }}</td>
              <!-- Current Stock: Sum over all variations' stock -->
              <td>
                @if($product->enable_stock)
                  @php
                    $totalStock = $product->variations->sum(function($variation) {
                        return $variation->variation_location_details->sum('qty_available');
                    });
                  @endphp
                  {{ $totalStock }}
                @else
                  @lang('messages.no_stock_tracking')
                @endif
              </td>
              <!-- Locations -->
              <td>
                @if($product->rack_details->isNotEmpty())
                  {{ $product->rack_details->pluck('location.name')->implode(', ') }}
                @else
                  @lang('lang_v1.no_location_assigned')
                @endif
              </td>
              <!-- Actions -->
              <td>
                <button type="button" class="btn btn-info btn-sm edit-rack-btn"
                        data-product_id="{{ $product->id }}"
                        data-rack_details='@json($product->rack_details)'>
                  @lang('Edit Locations')
                </button>
              </td>
            </tr>
          @endforeach
        </tbody>
      </table>
    </div>
  </div>

  <!-- Modal for editing rack details -->
  <div class="modal fade" id="rack_edit_modal" tabindex="-1" role="dialog" aria-labelledby="rackEditModalLabel">
    <div class="modal-dialog" role="document">
      <form action="{{ route('products.rack_edit.update') }}" method="POST">
        @csrf
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="rackEditModalLabel">@lang('Edit Rack Details')</h4>
          </div>
          <div class="modal-body">
            <!-- Hidden field for product id -->
            <input type="hidden" name="product_id" id="modal_product_id">
            <div id="rack_edit_container">
              <!-- Dynamically populated form fields for each rack record -->
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">@lang('Close')</button>
            <button type="submit" class="btn btn-primary">@lang('Save Changes')</button>
          </div>
        </div>
      </form>
    </div>
  </div>
</section>
@endsection

@section('javascript')
<script>
// Pass business locations to JavaScript. $business_locations should be an associative array: id => name.
var businessLocations = @json($business_locations);

$(document).ready(function(){
    // Client-side search: filter table rows based on product name or SKU
    $('#search_input').on('keyup', function(){
        var value = $(this).val().toLowerCase();
        $('#rack_table tbody tr').filter(function(){
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
        });
    });

    $('.edit-rack-btn').on('click', function(e){
        e.preventDefault();
        var product_id = $(this).data('product_id');
        var rackDetails = $(this).data('rack_details'); // Array of rack objects
        $('#modal_product_id').val(product_id);
        var container = $('#rack_edit_container');
        container.empty();
        if(rackDetails.length > 0){
            rackDetails.forEach(function(rack, index){
                // Build select options from businessLocations
                var selectOptions = '';
                $.each(businessLocations, function(key, value){
                    var selected = (key == rack.location_id) ? 'selected' : '';
                    selectOptions += '<option value="'+ key +'" '+ selected +'>' + value + '</option>';
                });
                var html = '<div class="rack-entry">' +
                           // Hidden field to track the old location
                           '<input type="hidden" name="rack_entries['+ index +'][old_location_id]" value="'+ rack.location_id +'">' +
                           '<div class="form-group">' +
                               '<label>@lang("business.location"):</label>' +
                               '<select name="rack_entries['+ index +'][location_id]" class="form-control">' +
                                 selectOptions +
                               '</select>' +
                           '</div>' +
                           '<div class="form-group">' +
                               '<label>@lang("lang_v1.rack"):</label>' +
                               '<input type="text" name="rack_entries['+ index +'][rack]" class="form-control" value="'+ (rack.rack ? rack.rack : '') +'">' +
                           '</div>' +
                           '<div class="form-group">' +
                               '<label>@lang("lang_v1.row"):</label>' +
                               '<input type="text" name="rack_entries['+ index +'][row]" class="form-control" value="'+ (rack.row ? rack.row : '') +'">' +
                           '</div>' +
                           '<div class="form-group">' +
                               '<label>@lang("lang_v1.position"):</label>' +
                               '<input type="text" name="rack_entries['+ index +'][position]" class="form-control" value="'+ (rack.position ? rack.position : '') +'">' +
                           '</div>' +
                           '<hr>' +
                           '</div>';
                container.append(html);
            });
        } else {
            container.append('<p>@lang("lang_v1.no_location_assigned")</p>');
        }
        $('#rack_edit_modal').modal('show');
    });
});
</script>
@endsection
