@extends('layouts/base_view')
@section('title')
{!! $variables['header_routes'] !!}
@endsection
@section('content')
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="card card-outline card-warning">
                    <div class="card-header">
                        <h3 class="card-title">Stock Opname</h3>
                    </div>
                    <div class="card-body">
                        <form id="formID" method="post" action="{{ route('stock_opnames.store', ['prm_id' => $data->id]) }}">
                            @csrf

                            <!-- Header Section -->
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="card">
                                        <div class="card-header bg-warning">
                                            <h5 class="mb-0">Laporan Stok Malam</h5>
                                        </div>
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-md-3">
                                                    <div class="form-group">
                                                        <label class="font-weight-bold">User</label>
                                                        <div class="mt-1">
                                                            <div>{{ auth()->user()->fullname }}</div>
                                                            @if(auth()->user()->roles->isNotEmpty())
                                                            <small class="text-muted">
                                                                <i class="fas fa-user-tag"></i> 
                                                                {{ auth()->user()->roles->pluck('name')->join(', ') }}
                                                            </small>
                                                            @endif
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="col-md-3">
                                                    <div class="form-group">
                                                        <label class="font-weight-bold">Store</label>
                                                        <div class="mt-1">
                                                            @if(session('store_selected'))
                                                            @php
                                                            $stores = Cache::get('select_stores', []);
                                                            $selectedStore = collect($stores)->firstWhere('id', session('store_selected'));
                                                            @endphp
                                                            <div>{{ $selectedStore ? $selectedStore->name : 'No Store Selected' }}</div>
                                                            @else
                                                            <div class="text-danger">No Store Selected</div>
                                                            @endif
                                                        </div>
                                                        <input type="hidden" name="store_id" id="store_id" value="{{ session('store_selected') }}" required>
                                                    </div>
                                                </div> 
                                                <div class="col-md-3">
                                                    <div class="form-group">
                                                        <label class="font-weight-bold">Status</label>
                                                        <div>
                                                            @if(isset($data->id) && $data->status)
                                                             {{ $data->status }} 
                                                            @else
                                                              Belum Disimpan
                                                            @endif
                                                        </div>
                                                        <!-- <small class="text-muted text-sm">Last Updated Forecast: {{ date('d M Y') }}</small><br>
                                                        <small class="text-muted text-sm">Last Updated Shipment: {{ date('d M Y') }}</small> -->
                                                        <input type="hidden" name="status" id="status_input" value="{{ old('status', $data->status ?? 'Draft') }}">
                                                    </div>
                                                </div>
                                                <div class="col-md-3">
                                                    <div class="form-group">
                                                        <label class="font-weight-bold">LSM Date <span class="text-danger">*</span></label>
                                                        @if(auth()->user()->canBackdateSO())
                                                        <input 
                                                            value="{{ old('so_date', $data->so_date ? $data->so_date->format('Y-m-d') : date('Y-m-d')) }}" 
                                                            type="date" 
                                                            class="form-control form-control-sm" 
                                                            name="so_date" 
                                                            id="so_date"
                                                            max="{{ date('Y-m-d') }}"
                                                            required>
                                                        <small class="text-success text-sm">
                                                            <i class="fas fa-check-circle"></i> Backdate diizinkan
                                                        </small>
                                                        @else
                                                        <input 
                                                            value="{{ old('so_date', $data->so_date ? $data->so_date->format('d F Y') : date('d F Y')) }}" 
                                                            type="text" 
                                                            class="form-control form-control-sm" 
                                                            readonly>
                                                        <small class="text-muted text-sm">Tanggal sistem (tidak bisa backdate) kecuali user tertentu</small>
                                                        <input type="hidden" name="so_date" value="{{ $data->so_date ? $data->so_date->format('Y-m-d') : date('Y-m-d') }}">
                                                        @endif
                                                    </div>
                                                </div>
                                                <div class="col-md-12">
                                                     @if($data->id > 0)
                                                    <div class="alert alert-info alert-dismissible fade show" role="alert">
                                                        <i class="fa fa-info-circle"></i>
                                                        <strong>Autosave Aktif:</strong> Semua field akan otomatis tersimpan saat Anda mengubah nilai. 
                                                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                                            <span aria-hidden="true">&times;</span>
                                                        </button>
                                                        @if($data->status === 'Submitted')
                                                        <div class="mt-2">
                                                            <button type="button" class="btn btn-sm btn-warning" id="updateCurrentStock">
                                                                <i class="fa fa-sync"></i> Update Current Stock
                                                            </button>
                                                        </div>
                                                        @endif
                                                    </div>
                                                    @endif
                                                </div>
                                            </div> 
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- Search Section -->
                            <div class="row">
                                <div class="col-md-6"> 
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group"> 
                                        <div class="input-group">
                                            <input type="text" class="form-control" id="search_item" placeholder="Search Item by Description">
                                            <div class="input-group-append">
                                                <button class="btn btn-sm btn-warning" type="button" id="search_btn">Search</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- Items Section -->
                            <div class="row">
                                <div class="col-12"> 
                                    <div class="table-responsive">
                                        <table class="table table-hover table-sm" id="items-table">
                                            <thead class="bg-warning">
                                                <tr>
                                                    <th width="3%">No</th>
                                                    <th width="10%">Code</th>
                                                    <th>Description</th>
                                                    <th width="7%" class="text-center">UOM Pakai</th>
                                                    <th width="13%" class="text-center">Current Stock</th>
                                                    <th width="7%" class="text-center">Sisa Utuh</th>
                                                    <th width="7%" class="text-center">Sisa Pakai</th>
                                                    <th width="7%" class="text-center">Ending Stock</th>
                                                    <th width="7%" class="text-center">DOI</th>
                                                    <th width="13%" class="text-center">Adjustments</th>
                                                    <th width="2%">History</th>
                                                    <th width="2%">Action</th>
                                                </tr>
                                            </thead>
                                            <tbody id="items-tbody">
                                                @foreach($variables['raw_materials'] as $index => $rm)
                                                @php
                                                $existingDetail = null;
                                                if(isset($data->details)) {
                                                $existingDetail = $data->details->where('raw_material_id', $rm->id)->first();
                                                }

                                                // Get conversion data
                                                $activeConversion = $rm->activeConversion;
                                                $hasConversion = $activeConversion !== null;
                                                $conversionFactor = $hasConversion ? $activeConversion->conversion_factor : 1;
                                                $uomUtuh = $hasConversion ? $activeConversion->uom_utuh : $rm->uom;
                                                $uomPakai = $hasConversion ? $activeConversion->uom_pakai : $rm->uom;
                                                @endphp
                                                <tr data-index="{{ $index }}" class="{{ !$hasConversion ? 'table-warning' : '' }}">
                                                    <td class="text-center">
                                                        {{ $index + 1 }}
                                                        @if(!$hasConversion)
                                                        <br><i class="fa fa-exclamation-triangle text-danger" title="No conversion mapping!"></i>
                                                        @endif
                                                    </td>
                                                    <td>
                                                        <strong>{{ $rm->code }}</strong>
                                                        <input type="hidden" name="items[{{ $index }}][raw_material_id]" value="{{ $rm->id }}">
                                                        @if(!$hasConversion)
                                                        <br><small class="text-danger"><i class="fa fa-warning"></i> Tidak ada mapping</small>
                                                        @endif
                                                    </td>
                                                    <td>
                                                        {{ $rm->name }}
                                                        @if(!$hasConversion)
                                                        <br><small class="text-danger">⚠️ Menggunakan rasio 1:1 (tidak akurat!)</small>
                                                        @endif
                                                    </td>
                                                    <td class="text-center">
                                                        {{ $uomPakai }}
                                                        @if($hasConversion)
                                                        <br><small class="text-muted">1 {{ $uomUtuh }} = {{ $conversionFactor }} {{ $uomPakai }}</small>
                                                        @endif
                                                    </td>
                                                    <td class="text-center">
                                                        <div class="current-stock-display" data-raw-material-id="{{ $rm->id }}">
                                                            <div class="stock-loading" style="display: none;">
                                                                <i class="fa fa-spinner fa-spin"></i>
                                                            </div>
                                                            <div class="stock-info">
                                                                <div class="stock-qty">
                                                                    <span class="stock-utuh">-</span> + <span class="stock-pakai">-</span>
                                                                </div>
                                                                <div class="stock-status">
                                                                    <span class="badge badge-secondary stock-status-badge">Tidak Diketahui</span>
                                                                </div>
                                                                <small class="text-muted text-sm stock-last-updated">Belum Pernah</small>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <input type="number" step="1" min="0" class="form-control form-control-sm qty-utuh text-right autosave-field {{ !$hasConversion ? 'border-danger' : '' }}"
                                                            name="items[{{ $index }}][qty_utuh]"
                                                            data-field-name="qty_utuh"
                                                            data-so-detail-id="{{ $existingDetail ? $existingDetail->id : '' }}"
                                                            data-original-value="{{ $existingDetail ? $existingDetail->qty_utuh : 0 }}"
                                                            data-has-existing-data="{{ $existingDetail ? 'true' : 'false' }}"
                                                            value="{{ $existingDetail ? $existingDetail->qty_utuh : 0 }}"
                                                            data-conversion="{{ $conversionFactor }}"
                                                            data-has-conversion="{{ $hasConversion ? 'true' : 'false' }}"
                                                            data-uom-utuh="{{ $uomUtuh }}"
                                                            data-uom-pakai="{{ $uomPakai }}"
                                                            data-item-code="{{ $rm->code }}"
                                                            data-item-name="{{ $rm->name }}">
                                                    </td>
                                                    <td>
                                                        <input type="number" step="0.01" min="0" max="999999.99" class="form-control form-control-sm qty-pakai text-right autosave-field {{ !$hasConversion ? 'border-danger' : '' }}"
                                                            name="items[{{ $index }}][qty_pakai]"
                                                            data-field-name="qty_pakai"
                                                            data-so-detail-id="{{ $existingDetail ? $existingDetail->id : '' }}"
                                                            data-original-value="{{ $existingDetail ? $existingDetail->qty_pakai : 0 }}"
                                                            data-has-existing-data="{{ $existingDetail ? 'true' : 'false' }}"
                                                            value="{{ $existingDetail ? $existingDetail->qty_pakai : 0 }}">
                                                    </td>
                                                    <td>
                                                        <input type="text" class="form-control form-control-sm form-control-sm ending-stock text-right"
                                                            value="{{ $existingDetail ? number_format($existingDetail->lsm_aktual, 2, '.', '') : '0.00' }}" readonly>
                                                    </td>
                                                    <td>
                                                        <input type="text" class="form-control form-control-sm form-control-sm doi-value text-right"
                                                            value="{{ $existingDetail && $existingDetail->doi ? number_format($existingDetail->doi, 2, '.', '') : '0.00' }}" readonly>
                                                    </td>
                                                    <td>
                                                        @php
                                                            $mapping = $variables['mappings']->get($rm->id);
                                                            $hasInvMatrix = $mapping && $mapping->inv_matrix_flag;
                                                        @endphp
                                                        @if($hasInvMatrix)
                                                        <div class="adjustment-container"> 
                                                            <div class="row no-gutters align-items-center mb-1">
                                                                <div class="col-4">
                                                                    <small>Ekstra</small>
                                                                </div>
                                                                <div class="col-8">
                                                                    <input type="number" step="0.01" class="form-control form-control-sm adjustment-ekstra text-right autosave-field"
                                                                        name="items[{{ $index }}][adj_ekstra]"
                                                                        data-field-name="adj_ekstra"
                                                                        data-so-detail-id="{{ $existingDetail ? $existingDetail->id : '' }}"
                                                                        value="{{ $existingDetail ? $existingDetail->adj_ekstra : 0 }}">
                                                                </div>
                                                            </div>
                                                            <div class="row no-gutters align-items-center mb-1">
                                                                <div class="col-4">
                                                                    <small>Restan</small>
                                                                </div>
                                                                <div class="col-8">
                                                                    <input type="number" step="0.01" class="form-control form-control-sm adjustment-restan text-right autosave-field"
                                                                        name="items[{{ $index }}][adj_restan]"
                                                                        data-field-name="adj_restan"
                                                                        data-so-detail-id="{{ $existingDetail ? $existingDetail->id : '' }}"
                                                                        value="{{ $existingDetail ? $existingDetail->adj_restan : 0 }}">
                                                                </div>
                                                            </div>
                                                            <div class="row no-gutters align-items-center mb-1">
                                                                <div class="col-4">
                                                                    <small>Ringkas</small>
                                                                </div>
                                                                <div class="col-8">
                                                                    <input type="number" step="0.01" class="form-control form-control-sm adjustment-ringkas text-right autosave-field"
                                                                        name="items[{{ $index }}][adj_ringkas]"
                                                                        data-field-name="adj_ringkas"
                                                                        data-so-detail-id="{{ $existingDetail ? $existingDetail->id : '' }}"
                                                                        value="{{ $existingDetail ? $existingDetail->adj_ringkas : 0 }}">
                                                                </div>
                                                            </div>
                                                            <div class="row no-gutters align-items-center">
                                                                <div class="col-4">
                                                                    <small>Selisih</small>
                                                                </div>
                                                                <div class="col-8">
                                                                    <input type="number" step="0.01" class="form-control form-control-sm adjustment-selisih text-right autosave-field"
                                                                        name="items[{{ $index }}][adj_selisih]"
                                                                        data-field-name="adj_selisih"
                                                                        data-so-detail-id="{{ $existingDetail ? $existingDetail->id : '' }}"
                                                                        value="{{ $existingDetail ? $existingDetail->adj_selisih : 0 }}">
                                                                </div>
                                                            </div>
                                                        </div>
                                                        @else
                                                        <div class="text-center text-muted">
                                                            <small>Adjustment not available<br>for this material</small>
                                                            <!-- Hidden inputs with 0 values for form submission -->
                                                            <input type="hidden" name="items[{{ $index }}][adj_ekstra]" value="0">
                                                            <input type="hidden" name="items[{{ $index }}][adj_restan]" value="0">
                                                            <input type="hidden" name="items[{{ $index }}][adj_ringkas]" value="0">
                                                            <input type="hidden" name="items[{{ $index }}][adj_selisih]" value="0">
                                                        </div>
                                                        @endif
                                                    </td>
                                                    <td class="text-center">
                                                        @if($data->id > 0)
                                                        <button type="button" class="btn btn-sm btn-info view-history"
                                                            data-so-detail-id="{{ $existingDetail ? $existingDetail->id : '' }}"
                                                            data-raw-material="{{ $rm->code }} - {{ $rm->name }}"
                                                            title="Lihat Riwayat Perubahan">
                                                            <i class="fa fa-history"></i>
                                                        </button>
                                                        @else
                                                        <span class="text-muted text-sm">-</span>
                                                        @endif
                                                    </td>
                                                    <td class="text-center">
                                                        <button type="button" class="btn btn-sm btn-secondary clear-row"
                                                            data-index="{{ $index }}"
                                                            title="Hapus baris ini">
                                                            <i class="fa fa-eraser"></i>
                                                        </button>
                                                    </td>
                                                </tr>
                                                @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>

                            <!-- Notes -->
                            <div class="row mt-3">
                                <div class="col-12">
                                    <div class="form-group">
                                        <label for="notes">Notes</label>
                                        <textarea class="form-control form-control-sm" name="notes" rows="3">{{ old('notes', $data->notes ?? '') }}</textarea>
                                    </div>
                                </div>
                            </div>

                            <!-- Action Buttons -->
                            <div class="row mt-3">
                                <div class="col-12 text-right">
                                    @if(!isset($data->id) || $data->status == 'Draft')
                                    <button type="button" id="save-draft-btn" class="btn btn-sm btn-info button-cek-permission" data-permission="stock_opnames.store">
                                        <i class="fas fa-save"></i> Simpan Draft 
                                    </button>
                                    <button type="button" id="submit-btn" class="btn btn-sm btn-success button-cek-permission" data-permission="stock_opnames.store">
                                        <i class="fas fa-check"></i> Submit
                                    </button>
                                    @endif
                                    <button type="button" class="btn btn-sm btn-secondary button-cek-permission" data-permission="stock_opnames.clear_inputs" id="clear-btn">
                                        <i class="fas fa-eraser"></i> Clear
                                    </button>
                                    @if(isset($data->id) && $data->id > 0 && $data->status == 'Submitted')
                                    <button type="button" class="btn btn-sm btn-info button-cek-permission" data-permission="stock_opnames.create_spb" id="create-spb-btn">
                                        <i class="fas fa-file-invoice"></i> Create SPB
                                    </button>
                                    @endif
                                    <a href="{{ route('stock_opnames.index') }}" class="btn btn-sm btn-warning">
                                        <i class="fas fa-arrow-left"></i> Kembali
                                    </a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Change History Modal -->
<div class="modal fade" id="changeHistoryModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-info">
                <h5 class="modal-title">
                    <i class="fa fa-history"></i> Change History
                </h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div id="historyLoadingIndicator" class="text-center" style="display: none;">
                    <i class="fa fa-spinner fa-spin fa-2x"></i>
                    <p class="mt-2">Memuat riwayat...</p>
                </div>
                <div id="historyContent">
                    <h6 id="historyItemName" class="mb-3"></h6>
                    <div class="table-responsive">
                        <table id="historyTable" class="table table-hover table-sm">
                            <thead>
                                <tr>
                                    <th width="15%">Date/Time</th>
                                    <th width="15%">Field</th>
                                    <th width="15%">Old Value</th>
                                    <th width="15%">New Value</th> 
                                    <th width="10%">Changed By</th>
                                    <th width="10%">IP Address</th>
                                </tr>
                            </thead>
                            <tbody id="historyTableBody">
                                <!-- Will be populated by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                    <div id="noHistoryMessage" class="alert alert-info" style="display: none;">
                        <i class="fa fa-info-circle"></i> No change history found for this item.
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function() {
        // Check if store is selected on page load
        checkStoreSelection();

        // Show notification if this is a newly auto-created SO
        @if(session('success') && strpos(session('success'), 'Auto-created') !== false)
        Swal.fire({
            title: 'Stock Opname Siap!',
            text: 'Semua bahan baku telah dimuat dengan autosave aktif. Anda dapat mulai input jumlah dan akan tersimpan otomatis.',
            icon: 'success',
            timer: 4000,
            showConfirmButton: false,
            toast: true,
            position: 'top-end'
        });
        @endif

        // Listen for store changes from header
        window.addEventListener('storeChanged', function(event) {
            updateStoreDisplay(event.detail.storeId, event.detail.storeName);
        });

        function checkStoreSelection() {
            const storeId = $('#store_id').val();
            if (!storeId) {
                Swal.fire({
                    title: 'Store Diperlukan',
                    text: 'Silakan pilih store dari menu header sebelum membuat Stock Opname',
                    icon: 'warning',
                    confirmButtonText: 'OK'
                }).then(() => {
                    // Disable form until store is selected
                    $('#formID input, #formID select, #formID button').not('#store_id').prop('disabled', true);
                });
            }
        }

        function updateStoreDisplay(storeId, storeName) {
            $('#store_id').val(storeId);
            $('#selected_store_display').text(storeName);

            // Enable form if store is selected
            if (storeId) {
                $('#formID input, #formID select, #formID button').prop('disabled', false);

                // Reload raw materials for the new store
                if (typeof autoLoadRawMaterials === 'function') {
                    autoLoadRawMaterials();
                }

                // Load current stock for all items
                loadCurrentStockForAllItems();
            }
        }

        // Load current stock for all raw materials
        function loadCurrentStockForAllItems() {
            const storeId = $('#store_id').val();
            if (!storeId) return;

            const rawMaterialIds = [];
            $('[data-raw-material-id]').each(function() {
                const rmId = $(this).data('raw-material-id');
                if (rmId) {
                    rawMaterialIds.push(rmId);
                }
            });

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

            // Show loading indicators
            $('.stock-loading').show();
            $('.stock-info').hide();

            $.ajax({
                url: '{{ route("stock_opnames.get_current_stock") }}',
                type: 'POST',
                data: {
                    _token: '{{ csrf_token() }}',
                    store_id: storeId,
                    raw_material_ids: rawMaterialIds
                },
                success: function(response) {
                    if (response.success) {
                        updateCurrentStockDisplay(response.stocks);
                    } else {
                        console.error('Failed to load current stock:', response.message);
                    }
                },
                error: function(xhr) {
                    console.error('Error loading current stock:', xhr.responseText);
                },
                complete: function() {
                    $('.stock-loading').hide();
                    $('.stock-info').show();
                }
            });
        }

        // Update current stock display
        function updateCurrentStockDisplay(stocks) {
            $.each(stocks, function(rawMaterialId, stockData) {
                const stockDisplay = $(`.current-stock-display[data-raw-material-id="${rawMaterialId}"]`);

                if (stockDisplay.length > 0) {
                    stockDisplay.find('.stock-utuh').text(parseFloat(stockData.qty_utuh).toFixed(0));
                    stockDisplay.find('.stock-pakai').text(parseFloat(stockData.qty_pakai).toFixed(2));

                    const statusBadge = stockDisplay.find('.stock-status-badge');
                    statusBadge.removeClass('badge-secondary badge-success badge-secondary badge-danger badge-info')
                        .addClass(`badge-${stockData.status_color}`)
                        .text(stockData.status);

                    stockDisplay.find('.stock-last-updated').text(`Last: ${stockData.last_updated}`);

                    // Add tooltip with more info
                    stockDisplay.attr('title',
                        `Total: ${parseFloat(stockData.qty_total_converted).toFixed(2)} ${stockData.uom_pakai}\n` +
                        `Status: ${stockData.status}\n` +
                        `Last Updated: ${stockData.last_updated}`
                    );
                }
            });
        }

        // Load current stock when page loads
        $(document).ready(function() {
            setTimeout(function() {
                loadCurrentStockForAllItems();
            }, 1000); // Small delay to ensure everything is loaded

            // Debug: Check autosave fields
            console.log('Autosave fields found:', $('.autosave-field').length);

            // Count fields with missing SO detail ID
            let missingSODetailId = 0;
            $('.autosave-field').each(function(index) {
                const field = $(this);
                const soDetailId = field.data('so-detail-id');
                if (!soDetailId) {
                    missingSODetailId++;
                }
                console.log(`Field ${index + 1}:`, {
                    name: field.attr('name'),
                    fieldName: field.data('field-name'),
                    soDetailId: soDetailId,
                    hasExistingData: field.data('has-existing-data'),
                    originalValue: field.data('original-value'),
                    currentValue: field.val()
                });
            });

            if (missingSODetailId > 0) {
                console.warn(`Found ${missingSODetailId} fields without SO detail ID`);

                // Show warning to user
                Swal.fire({
                    title: 'Masalah Setup Terdeteksi',
                    text: `${missingSODetailId} item tidak memiliki record database. Ini akan mencegah autosave bekerja.`,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Perbaiki Sekarang',
                    cancelButtonText: 'Lanjutkan'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Reload page to trigger auto-create
                        window.location.reload();
                    }
                });
            }
        });

        // Clear row functionality
        $(document).on('click', '.clear-row', function() {
            const index = $(this).data('index');
            const row = $(this).closest('tr');

            Swal.fire({
                title: 'Hapus Baris?',
                text: 'Ini akan mereset semua nilai di baris ini menjadi nol. Anda yakin?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Ya, Hapus',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Clear all input fields in this row
                    row.find('input[type="number"]').not('[readonly]').each(function() {
                        const field = $(this);
                        const originalValue = field.val();
                        field.val(0);

                        // Trigger change event to save via autosave
                        if (field.hasClass('autosave-field')) {
                            field.trigger('change');
                        }
                    });

                    // Clear calculated fields
                    row.find('.ending-stock').text('0.00');
                    row.find('.doi-value').text('0.00');

                    Swal.fire({
                        title: 'Berhasil!',
                        text: 'Baris telah dihapus dan disimpan.',
                        icon: 'success',
                        timer: 2000,
                        showConfirmButton: false
                    });
                }
            });
        });


        // Update Current Stock button
        $(document).on('click', '#updateCurrentStock', function() {
            const soId = {{ $data->id ?? 0 }};

            Swal.fire({
                title: 'Update Current Stock?',
                text: 'Ini akan mengupdate level stok saat ini berdasarkan data Stock Opname yang sudah disubmit.',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Ya, Update',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    $(this).prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Updating...');

                    $.post('/stock_opnames/update_current_stock', {
                            _token: '{{ csrf_token() }}',
                            so_id: soId
                        })
                        .done(function(response) {
                            if (response.success) {
                                Swal.fire({
                                    title: 'Berhasil!',
                                    text: response.message,
                                    icon: 'success',
                                    confirmButtonText: 'OK'
                                }).then(() => {
                                    // Reload current stock display
                                    loadCurrentStockForAllItems();
                                });
                            } else {
                                Swal.fire({
                                    title: 'Gagal',
                                    text: response.message,
                                    icon: 'error',
                                    confirmButtonText: 'OK'
                                });
                            }
                        })
                        .fail(function(xhr) {
                            Swal.fire({
                                title: 'Error',
                                text: 'Gagal mengupdate current stock: ' + (xhr.responseJSON?.message || xhr.statusText),
                                icon: 'error',
                                confirmButtonText: 'OK'
                            });
                        })
                        .always(function() {
                            $('#updateCurrentStock').prop('disabled', false).html('<i class="fa fa-sync"></i> Update Current Stock');
                        });
                }
            });
        });

        // Autosave functionality
        let saveTimeout;

        $(document).on('change', '.autosave-field', function() {
            const field = $(this);
            const value = field.val();
            const soDetailId = field.data('so-detail-id');
            const fieldName = field.data('field-name');
            const hasExistingData = field.data('has-existing-data') === 'true';
            const originalValue = field.data('original-value');

            // Get current row to extract qty_utuh and qty_pakai
            const row = field.closest('tr');
            const qtyUtuh = row.find('.qty-utuh').val() || 0;
            const qtyPakai = row.find('.qty-pakai').val() || 0;

            // Debug logging
            console.log('Autosave triggered for:', {
                fieldName: fieldName,
                value: value,
                soDetailId: soDetailId,
                hasExistingData: hasExistingData,
                originalValue: originalValue,
                valueChanged: value != originalValue,
                qtyUtuh: qtyUtuh,
                qtyPakai: qtyPakai
            });

            // Skip if no SO detail ID (new record)
            if (!soDetailId) {
                console.log('Autosave skipped: No SO detail ID');
                return;
            }

            // Skip if value hasn't changed
            if (value == originalValue) {
                console.log('Autosave skipped: Value unchanged');
                return;
            }

            console.log('Proceeding with autosave...');

            // Show confirmation for existing data
            if (hasExistingData && value != originalValue) {
                showEditConfirmation(field, value, soDetailId, fieldName, qtyUtuh, qtyPakai);
            } else {
                autoSaveField(soDetailId, fieldName, value, qtyUtuh, qtyPakai);
            }
        });

        function showEditConfirmation(field, newValue, soDetailId, fieldName, qtyUtuh, qtyPakai) {
            Swal.fire({
                title: 'Konfirmasi Edit',
                text: 'Anda akan mengubah data yang sudah ada. Perubahan ini akan dicatat untuk keperluan audit.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Ya, Update',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    autoSaveField(soDetailId, fieldName, newValue, qtyUtuh, qtyPakai);
                    field.data('original-value', newValue); // Update original value
                } else {
                    field.val(field.data('original-value')); // Revert
                }
            });
        }

        function autoSaveField(soDetailId, fieldName, value, qtyUtuh = null, qtyPakai = null) {
            // Show saving indicator
            showSavingIndicator();

            $.ajax({
                url: '{{ route("stock_opnames.auto_save_field") }}',
                type: 'POST',
                data: {
                    _token: '{{ csrf_token() }}',
                    so_detail_id: soDetailId,
                    field_name: fieldName,
                    value: value,
                    qty_utuh: qtyUtuh,
                    qty_pakai: qtyPakai
                },
                success: function(response) {
                    if (response.success) {
                        updateCalculatedFields(soDetailId, response.data);
                        showSaveSuccess();
                    } else {
                        showSaveError(response.message);
                    }
                },
                error: function(xhr) {
                    const message = xhr.responseJSON?.message || 'Error saving field';
                    showSaveError(message);
                }
            });
        }

        function updateCalculatedFields(soDetailId, data) {
            // Find the specific row by SO detail ID
            const row = $(`.autosave-field[data-so-detail-id="${soDetailId}"]`).first().closest('tr');

            if (row.length > 0) {
                // Update calculated fields in the specific row only
                // Use lsm_aktual for ending stock
                row.find('.ending-stock').val((data.lsm_aktual || 0).toFixed(2));
                row.find('.doi-value').val((data.doi || 0).toFixed(2));

                console.log('Updated calculated fields for row:', soDetailId, {
                    lsm_aktual: data.lsm_aktual,
                    doi: data.doi
                });
            } else {
                console.warn('Could not find row for SO detail ID:', soDetailId);
            }
        }

        function showSavingIndicator() {
            // Show saving spinner
            if (!$('.save-indicator').length) {
                $('body').append('<div class="save-indicator"><i class="fa fa-spinner fa-spin"></i> Saving...</div>');
            }
        }

        function showSaveSuccess() {
            $('.save-indicator').remove();
            // Show brief success indicator
            if (!$('.save-success').length) {
                $('body').append('<div class="save-success"><i class="fa fa-check text-success"></i> Saved</div>');
                setTimeout(() => $('.save-success').fadeOut(), 2000);
            }
        }

        function showSaveError(message) {
            $('.save-indicator').remove();
            Swal.fire({
                icon: 'error',
                title: 'Save Error',
                text: message,
                timer: 3000
            });
        }

        // Input validation for Qty Utuh (Integer only, no decimal)
        $('.qty-utuh').on('input', function() {
            let value = $(this).val();
            
            // Remove any non-digit characters (including decimal point)
            value = value.replace(/[^0-9]/g, '');
            
            // Limit to 4 digits (max 9999)
            if (value.length > 4) {
                value = value.substring(0, 4);
            }
            
            $(this).val(value);
        });

        // Input validation for Qty Pakai (Decimal with max 2 decimal places)
        $('.qty-pakai').on('input', function() {
            let value = $(this).val();
            
            // Allow only numbers, dot, and comma
            value = value.replace(/[^0-9.,]/g, '');
            
            // Convert comma to dot
            value = value.replace(',', '.');
            
            // Split by decimal point
            const parts = value.split('.');
            
            // Limit integer part to 6 digits
            if (parts[0].length > 6) {
                parts[0] = parts[0].substring(0, 6);
            }
            
            // Limit decimal part to 2 digits
            if (parts.length > 1) {
                parts[1] = parts[1].substring(0, 2);
                value = parts[0] + '.' + parts[1];
            } else {
                value = parts[0];
            }
            
            // Prevent multiple decimal points
            const dotCount = (value.match(/\./g) || []).length;
            if (dotCount > 1) {
                value = value.substring(0, value.lastIndexOf('.'));
            }
            
            $(this).val(value);
        });

        // Input validation for Adjustment fields (Decimal with max 2 decimal places)
        $('.adjustment-ekstra, .adjustment-restan, .adjustment-ringkas, .adjustment-selisih').on('input', function() {
            let value = $(this).val();
            
            // Allow only numbers, dot, comma, and minus sign
            value = value.replace(/[^0-9.,-]/g, '');
            
            // Convert comma to dot
            value = value.replace(',', '.');
            
            // Handle negative sign - only at the beginning
            const isNegative = value.startsWith('-');
            value = value.replace(/-/g, '');
            if (isNegative) {
                value = '-' + value;
            }
            
            // Split by decimal point
            const parts = value.replace('-', '').split('.');
            
            // Limit integer part to 6 digits
            if (parts[0].length > 6) {
                parts[0] = parts[0].substring(0, 6);
            }
            
            // Limit decimal part to 2 digits
            if (parts.length > 1) {
                parts[1] = parts[1].substring(0, 2);
                value = (isNegative ? '-' : '') + parts[0] + '.' + parts[1];
            } else {
                value = (isNegative ? '-' : '') + parts[0];
            }
            
            // Prevent multiple decimal points
            const dotCount = (value.match(/\./g) || []).length;
            if (dotCount > 1) {
                value = value.substring(0, value.lastIndexOf('.'));
            }
            
            $(this).val(value);
        });

        // Format existing values on page load (handle database numeric values)
        $('.qty-utuh').each(function() {
            let value = $(this).val();
            if (value) {
                // Convert to integer (remove any decimal from database)
                let intValue = parseInt(parseFloat(value));
                if (!isNaN(intValue)) {
                    $(this).val(intValue);
                }
            }
        });

        $('.qty-pakai').each(function() {
            let value = $(this).val();
            if (value) {
                // Format to 2 decimal places
                let floatValue = parseFloat(value);
                if (!isNaN(floatValue)) {
                    $(this).val(floatValue.toFixed(2));
                }
            }
        });

        // Format adjustment fields to 2 decimal places
        $('.adjustment-ekstra, .adjustment-restan, .adjustment-ringkas, .adjustment-selisih').each(function() {
            let value = $(this).val();
            if (value) {
                // Format to 2 decimal places
                let floatValue = parseFloat(value);
                if (!isNaN(floatValue)) {
                    $(this).val(floatValue.toFixed(2));
                }
            }
        });

        // Calculate ending stock when qty changes
        $(document).on('input', '.qty-utuh, .qty-pakai', function() {
            const row = $(this).closest('tr');
            const qtyUtuh = parseFloat(row.find('.qty-utuh').val()) || 0;
            const qtyPakai = parseFloat(row.find('.qty-pakai').val()) || 0;
            const conversion = parseFloat(row.find('.qty-utuh').data('conversion')) || 1;

            const qtyConverted = qtyUtuh * conversion;
            const endingStock = qtyConverted + qtyPakai;

            row.find('.ending-stock').val(endingStock.toFixed(2));

            // DOI will be calculated by backend after autosave
            // Don't calculate here to avoid random values
        });

        // Search functionality - filter table rows
        $('#search_btn').click(function() {
            const searchTerm = $('#search_item').val().toLowerCase();
            if (searchTerm) {
                $('#items-tbody tr').each(function() {
                    const itemDescription = $(this).find('td:nth-child(3)').text().toLowerCase();
                    const itemCode = $(this).find('td:nth-child(2)').text().toLowerCase();

                    if (itemDescription.includes(searchTerm) || itemCode.includes(searchTerm)) {
                        $(this).show();
                        // Focus on the first input in this row
                        $(this).find('.qty-utuh').focus();
                    } else {
                        $(this).hide();
                    }
                });
            } else {
                // Show all rows if search is empty
                $('#items-tbody tr').show();
            }
        });

        // Enter key search
        $('#search_item').keypress(function(e) {
            if (e.which == 13) {
                $('#search_btn').click();
            }
        });

        // Clear search - show all rows
        $('#search_item').on('input', function() {
            if ($(this).val() === '') {
                $('#items-tbody tr').show();
            }
        });

        // View History button functionality
        $(document).on('click', '.view-history', function() {
            const soDetailId = $(this).data('so-detail-id');
            const rawMaterial = $(this).data('raw-material');

            if (!soDetailId) {
                Swal.fire({
                    title: 'No History',
                    text: 'This item has not been saved yet.',
                    icon: 'info'
                });
                return;
            }

            // Set item name in modal
            $('#historyItemName').text('Item: ' + rawMaterial);

            // Show modal
            $('#changeHistoryModal').modal('show');

            // Show loading
            $('#historyLoadingIndicator').show();
            $('#historyContent').hide();

            // Fetch history
            $.ajax({
                url: '{{ route("stock_opnames.get_change_history") }}',
                type: 'GET',
                data: {
                    so_detail_id: soDetailId
                },
                success: function(response) {
                    $('#historyLoadingIndicator').hide();
                    $('#historyContent').show();

                    if (response.success && response.change_logs.length > 0) {
                        $('#historyTable').show();
                        $('#noHistoryMessage').hide();

                        // Populate table
                        let tbody = $('#historyTableBody');
                        tbody.empty();

                        response.change_logs.forEach(function(log) {
                            // Format numeric values to 2 decimal places for qty fields
                            let oldValue = log.old_value;
                            let newValue = log.new_value;
                            
                            // Check if field is a quantity field that needs formatting
                            const qtyFields = ['qty_utuh', 'qty_pakai', 'adj_ekstra', 'adj_restan', 'adj_ringkas', 'adj_selisih'];
                            if (qtyFields.includes(log.field_name)) {
                                // Format to 2 decimal places if it's a number
                                if (!isNaN(parseFloat(oldValue))) {
                                    oldValue = parseFloat(oldValue).toFixed(2);
                                }
                                if (!isNaN(parseFloat(newValue))) {
                                    newValue = parseFloat(newValue).toFixed(2);
                                }
                            }
                            
                            let row = `
                                <tr>
                                    <td>${log.changed_at}</td>
                                    <td><strong>${log.field_name}</strong></td>
                                    <td>${oldValue}</td>
                                    <td>${newValue}</td> 
                                    <td>${log.changed_by}</td>
                                    <td>${log.ip_address || '-'}</td>
                                </tr>
                            `;
                            tbody.append(row);
                        });
                    } else {
                        $('#historyTable').hide();
                        $('#noHistoryMessage').show();
                    }
                },
                error: function(xhr) {
                    $('#historyLoadingIndicator').hide();
                    $('#historyContent').show();

                    Swal.fire({
                        title: 'Error',
                        text: 'Gagal memuat riwayat perubahan: ' + (xhr.responseJSON?.message || 'Error tidak diketahui'),
                        icon: 'error'
                    });
                }
            });
        });

        // Clear button functionality
        $('#clear-btn').click(function() {
            Swal.fire({
                title: 'Hapus Semua Input',
                text: 'Anda yakin ingin menghapus semua data input? Ini tidak akan mempengaruhi log perubahan.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Ya, Hapus Semua',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    $('.qty-utuh, .qty-pakai').val('0');
                    $('.ending-stock, .doi-value').val('0.00');
                    $('.adjustment-ekstra, .adjustment-restan, .adjustment-ringkas, .adjustment-selisih').val('0');
                    $('#search_item').val('');
                    $('#items-tbody tr').show(); // Show all rows after clear

                    Swal.fire('Berhasil!', 'Semua input telah dihapus.', 'success');
                }
            });
        });

        // Save Only button (without creating SPB)
        $('#save-only-btn').click(function() {
            $.ajax({
                url: '{{ route("stock_opnames.save_only") }}',
                type: 'POST',
                data: {
                    _token: '{{ csrf_token() }}',
                    so_id: '{{ $data->id ?? 0 }}'
                },
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Berhasil Disimpan',
                            text: response.warning || response.message,
                            confirmButtonText: 'OK'
                        });
                    } else {
                        Swal.fire('Error', response.message, 'error');
                    }
                }
            });
        });

        // Create SPB button
        $('#create-spb-btn').click(function() {
            Swal.fire({
                title: 'Buat SPB',
                text: 'Data yang sudah disubmit tidak dapat diedit. Lanjutkan?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Ya, Buat SPB',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '{{ route("stock_opnames.create_spb") }}',
                        type: 'POST',
                        data: {
                            _token: '{{ csrf_token() }}',
                            so_id: '{{ $data->id ?? 0 }}',
                            spb_type: 'Regular'
                        },
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Success',
                                    text: response.message,
                                    confirmButtonText: 'Go to SPB'
                                }).then(() => {
                                    window.location.href = response.redirect_url;
                                });
                            } else {
                                Swal.fire('Error', response.message, 'error');
                            }
                        }
                    });
                }
            });
        });

        // Form validation and submission
        var isSubmitting = false;

        // Check if jQuery validate is available
        if (typeof $.fn.validate === 'undefined') {
            console.error('jQuery Validate plugin is not loaded!');
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'jQuery Validate plugin tidak ter-load. Silakan refresh halaman.',
                confirmButtonText: 'Refresh'
            }).then(() => {
                window.location.reload();
            });
            return;
        }

        // Save Draft button click handler
        $('#save-draft-btn').on('click', function(e) {
            e.preventDefault();
            console.log('Save Draft button clicked');
            $('#status_input').val('Draft');
            $('#formID').submit();
        });

        // Submit button click handler
        $('#submit-btn').on('click', function(e) {
            e.preventDefault();
            console.log('Submit button clicked');
            
            // Konfirmasi sebelum submit
            Swal.fire({
                title: 'Submit Stock Opname?',
                text: 'Data yang sudah disubmit tidak dapat diubah lagi. Pastikan semua data sudah benar.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Ya, Submit',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    $('#status_input').val('Submitted');
                    $('#formID').submit();
                }
            });
        });

        $('#formID').validate({
            rules: {
                store_id: {
                    required: true
                },
                status: {
                    required: true
                }
            },
            submitHandler: function(form) {
                if (isSubmitting) return false;

                // ========================================
                // Check for items without conversion mapping
                // ========================================
                let itemsWithoutConversion = [];

                $('.qty-utuh').each(function() {
                    const hasConversionAttr = $(this).data('has-conversion');
                    const hasConversion = hasConversionAttr === 'true' || hasConversionAttr === true;
                    const qtyUtuh = parseFloat($(this).val()) || 0;
                    const itemCode = $(this).data('item-code');
                    const itemName = $(this).data('item-name');

                    // Debug log
                    if (qtyUtuh > 0) {
                        console.log(`Item ${itemCode}:`, {
                            hasConversionAttr: hasConversionAttr,
                            hasConversionAttrType: typeof hasConversionAttr,
                            hasConversion: hasConversion,
                            qtyUtuh: qtyUtuh
                        });
                    }

                    // Debug log
                    if (qtyUtuh > 0) {
                        console.log(`Item ${itemCode}:`, {
                            hasConversionAttr: hasConversionAttr,
                            hasConversionAttrType: typeof hasConversionAttr,
                            hasConversion: hasConversion,
                            qtyUtuh: qtyUtuh
                        });
                    }

                    if (!hasConversion && qtyUtuh > 0) {
                        itemsWithoutConversion.push({
                            code: itemCode,
                            name: itemName,
                            qty: qtyUtuh
                        });
                    }
                });

                if (itemsWithoutConversion.length > 0) {
                    let itemsList = itemsWithoutConversion.map(item =>
                        `<li><strong>${item.code}</strong> - ${item.name} (Qty Utuh: ${item.qty})</li>`
                    ).join('');

                    Swal.fire({
                        icon: 'error',
                        title: 'Konversi Mapping Diperlukan!',
                        html: `
                            <div class="text-left">
                                <p class="text-danger"><strong>⚠️ Tidak dapat submit Stock Opname!</strong></p>
                                <p>Item berikut tidak memiliki konversi mapping:</p>
                                <ul class="text-left" style="max-height: 200px; overflow-y: auto;">
                                    ${itemsList}
                                </ul>
                                <hr>
                                <p class="text-danger mt-3">
                                    <strong>Mengapa ini penting?</strong><br>
                                    Tanpa konversi mapping, sistem akan menggunakan rasio 1:1 yang <strong>SALAH</strong>!<br>
                                    Ini akan menyebabkan perhitungan yang salah untuk:
                                </p>
                                <ul class="text-left">
                                    <li>Ending Stock</li>
                                    <li>DOI (Days of Inventory)</li>
                                    <li>SPB (Surat Permintaan Item)</li>
                                    <li>Laporan</li>
                                </ul>
                                <p class="text-primary mt-3">
                                    <strong>Apa yang harus dilakukan?</strong><br>
                                    Silakan mapping konversi terlebih dahulu di <strong>Master → Items → Item Conversions</strong>
                                </p>
                            </div>
                        `,
                        width: '600px',
                        confirmButtonText: '<i class="fa fa-external-link-alt"></i> Ke Item Conversions',
                        confirmButtonColor: '#007bff',
                        showCancelButton: true,
                        cancelButtonText: 'Batal',
                        cancelButtonColor: '#6c757d'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.open('{{ route("item_conversions.index") }}', '_blank');
                        }
                    });

                    return false;
                }

                // ========================================
                // Proceed with form submission
                // ========================================
                isSubmitting = true;
                $('#loaderkdnknz').show();

                var formData = new FormData(form);

                $.ajax({
                        type: "POST",
                        url: $(form).attr('action'),
                        data: formData,
                        processData: false,
                        contentType: false,
                        dataType: "json",
                    })
                    .done(function(data) {
                        Swal.fire({
                            icon: data[0],
                            text: data[1],
                            showCancelButton: false,
                            confirmButtonColor: '#6c757d',
                            confirmButtonText: 'OK',
                            allowOutsideClick: false
                        }).then((result) => {
                            if (result.isConfirmed && data[0] == 'success') {
                                if ("{{$data->id}}" > 0) {
                                    window.location.href = "{{ route('stock_opnames.show', $data->id) }}";
                                } else {
                                    window.location.href = "{{ route('stock_opnames.index') }}";
                                }
                            }
                        });
                    })
                    .fail(function(xhr) {
                        let errorText = "Silakan hubungi tim terkait atau coba lagi.";

                        if (xhr.status === 422 && xhr.responseJSON.errors) {
                            const errors = xhr.responseJSON.errors;
                            errorText = '';

                            for (const key in errors) {
                                if (errors.hasOwnProperty(key)) {
                                    errorText += `<strong>${key}</strong> : ${errors[key].join(', ')}<br>`;
                                }
                            }
                        } else if (xhr.responseJSON && xhr.responseJSON.message) {
                            errorText = xhr.responseJSON.message;
                        }

                        Swal.fire({
                            icon: "error",
                            title: "Validasi Gagal",
                            html: errorText,
                            confirmButtonColor: '#6c757d',
                            confirmButtonText: 'OK'
                        });
                    })
                    .always(function() {
                        isSubmitting = false;
                        $('#loaderkdnknz').hide();
                    });
            }
        });

        // Initial calculation for existing items
        $('.qty-utuh').trigger('input');

        // ========================================
        // SO Locking: Unlock on navigate away
        // ========================================
        @if(isset($data->id) && $data->id > 0)
        let isFormSubmitted = false;
        let heartbeatInterval = null;
        
        // Start heartbeat - send ping every 2 minutes (120 seconds)
        function startHeartbeat() {
            console.log('Starting heartbeat for SO ID: {{ $data->id }}');
            
            // Send initial heartbeat
            sendHeartbeat();
            
            // Set interval to send heartbeat every 2 minutes
            heartbeatInterval = setInterval(function() {
                sendHeartbeat();
            }, 120000); // 120000ms = 2 minutes
        }
        
        function sendHeartbeat() {
            $.ajax({
                url: '{{ route("stock_opnames.heartbeat") }}',
                type: 'POST',
                data: {
                    _token: '{{ csrf_token() }}',
                    so_id: {{ $data->id }}
                },
                success: function(response) {
                    if (response.success) {
                        console.log('Heartbeat sent successfully at:', response.timestamp);
                    } else {
                        console.warn('Heartbeat failed:', response.message);
                        // Stop heartbeat if not authorized
                        stopHeartbeat();
                    }
                },
                error: function(xhr) {
                    console.error('Heartbeat error:', xhr.responseJSON?.message || xhr.statusText);
                }
            });
        }
        
        function stopHeartbeat() {
            if (heartbeatInterval) {
                clearInterval(heartbeatInterval);
                heartbeatInterval = null;
                console.log('Heartbeat stopped');
            }
        }
        
        // Start heartbeat when page loads
        startHeartbeat();
        
        // Mark form as submitted when save/submit buttons are clicked
        $('#save-draft-btn, #submit-btn').on('click', function() {
            isFormSubmitted = true;
            stopHeartbeat(); // Stop heartbeat when saving
        });

        // Unlock SO when user navigates away (without saving)
        window.addEventListener('beforeunload', function(e) {
            if (!isFormSubmitted) {
                stopHeartbeat(); // Stop heartbeat
                
                // Use synchronous AJAX to ensure it completes before page unload
                $.ajax({
                    url: '{{ route("stock_opnames.unlock") }}',
                    type: 'POST',
                    async: false, // Synchronous to ensure completion
                    data: {
                        _token: '{{ csrf_token() }}',
                        so_id: {{ $data->id }}
                    }
                });
            }
        });

        // Also unlock when clicking "Kembali" button
        $('a[href="{{ route('stock_opnames.index') }}"]').on('click', function(e) {
            if (!isFormSubmitted) {
                e.preventDefault();
                const href = $(this).attr('href');
                
                stopHeartbeat(); // Stop heartbeat
                
                // Unlock SO
                $.ajax({
                    url: '{{ route("stock_opnames.unlock") }}',
                    type: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}',
                        so_id: {{ $data->id }}
                    },
                    success: function() {
                        window.location.href = href;
                    },
                    error: function() {
                        // Navigate anyway even if unlock fails
                        window.location.href = href;
                    }
                });
            }
        });
        @endif
    });
</script>

<style>
    /* Warning styles for items without conversion */
    .table-warning {
        background-color: #fff3cd !important;
    }

    .border-danger {
        border-color: #dc3545 !important;
        border-width: 2px !important;
    }

    .table-warning td {
        background-color: #fff3cd !important;
    }

    .table-warning:hover td {
        background-color: #ffe69c !important;
    }

    .save-indicator,
    .save-success {
        position: fixed;
        top: 20px;
        right: 20px;
        background: rgba(0, 0, 0, 0.8);
        color: white;
        padding: 10px 15px;
        border-radius: 5px;
        z-index: 9999;
        font-size: 14px;
    }

    .save-success {
        background: rgba(40, 167, 69, 0.9);
    }

    .autosave-field:focus {
        border-color: #007bff;
        box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
    }

    /* Store Display Styles */
    .form-control-plaintext {
        background-color: #f8f9fa !important;
        border: 1px solid #ced4da !important;
        color: #495057 !important;
    }

    #selected_store_display {
        color: #007bff !important;
        font-weight: 600 !important;
    }

    /* Current Stock Display Styles */
    .current-stock-display {
        text-align: center;
        font-size: 0.8rem;
    }

    .stock-qty {
        font-weight: 600;
        margin-bottom: 2px;
    }

    .stock-utuh {
        color: #007bff;
    }

    .stock-pakai {
        color: #28a745;
    }

    .stock-status {
        margin-bottom: 2px;
    }

    .stock-status-badge {
        font-size: 0.65rem;
        padding: 2px 6px;
    }

    .stock-last-updated {
        font-size: 0.65rem;
        display: block;
    }

    .stock-loading {
        padding: 10px;
        color: #6c757d;
    }

    /* Change History Modal Styles */
    #changeHistoryModal .modal-dialog {
        max-width: 90%;
    }

    #historyTable {
        font-size: 0.875rem;
    }

    #historyTable th {
        background-color: #f8f9fa;
        border-top: none;
        font-weight: 600;
        font-size: 0.9rem;
        padding: 0.75rem 0.5rem;
    }

    #historyTable td {
        vertical-align: middle;
        padding: 0.5rem;
    }

    .view-history {
        transition: all 0.2s ease;
    }

    .view-history:hover {
        transform: scale(1.1);
    }

    .clear-row {
        transition: all 0.2s ease;
    }

    .clear-row:hover {
        transform: scale(1.1);
        background-color: #dc3545 !important;
        border-color: #dc3545 !important;
    }

    .badge {
        font-size: 0.75em;
    }

    /* Change type indicators */
    .text-success .fa-arrow-up {
        color: #28a745;
    }

    .text-danger .fa-arrow-down {
        color: #dc3545;
    }

    .text-info .fa-edit {
        color: #17a2b8;
    }

    /* Loading indicator */
    #historyLoadingIndicator {
        padding: 2rem;
    }

    /* Responsive adjustments */
    @media (max-width: 768px) {
        #changeHistoryModal .modal-dialog {
            max-width: 95%;
            margin: 1rem;
        }

        #historyTable {
            font-size: 0.75rem;
        }

        #historyTable th,
        #historyTable td {
            padding: 0.25rem;
        }

        .current-stock-display {
            font-size: 0.7rem;
        }

        .stock-status-badge {
            font-size: 0.6rem;
            padding: 1px 4px;
        }
    }

    /* Adjustment container styling */
    .adjustment-container {
        padding: 0.25rem;
    }

    .adjustment-container .row {
        margin-left: 0;
        margin-right: 0;
    }

    .adjustment-container .col-4,
    .adjustment-container .col-8 {
        padding-left: 0.25rem;
        padding-right: 0.25rem;
    }

    .adjustment-container small {
        line-height: 1.8;
        display: inline-block;
        vertical-align: middle;
    }

    .adjustment-container .form-control-sm {
        height: calc(1.5em + 0.5rem + 2px);
    }

</style>

@endsection