@php
    // Get the first variation if the product has variations.
    // If single product, it's just the "default" variation or no variation needed.
    $first_variation = $product->variations->first();
    // Variation details
    $variation_display_name = '';
    $variation_id = null;
    $default_purchase_price = $product->default_purchase_price;

    if (!empty($first_variation)) {
        $variation_id = $first_variation->id;
        $default_purchase_price = $first_variation->default_purchase_price;

        if ($product->type == 'variable') {
            $variation_display_name = " (<b>{$first_variation->product_variation->name}</b> : {$first_variation->name})";
        }
    }
@endphp

<div class="row">
    <div class="col-sm-12">

        @forelse($locations as $key => $value)
            <!-- Input for the number of entries and submit button outside the table -->
            <div class="form-group">
                <label for="number_of_entries_{{$key}}">Number of Entries:</label>
                <input
                    type="number"
                    id="number_of_entries_{{$key}}"
                    class="form-control"
                    placeholder="Enter number of entries"
                    value="1"
                >
            </div>
            <div class="form-group">
                <button
                    id="submit_entries_{{$key}}"
                    class="btn btn-primary"
                    data-table-id="add_opening_stock_table_{{$key}}"
                >
                    Add Rows
                </button>
            </div>

            <div class="box box-solid">
                <div class="box-header">
                    <h3 class="box-title">
                        @lang('sale.location'): {{$value}}
                    </h3>
                </div>

                <div class="box-body">
                    <div class="row">
                        <div class="col-sm-12">

                            <!-- The table starts with exactly 1 row by default. -->
                            <table
                                id="add_opening_stock_table_{{$key}}"
                                class="table table-condensed table-bordered text-center table-striped add_opening_stock_table"
                            >
                                <thead>
                                    <tr class="bg-green">
                                        <th>@lang('product.product_name')</th>
                                        <th>@lang('lang_v1.quantity_left')</th>
                                        <th>@lang('purchase.unit_cost_before_tax')</th>
                                        @if($enable_expiry == 1 && $product->enable_stock == 1)
                                            <th>Exp. Date</th>
                                        @endif
                                        @if($enable_lot == 1)
                                            <th>@lang('lang_v1.lot_number')</th>
                                        @endif
                                        <th>@lang('purchase.subtotal_before_tax')</th>
                                        <th>@lang('lang_v1.date')</th>
                                        <th>@lang('brand.note')</th>
                                        <th>&nbsp;</th>
                                    </tr>
                                </thead>

                                <tbody>
                                    <!-- ONE default row -->
                                    @php
                                        // We'll call sub_key = 0 for this first row
                                        $sub_key = 0;
                                    @endphp
                                    <tr>
                                        <td>
                                            {{-- Product name + variation name if variable --}}
                                            {{ $product->name }}{!! $variation_display_name !!}
                                        </td>

                                        <td>
                                            <div class="input-group">
                                                {!! Form::text(
                                                    "stocks[$key][$variation_id][$sub_key][quantity]",
                                                    @format_quantity(0),
                                                    [
                                                        'class' => 'form-control input-sm input_number purchase_quantity input_quantity',
                                                        'required',
                                                    ]
                                                ) !!}
                                                <span class="input-group-addon">
                                                    {{ $product->unit->short_name }}
                                                </span>
                                            </div>

                                            @if(!empty($product->second_unit))
                                                <br>
                                                <span>
                                                    @lang('lang_v1.quantity_in_second_unit', ['unit' => $product->second_unit->short_name])*
                                                </span>
                                                <br>
                                                {!! Form::text(
                                                    "stocks[$key][$variation_id][$sub_key][secondary_unit_quantity]",
                                                    @format_quantity(1),
                                                    [
                                                        'class' => 'form-control input-sm input_number input_quantity',
                                                        'required'
                                                    ]
                                                ) !!}
                                            @endif
                                        </td>

                                        <td>
                                            {!! Form::text(
                                                "stocks[$key][$variation_id][$sub_key][purchase_price]",
                                                @num_format($default_purchase_price),
                                                [
                                                    'class' => 'form-control input-sm input_number unit_price',
                                                    'required'
                                                ]
                                            ) !!}
                                        </td>

                                        @if($enable_expiry == 1 && $product->enable_stock == 1)
                                            <td>
                                                {!! Form::text(
                                                    "stocks[$key][$variation_id][$sub_key][exp_date]",
                                                    null,
                                                    [
                                                        'class' => 'form-control input-sm os_exp_date',
                                                        'readonly'
                                                    ]
                                                ) !!}
                                            </td>
                                        @endif

                                        @if($enable_lot == 1)
                                            <td>
                                                {!! Form::text(
                                                    "stocks[$key][$variation_id][$sub_key][lot_number]",
                                                    null,
                                                    [
                                                        'class' => 'form-control input-sm'
                                                    ]
                                                ) !!}
                                            </td>
                                        @endif

                                        <td>
                                            <span class="row_subtotal_before_tax">0.00</span>
                                        </td>

                                        <td>
                                            <div class="input-group date">
                                                {!! Form::text(
                                                    "stocks[$key][$variation_id][$sub_key][transaction_date]",
                                                    null,
                                                    [
                                                        'class' => 'form-control input-sm os_date',
                                                        'readonly'
                                                    ]
                                                ) !!}
                                            </div>
                                        </td>

                                        <td>
                                            {!! Form::textarea(
                                                "stocks[$key][$variation_id][$sub_key][purchase_line_note]",
                                                null,
                                                [
                                                    'class' => 'form-control input-sm',
                                                    'rows' => 3
                                                ]
                                            ) !!}
                                        </td>

                                        <td>
                                            <!-- The plus button for the first row -->
                                            <button
                                                type="button"
                                                class="btn btn-primary btn-xs add_stock_row"
                                                data-sub-key="1"
                                                data-row-html='<tr>
                                                    <td>
                                                        {{ $product->name }}@if($product->type=="variable"){!! " (<b>{$first_variation->product_variation->name}</b> : {$first_variation->name})" !!}@endif
                                                    </td>
                                                    <td>
                                                        <div class="input-group">
                                                            <input class="form-control input-sm input_number purchase_quantity input_quantity"
                                                                   required
                                                                   name="stocks[{{$key}}][{{$variation_id}}][__subkey__][quantity]"
                                                                   type="text"
                                                                   value="1">
                                                            <span class="input-group-addon">
                                                                {{ $product->unit->short_name }}
                                                            </span>
                                                        </div>
                                                        @if(!empty($product->second_unit))
                                                            <br>
                                                            <span>
                                                                @lang("lang_v1.quantity_in_second_unit", ["unit" => $product->second_unit->short_name])*:
                                                            </span>
                                                            <br>
                                                            <input class="form-control input-sm input_number input_quantity"
                                                                   required
                                                                   name="stocks[{{$key}}][{{$variation_id}}][__subkey__][secondary_unit_quantity]"
                                                                   type="text"
                                                                   value="1">
                                                        @endif
                                                    </td>
                                                    <td>
                                                        <input class="form-control input-sm input_number unit_price"
                                                               required
                                                               name="stocks[{{$key}}][{{$variation_id}}][__subkey__][purchase_price]"
                                                               type="text"
                                                               value="{{ @num_format($default_purchase_price) }}">
                                                    </td>
                                                    @if($enable_expiry==1 && $product->enable_stock==1)
                                                        <td>
                                                            <input class="form-control input-sm os_exp_date"
                                                                   required
                                                                   name="stocks[{{$key}}][{{$variation_id}}][__subkey__][exp_date]"
                                                                   type="text"
                                                                   readonly>
                                                        </td>
                                                    @endif
                                                    @if($enable_lot==1)
                                                        <td>
                                                            <input class="form-control input-sm"
                                                                   name="stocks[{{$key}}][{{$variation_id}}][__subkey__][lot_number]"
                                                                   type="text">
                                                        </td>
                                                    @endif
                                                    <td>
                                                        <span class="row_subtotal_before_tax">
                                                            0.00
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div class="input-group date">
                                                            <input class="form-control input-sm os_date"
                                                                   name="stocks[{{$key}}][{{$variation_id}}][__subkey__][transaction_date]"
                                                                   type="text"
                                                                   readonly>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <textarea
                                                            rows="3"
                                                            class="form-control input-sm"
                                                            name="stocks[{{$key}}][{{$variation_id}}][__subkey__][purchase_line_note]"
                                                        ></textarea>
                                                    </td>
                                                    <td>
                                                        <button
                                                            type="button"
                                                            class="btn btn-danger btn-xs remove_purchase_entry_row"
                                                        >
                                                            -
                                                        </button>
                                                    </td>
                                                </tr>'
                                            >
                                                +
                                            </button>

                                            <button
                                                type="button"
                                                class="btn btn-danger btn-xs remove_purchase_entry_row"
                                            >
                                                -
                                            </button>
                                        </td>
                                    </tr>
                                </tbody>

                                <tfoot>
                                    <tr>
                                        <td colspan="5"></td>
                                        <td>
                                            <strong>
                                                @lang('sale.total'):
                                                <span class="location_total">0.00</span>
                                            </strong>
                                        </td>
                                        <td colspan="3"></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

        @empty
        @endforelse
    </div>
</div>

<script type="text/javascript">
$(document).ready(function() {

    // Prevent form submission when Enter key is pressed in any input
    $('form').on('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();  // Prevent form submission
        }
    });

    // Handle the "Add Rows" button click event, dynamically for each table
    $('[id^=submit_entries_]').click(function(e) {
        e.preventDefault(); 
        var button = $(this);
        var tableId = button.data('table-id'); 
        var numberOfEntries = $('#number_of_entries_' + tableId.split('_').pop()).val(); 

        if (numberOfEntries > 0) {
            for (var i = 0; i < numberOfEntries; i++) {
                var firstRow = $('#' + tableId).find('.add_stock_row').first();
                firstRow.trigger('click'); // triggers the "+" button click event to add a new row

                // After adding a new row, find the newly added row
                var newRow = $('#' + tableId + ' tbody tr').last();

                // Copy values from the first row to the new row
                var firstRowTr = $('#' + tableId + ' tbody tr').first();
                firstRowTr.find('input').each(function(index) {
                    var valueToCopy = $(this).val();
                    newRow.find('input').eq(index).val(valueToCopy);
                });
            }
        }
    });

    // Automatically move to the next lot_number field after input in the current field
    $('.add_opening_stock_table').on('input', 'input[name*="[lot_number]"]', function() {
        var $this = $(this);
        if ($this.val().trim() !== "") {
            setTimeout(function() {
                var currentRow = $this.closest('tr');
                var nextRow = currentRow.next();
                var nextLotField = nextRow.find('input[name*="[lot_number]"]');
                if (nextLotField.length > 0) {
                    nextLotField.focus();
                }
            }, 600);
        }
    });
    // Remove row ("-") button logic
    $(document).on('click', '.remove_purchase_entry_row', function(e) {
        e.preventDefault();
        var row = $(this).closest('tr');
        row.remove();
        // Recalculate totals if needed
    });


});
</script>
