@extends('base.layout')

@section('content')
<div class="wrapper">
	<div class="container-fluid">
		<div class="row">
			<div class="col-sm-12">
				<div class="page-title-box">
					<div class="btn-group pull-right">
						<ol class="breadcrumb hide-phone p-0 m-0">
							<li class="breadcrumb-item active">SIM Barang Habis Pakai</li>
						</ol>
					</div>
					<h4 class="page-title">SIMBHP</h4>
				</div>
			</div>
		</div>
		<div class="row">
			<div class="col-sm-12">
				<div class="card-box">
					<ul class="nav nav-tabs m-b-20">
						<li class="nav-item">
							<a href="#tab_keluar" data-toggle="tab" aria-expanded="true" class="nav-link active">POS (Barang Keluar)</a>
						</li>
						<li class="nav-item">
							<a href="#tab_masuk" data-toggle="tab" aria-expanded="false" class="nav-link">Stok Opname (Barang Masuk)</a>
						</li>
						<li class="nav-item">
							<a href="#tab_report" data-toggle="tab" aria-expanded="false" class="nav-link">Statistik / Report</a>
						</li>
						<li class="nav-item">
							<a href="#tab_master" data-toggle="tab" aria-expanded="false" class="nav-link">Master Barang</a>
						</li>
					</ul>
					<div class="tab-content">
						<div class="tab-pane active" id="tab_keluar">
							@livewire('gudang-pos')
						</div>

						<div class="tab-pane" id="tab_masuk">
							<div class="row">
								<div class="col-lg-4">
									<div class="card-box">
										<h4 class="m-t-0">Barang Masuk (Stok Opname)</h4>
										<div class="form-group">
											<label>Tanggal Masuk</label>
											<input type="text" id="op_in_tanggal" class="form-control" value="{{$tanggal}}">
										</div>
										<div class="form-group">
											<label>Supplier / Keterangan</label>
											<input type="text" id="op_in_supplier" class="form-control" placeholder="contoh: PT ABC / PO # / dll">
										</div>
										<div class="form-group">
											<label>Pilih Barang</label>
											<select id="op_in_pos" class="form-control">
												<option value="" selected disabled>-- Pilih Barang --</option>
												@foreach($jjenis as $rjenis)
													@php($kode = ($rjenis['kodejenis'] ?? '') ?: preg_replace('/\s+/', '', (string) ($rjenis['jenis'] ?? '')))
													<option value="{{ $rjenis['jenis'] }}"
														data-kodejenis="{{ $kode }}"
														data-jenisid="{{ $rjenis['id'] ?? '' }}"
														data-satuan="{{ $rjenis['satuan'] }}"
														data-satuan-kecil="{{ $rjenis['satuan_kecil'] ?? '' }}"
														data-konversi="{{ $rjenis['konversi_kecil'] ?? 1 }}">{{ $kode }} - {{ $rjenis['jenis'] }} ( {{ $rjenis['satuan'] }} )</option>
												@endforeach
												<option value="__NEW__">+ Barang Baru (Input Manual)</option>
											</select>
										</div>
										<div class="form-group">
											<label>Kode Barang (Internal)</label>
											<input type="text" id="op_in_kode_barang" class="form-control" placeholder="contoh: ATK / CAIRAN / KODE ITEM" maxlength="40" readonly>
											<small class="text-muted">Kode internal barang (bukan barcode). Otomatis terisi jika pilih barang dari list.</small>
										</div>
										<div class="form-group">
											<label>Barcode (CODE128 - Angka)</label>
											<input type="text" id="op_in_barcode" class="form-control" placeholder="akan terisi otomatis" readonly>
											<small class="text-muted">Barcode dibedakan: satuan besar vs satuan kecil (nilai barcode berbeda).</small>
										</div>
										<div id="op_in_new_fields" style="display:none;">
											<div class="form-group">
												<label>Nama Barang (Baru)</label>
												<input type="text" id="op_in_new_jenis" class="form-control" placeholder="contoh: AST N806">
											</div>
											<div class="form-group">
												<label>Satuan Besar</label>
												<input type="text" id="op_in_new_satuan" class="form-control" placeholder="contoh: BOX">
											</div>
											<div class="form-group">
												<label>Satuan Kecil (opsional)</label>
												<input type="text" id="op_in_new_satuan_kecil" class="form-control" placeholder="contoh: PCS / STRIP">
											</div>
											<div class="form-group">
												<label>Konversi ke Satuan Kecil (opsional)</label>
												<input type="number" id="op_in_new_konversi" class="form-control" value="1" min="1">
											</div>
											<div class="form-group">
												<label>Stok Minimum Warning (base)</label>
												<input type="number" id="op_in_new_stok_minimum" class="form-control" value="0" min="0">
											</div>
											<div class="form-group">
												<small class="text-muted">Catatan: barcode (CODE128 angka) untuk barang baru dibuat otomatis setelah barang disimpan.</small>
											</div>
										</div>
										<div class="form-group">
											<label>Scan Barcode (CODE128)</label>
											<input type="text" id="op_in_scan" class="form-control" placeholder="scan lalu Enter">
											<small class="text-muted">Scan akan otomatis memilih barang & set satuan (besar/kecil) sesuai barcode.</small>
										</div>
										<div class="form-group">
											<label>Satuan Input</label>
											<select id="op_in_satuan_transaksi" class="form-control">
												<option value="besar">Satuan Besar</option>
												<option value="kecil">Satuan Kecil (Pecah Satuan)</option>
											</select>
										</div>
										<div class="form-group">
											<label>Jumlah</label>
											<input type="text" id="op_in_total" class="form-control">
										</div>
										<div class="form-group">
											<label>Masa Expired</label>
											<input type="text" id="op_in_masa_expired" class="form-control" placeholder="dd-mm-yyyy (opsional)">
										</div>
										<div class="form-group">
											<button type="button" class="btn btn-success btn-block" id="btn_op_in_addline">Tambah ke Daftar</button>
										</div>
										<div class="form-group m-b-0">
											<button type="button" class="btn btn-custom btn-block" id="btn_op_in_commit">Simpan Semua Barang Masuk</button>
										</div>
									</div>
								</div>
								<div class="col-lg-8">
									<div class="card-box">
										<h4 class="m-t-0">Daftar Barang Masuk</h4>
										<div class="table-responsive">
											<table class="table table-bordered table-striped m-b-0">
												<thead>
													<tr>
														<th style="width: 110px">Kode</th>
														<th>Barang</th>
														<th style="width: 140px">Qty</th>
														<th style="width: 120px">Satuan</th>
														<th style="width: 140px">Expired</th>
														<th style="width: 90px">Aksi</th>
													</tr>
												</thead>
												<tbody id="op_in_lines">
													<tr><td colspan="6" class="text-center text-muted">Belum ada item.</td></tr>
												</tbody>
											</table>
										</div>
										<small class="text-muted d-block m-t-10">Catatan: sistem akan menyimpan per-item menjadi baris transaksi (mirip stok opname).</small>
									</div>
								</div>
							</div>
						</div>

						<div class="tab-pane" id="tab_report">
							<div class="row">
								<div class="col-md-12">
									<div class="card-box ribbon-box">
										<div class="ribbon ribbon-primary">Report Transaksi</div>
										<p class="m-b-0"></p>
										<div class="form-group">
											<div class="row">
												<div class="col-lg-4">
													<select id="cekbln" class="form-control">
														<option value="ALL">ALL</option>
														<option value="01">Jan</option>
														<option value="02">Feb</option>
														<option value="03">Mar</option>
														<option value="04">Apr</option>
														<option value="05">May</option>
														<option value="06">Jun</option>
														<option value="07">Jul</option>
														<option value="08">Aug</option>
														<option value="09">Sep</option>
														<option value="10">Oct</option>
														<option value="11">Nov</option>
														<option value="12">Dec</option>
													</select>
												</div>
												<div class="col-lg-4">
													<input type="text" class="form-control" id="cekthn" value="{{ $tahunne }}">
												</div>
												<div class="col-lg-2">
													<button class="btn btn-warning btn-flat" type="button" id="btnviewdata">View Report</button>
												</div>
												<div class="col-lg-2">
													<button class="btn btn-success btn-flat" type="button" id="btnexportreport">Export</button>
												</div>
											</div>
										</div>
										<div class="form-group">
											<div id="gridreportblnini"></div>
										</div>
									</div>
								</div>
							</div>

							<div class="row">
								<div class="col-md-4">
									<div class="card-box">
										<h5 class="m-t-0">Statistik Harian (Base Unit)</h5>
										<div>Masuk: <b id="stat_harian_masuk">{{ number_format($stat_harian_masuk ?? 0, 0, '.', ',') }}</b></div>
										<div>Keluar: <b id="stat_harian_keluar">{{ number_format($stat_harian_keluar ?? 0, 0, '.', ',') }}</b></div>
										<hr>
										<div class="table-responsive">
											<table class="table table-sm table-bordered m-b-0">
												<thead><tr><th>Jenis</th><th>Masuk</th><th>Keluar</th></tr></thead>
												<tbody id="stat_perjenis_harian_body">
												@forelse($stat_perjenis_harian ?? [] as $row)
													<tr><td>{{ $row['jenis'] }}</td><td class="text-right">{{ number_format($row['masuk'],0,'.',',') }}</td><td class="text-right">{{ number_format($row['keluar'],0,'.',',') }}</td></tr>
												@empty
													<tr><td colspan="3" class="text-center">Belum ada transaksi</td></tr>
												@endforelse
												</tbody>
											</table>
										</div>
									</div>
								</div>
								<div class="col-md-4">
									<div class="card-box">
										<h5 class="m-t-0">Statistik Bulanan (Base Unit)</h5>
										<div>Masuk: <b id="stat_bulanan_masuk">{{ number_format($stat_bulanan_masuk ?? 0, 0, '.', ',') }}</b></div>
										<div>Keluar: <b id="stat_bulanan_keluar">{{ number_format($stat_bulanan_keluar ?? 0, 0, '.', ',') }}</b></div>
										<hr>
										<div class="table-responsive">
											<table class="table table-sm table-bordered m-b-0">
												<thead><tr><th>Jenis</th><th>Masuk</th><th>Keluar</th></tr></thead>
												<tbody id="stat_perjenis_bulanan_body">
												@forelse($stat_perjenis_bulanan ?? [] as $row)
													<tr><td>{{ $row['jenis'] }}</td><td class="text-right">{{ number_format($row['masuk'],0,'.',',') }}</td><td class="text-right">{{ number_format($row['keluar'],0,'.',',') }}</td></tr>
												@empty
													<tr><td colspan="3" class="text-center">Belum ada transaksi</td></tr>
												@endforelse
												</tbody>
											</table>
										</div>
									</div>
								</div>
								<div class="col-md-4">
									<div class="card-box">
										<h5 class="m-t-0">Statistik Tahunan (Base Unit)</h5>
										<div>Masuk: <b id="stat_tahunan_masuk">{{ number_format($stat_tahunan_masuk ?? 0, 0, '.', ',') }}</b></div>
										<div>Keluar: <b id="stat_tahunan_keluar">{{ number_format($stat_tahunan_keluar ?? 0, 0, '.', ',') }}</b></div>
										<hr>
										<div class="table-responsive">
											<table class="table table-sm table-bordered m-b-0">
												<thead><tr><th>Jenis</th><th>Masuk</th><th>Keluar</th></tr></thead>
												<tbody id="stat_perjenis_tahunan_body">
												@forelse($stat_perjenis_tahunan ?? [] as $row)
													<tr><td>{{ $row['jenis'] }}</td><td class="text-right">{{ number_format($row['masuk'],0,'.',',') }}</td><td class="text-right">{{ number_format($row['keluar'],0,'.',',') }}</td></tr>
												@empty
													<tr><td colspan="3" class="text-center">Belum ada transaksi</td></tr>
												@endforelse
												</tbody>
											</table>
										</div>
									</div>
								</div>
							</div>

							<div class="row">
								<div class="col-md-6">
									<div class="card-box">
										<h4 class="m-t-0 m-b-15">Warning Barang Segera Habis</h4>
										<div id="warningStockList">
											@if(isset($warningstok) && count($warningstok) > 0)
												@foreach($warningstok as $w)
													<div class="alert alert-danger m-b-10">
														<b>{{ $w['jenis'] }}</b> tersisa {{ $w['saldo'] }}.
														Stok minimum: {{ number_format($w['minimum'], 0, '.', ',') }} {{ $w['satuan_kecil'] }}.
													</div>
												@endforeach
											@else
												<div class="alert alert-success m-b-0">Semua stok masih aman.</div>
											@endif
										</div>
									</div>
								</div>
								<div class="col-md-6">
									<div class="card-box">
										<h4 class="m-t-0 m-b-15">Barang Mendekati Expired (H-30)</h4>
										@if(isset($expiringSoon) && count($expiringSoon) > 0)
											<div class="table-responsive">
												<table class="table table-bordered table-striped">
													<thead>
														<tr>
															<th>Jenis</th>
															<th>Deskripsi</th>
															<th>Tanggal Masuk</th>
															<th>Masa Expired</th>
															<th>Jumlah</th>
															<th>Satuan</th>
															<th>Sisa Hari</th>
														</tr>
													</thead>
													<tbody id="expiringSoonBody">
														@foreach($expiringSoon as $e)
															<tr>
																<td>{{ $e['jenis'] }}</td>
																<td>{{ $e['deskripsi'] }}</td>
																<td class="text-center">{{ $e['tanggal_masuk'] }}</td>
																<td class="text-center">{{ $e['masa_expired'] }}</td>
																<td class="text-right">{{ number_format($e['qty'], 0, '.', ',') }}</td>
																<td class="text-center">{{ strtoupper($e['satuan']) }}</td>
																<td class="text-center"><span class="badge badge-{{ $e['badge'] }}">{{ $e['sisa_hari'] }} hari</span></td>
															</tr>
														@endforeach
													</tbody>
												</table>
											</div>
										@else
											<div class="alert alert-success m-b-0">Tidak ada barang yang mendekati masa expired dalam 30 hari ke depan.</div>
										@endif
									</div>
								</div>
							</div>
						</div>

						<div class="tab-pane" id="tab_master">
							<div class="row">
								<div class="col-md-12">
									<div class="card-box ribbon-box">
										<div class="ribbon ribbon-primary">Master Barang / Stok</div>
										<p class="m-b-0"></p>
										<div class="form-group">
											<a href="#" id="topbtntambahjenis" class="btn btn-block btn-social btn-flickr">
												<i class="fa fa-database"></i> Tambah Jenis
											</a>
										</div>
										<div class="form-group">
											<div class="table-responsive">
												<table id="gridjenisTable" class="table table-bordered table-striped">
													<thead>
														<tr>
															<th>Kode</th>
															<th>Jenis</th>
															<th>Satuan</th>
															<th>Satuan Kecil</th>
															<th>Konversi</th>
															<th>Stok Min</th>
															<th>Sisa</th>
															<th>Warning</th>
															<th>Barcode</th>
															<th>Detail</th>
															<th>Edit</th>
														</tr>
													</thead>
													<tbody>
														@foreach(($jenisRows ?? []) as $row)
															@php($kode = ($row['kodejenis'] ?? '') ?: preg_replace('/\s+/', '', (string) ($row['jenis'] ?? '')))
																@php($hasBreakdown = trim((string)($row['satuan_kecil'] ?? '')) !== '' && (int)($row['konversi_kecil'] ?? 1) > 1)
															<tr>
																<td class="text-center"><code>{{ $kode }}</code></td>
																<td>{{ $row['jenis'] }}</td>
																<td>{{ $row['satuan'] }}</td>
																<td>{{ $row['satuan_kecil'] }}</td>
																<td class="text-right">{{ number_format($row['konversi_kecil'], 0, '.', ',') }}</td>
																<td class="text-right">{{ number_format($row['stok_minimum'], 0, '.', ',') }}</td>
																<td>{{ $row['saldo'] }}</td>
																<td class="text-center">{{ $row['warning'] }}</td>
																<td class="text-center">
																	<button type="button"
																		class="btn btn-sm btn-info btnprintbarcode"
																		data-id="{{ $row['id'] }}"
																		data-jenis="{{ $row['jenis'] }}"
																		data-mode="besar"
																		data-satuan="{{ $row['satuan'] }}">Besar</button>
																	@if($hasBreakdown)
																		<button type="button"
																			class="btn btn-sm btn-info btnprintbarcode"
																			data-id="{{ $row['id'] }}"
																			data-jenis="{{ $row['jenis'] }}"
																			data-mode="kecil"
																			data-satuan="{{ $row['satuan_kecil'] }}">Kecil</button>
																	@endif
																</td>
																<td class="text-center">
																	<button type="button"
																		class="btn btn-sm btn-primary btndetailbarang"
																		data-id="{{ $row['id'] }}"
																		data-kode="{{ $kode }}"
																		data-jenis="{{ $row['jenis'] }}"
																		data-satuan="{{ $row['satuan'] }}"
																		data-has-breakdown="{{ $hasBreakdown ? 1 : 0 }}"
																		data-satuan-kecil="{{ $row['satuan_kecil'] }}"
																		data-konversi="{{ $row['konversi_kecil'] }}"
																		data-saldo="{{ $row['saldo'] }}">Detail</button>
																</td>
																<td class="text-center">
																	<button type="button"
																		class="btn btn-sm btn-warning btneditjenis"
																		data-id="{{ $row['id'] }}"
																		data-kodejenis="{{ $kode }}"
																		data-jenis="{{ $row['jenis'] }}"
																		data-satuan="{{ $row['satuan'] }}"
																		data-satuan-kecil="{{ $row['satuan_kecil'] }}"
																		data-konversi-kecil="{{ $row['konversi_kecil'] }}"
																		data-stok-minimum="{{ $row['stok_minimum'] }}">Edit</button>
																</td>
															</tr>
														@endforeach
													</tbody>
												</table>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div> <!-- end container -->
</div>
<!-- TOKEN -->
<div id="modaltambahjenisbrg" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
				<h4 class="modal-title" id="myModalLabel">Input Jenis Barang</h4>
			</div>
			<div class="modal-body">
				<div class="form-group">
					<label>Jenis Barang</label>
					<input type="text" id="jenis_deskripsi" name="jenis_deskripsi" class="form-control">			  
				</div>
				<div class="form-group">
					<label>Kode Barang (Internal)</label>
					<div class="input-group">
						<input type="text" id="jenis_kode" name="jenis_kode" class="form-control" placeholder="contoh: ASTN806" maxlength="40">
						<div class="input-group-append">
							<button class="btn btn-info" type="button" id="btn_autokode">Auto</button>
						</div>
					</div>
					<small class="text-muted">Kode internal untuk identifikasi (bukan barcode). Hanya huruf/angka dan simbol <code>-</code> <code>_</code> <code>.</code>, tanpa spasi (2-40 karakter).</small>
				</div>
                <div class="form-group">
                    <label>Satuan </label>
                    <input type="text" id="jenis_satuan" name="jenis_satuan" class="form-control">			  
                </div>
                <div class="form-group">
                    <label>Satuan Kecil (untuk pecah satuan)</label>
                    <input type="text" id="jenis_satuan_kecil" name="jenis_satuan_kecil" class="form-control" placeholder="contoh: strip / pcs / vial">
                </div>
                <div class="form-group">
                    <label>Konversi ke Satuan Kecil</label>
                    <input type="number" id="jenis_konversi_kecil" name="jenis_konversi_kecil" class="form-control" value="1" min="1">
                    <small class="text-muted">Contoh: 1 box = 100 strip, isi 100.</small>
                </div>
                <div class="form-group">
                    <label>Stok Minimum Warning (dalam satuan kecil/base)</label>
                    <input type="number" id="jenis_stok_minimum" name="jenis_stok_minimum" class="form-control" value="0" min="0">
                </div>
                <div class="form-group account-btn text-center m-t-10">
					<div class="col-12">
                        <input type="hidden" id="jenis_idne" name="jenis_idne" class="form-control">
						<button class="btn w-lg btn-custom waves-effect waves-light" type="button" id="btnsimpanjenis">Tambahkan</button>
					</div>
				</div>
			</div>
		</div><!-- /.modal-content -->
	</div><!-- /.modal-dialog -->
</div>
<div id="modalpemasukan" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
				<h4 class="modal-title" id="myModalLabel">Input Data Penerimaan</h4>
			</div>
			<div class="modal-body">
                <div class="form-group">
                    <label>Tanggal Masuk</label>
                    <input type="text" id="in_tanggal" name="in_tanggal" class="form-control" value="{{$tanggal}}">
                </div>
                <div class="form-group">
                    <label>Jenis Barang</label>
                    <select id="in_pos" name="in_pos" class="form-control" >
                        @foreach($jjenis as $rjenis)
							@php($kode = ($rjenis['kodejenis'] ?? '') ?: preg_replace('/\s+/', '', (string) ($rjenis['jenis'] ?? '')))
                            <option value="{{ $rjenis['jenis'] }}" data-kodejenis="{{ $kode }}" data-satuan="{{ $rjenis['satuan'] }}" data-satuan-kecil="{{ $rjenis['satuan_kecil'] ?? '' }}" data-konversi="{{ $rjenis['konversi_kecil'] ?? 1 }}">{{ $kode }} - {{ $rjenis['jenis'] }} ( {{ $rjenis['satuan'] }} )</option>
                        @endforeach
                    </select>			  
                </div>
                <div class="form-group">
                    <label>Satuan Input</label>
                    <select id="in_satuan_transaksi" class="form-control">
                        <option value="besar">Satuan Besar</option>
                        <option value="kecil">Satuan Kecil (Pecah Satuan)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Supplier</label>
                    <input type="text" id="in_deskripsi" name="in_deskripsi" class="form-control">
                </div>
                <div class="form-group">
                    <label>Jumlah</label>
                    <input type="text" id="in_total" name="in_total" class="form-control">
                </div>
                <div class="form-group">
                    <label>Masa Expired</label>
                    <input type="text" id="in_masa_expired" name="in_masa_expired" class="form-control" placeholder="dd-mm-yyyy">
                </div>
				<div class="form-group account-btn text-center m-t-10">
					<div class="col-12">
						<button class="btn w-lg btn-custom waves-effect waves-light" type="button" id="btnsimpanpemasukan">Simpan</button>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>
<div id="modalpengeluaran" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
				<h4 class="modal-title" id="myModalLabel">Input Data Pengeluaran</h4>
			</div>
			<div class="modal-body">
                <div class="form-group">
                    <label>Tanggal</label>
                    <input type="text" id="out_tanggal" name="out_tanggal" class="form-control" value="{{$tanggal}}">
                </div>
                <div class="form-group">
                    <label>Barang yang diminta</label>
                    <select id="out_pos" name="out_pos" class="form-control" >
                        @foreach($jjenis as $rjenis)
							@php($kode = ($rjenis['kodejenis'] ?? '') ?: preg_replace('/\s+/', '', (string) ($rjenis['jenis'] ?? '')))
                            <option value="{{ $rjenis['jenis'] }}" data-kodejenis="{{ $kode }}" data-satuan="{{ $rjenis['satuan'] }}" data-satuan-kecil="{{ $rjenis['satuan_kecil'] ?? '' }}" data-konversi="{{ $rjenis['konversi_kecil'] ?? 1 }}">{{ $kode }} - {{ $rjenis['jenis'] }} ( {{ $rjenis['satuan'] }} )</option>
                        @endforeach
                    </select>			  
                </div>
                <div class="form-group">
                    <label>Satuan Pengeluaran</label>
                    <select id="out_satuan_transaksi" class="form-control">
                        <option value="kecil">Satuan Kecil (Pecah Satuan)</option>
                        <option value="besar">Satuan Besar</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Peminta</label>
                    <select id="out_deskripsi" name="out_deskripsi" class="form-control" >
                        @foreach($pegawai as $rpegawai)
                            <option value="{{ $rpegawai['id'] }}">{{ $rpegawai['nama'] }} ( {{ $rpegawai['previlege'] }} )</option>
                        @endforeach
                    </select>
                </div>
                <div class="form-group">
                    <label>Total</label>
                    <input type="text" id="out_total" name="out_total" class="form-control">
                </div>
				<div class="form-group account-btn text-center m-t-10">
					<div class="col-12">
						<button class="btn w-lg btn-custom waves-effect waves-light" type="button" id="btnsimpanpengeluaran">Simpan</button>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>
<div id="modaleditor" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
				<h4 class="modal-title" id="myModalLabel">Editor Data</h4>
			</div>
			<div class="modal-body">
                <div class="form-group">
                    <label>Tanggal</label>
                    <input type="text" id="edit_tanggal" name="edit_tanggal" class="form-control" value="{{$tanggal}}">
                </div>
                <div class="form-group">
                    <label>Jenis barang</label>
                    <select id="edit_pos" name="edit_pos" class="form-control" >
                        @foreach($jjenis as $rjenis)
                            <option value="{{ $rjenis['jenis'] }}">{{ $rjenis['jenis'] }} ( {{ $rjenis['satuan'] }} )</option>
                        @endforeach
                    </select>			  
                </div>
                <div class="form-group">
                    <label>Deskripsi</label>
                    <input type="text" id="edit_deskripsi" name="edit_deskripsi" class="form-control">
                </div>
                <div class="form-group">
                    <label>Total</label>
                    <input type="text" id="edit_total" name="edit_total" class="form-control">			  
                </div>
                <div class="form-group">
                    <label>Masa Expired</label>
                    <input type="text" id="edit_masa_expired" name="edit_masa_expired" class="form-control" placeholder="dd-mm-yyyy">
                </div>
                <div class="form-group">
                    <label>Alasan Di Edit / Di Hapus</label>
                    <input type="text" id="edit_alasan" name="edit_alasan" class="form-control">			  
                </div>
				<div class="form-group account-btn text-center m-t-10">
					<div class="col-12">
                        <button class="btn w-lg btn-danger waves-effect waves-light" type="button" id="btnsimpanhapus">Delete</button>
                        <input type="hidden" id="edit_id" name="edit_id" class="form-control">
						<button class="btn w-lg btn-custom waves-effect waves-light" type="button" id="btnsimpanedit">Simpan</button>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>
<div id="modalDetailBarang" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="modalDetailBarangLabel" aria-hidden="true">
	<div class="modal-dialog modal-lg">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
				<h4 class="modal-title" id="modalDetailBarangLabel">Detail Barang</h4>
			</div>
			<div class="modal-body">
				<div class="row">
					<div class="col-md-7">
						<table class="table table-bordered m-b-0">
							<tr><td style="width: 160px"><b>Kode</b></td><td><code id="detail_kode">-</code></td></tr>
							<tr><td><b>Nama</b></td><td id="detail_jenis">-</td></tr>
							<tr><td><b>Satuan</b></td><td id="detail_satuan">-</td></tr>
							<tr><td><b>Satuan Kecil</b></td><td id="detail_satuan_kecil">-</td></tr>
							<tr><td><b>Konversi</b></td><td id="detail_konversi">-</td></tr>
							<tr><td><b>Stok</b></td><td id="detail_saldo">-</td></tr>
						</table>
					</div>
					<div class="col-md-5">
						<div class="text-center" style="border:1px dashed #ddd; padding:12px;">
							<div class="form-group text-left">
								<label>Satuan Barcode</label>
								<select id="detail_barcode_mode" class="form-control">
									<option value="besar">Satuan Besar</option>
									<option value="kecil">Satuan Kecil</option>
								</select>
							</div>
							<svg id="detail_barcode_svg"></svg>
							<div class="m-t-5">
								<small class="text-muted">Barcode: <code id="detail_barcode_value">-</code></small>
							</div>
							<div class="m-t-10">
								<button type="button" class="btn btn-info" id="btn_detail_print_barcode">Cetak Barcode</button>
							</div>
							<small class="text-muted d-block m-t-10">Format: CODE128</small>
						</div>
					</div>
				</div>
				<hr>
				<div class="row">
					<div class="col-md-6">
						<button type="button" class="btn btn-success btn-block" id="btn_detail_quick_masuk">Input Barang Masuk</button>
					</div>
					<div class="col-md-6">
						<button type="button" class="btn btn-primary btn-block" id="btn_detail_quick_keluar">Input Barang Keluar</button>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>
<div id="tempatctk" style="overflow: hidden; display: none;">
	<div id="tabel_cetak"></div>
</div>
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">

@endsection
@push('script')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script type="text/javascript">
	    $(function () {
	        $("#in_tanggal").datepicker({format: 'yyyy-mm-dd'});
	        $("#out_tanggal").datepicker({format: 'yyyy-mm-dd'});
	        $("#edit_tanggal").datepicker({format: 'yyyy-mm-dd'});
			$("#op_in_tanggal").datepicker({format: 'yyyy-mm-dd'});
	        $("#in_masa_expired").datepicker({format: 'dd-mm-yyyy'});
			$("#op_in_masa_expired").datepicker({format: 'dd-mm-yyyy'});
	        $("#edit_masa_expired").datepicker({format: 'dd-mm-yyyy'});
	    });
    function openedpage( jQuery ){
		var set01=document.getElementById('cekbln').value;
		var set02=document.getElementById('cekthn').value;
		var token=document.getElementById('token').value;
		var source = {
			datatype: "json",
			datafields: [
                { name: 'id',type: 'text'},	
                { name: 'tanggal',type: 'text'},
                { name: 'bulan',type: 'text'},
                { name: 'tahun',type: 'text'},
                { name: 'deskripsi',type: 'text'},
                { name: 'pemasukan',type: 'text'},
                { name: 'pengeluaran',type: 'text'},
                { name: 'jenis',type: 'text'},
                { name: 'masa_expired',type: 'text'},
                { name: 'keterangan',type: 'text'},
                { name: 'tgllengkap',type: 'text'},
                { name: 'total',type: 'text'},
			],
			type: 'POST',
			data: {val01: set01, val02: set02, _token: token},
			url: 'simbhp/reportbhp',
		};
		var dataAdapter = new $.jqx.dataAdapter(source);
		$("#gridreportblnini").jqxGrid({
            width: '100%',
            showfilterrow: true,
            filterable: true,
            columnsresize: true,
            autoshowfiltericon: true,
            pageable: true,
            autoheight: true,
            theme: "energyblue",
            source: dataAdapter,
            selectionmode: 'multiplecellsextended',
            columns: [
                { text: 'dd', columngroup: 'tglinput', filtertype: 'checkedlist', datafield: 'tanggal', width: '5%', cellsalign: 'center', align: 'center' },
                { text: 'mm', columngroup: 'tglinput', filtertype: 'checkedlist', datafield: 'bulan', width: '5%', cellsalign: 'center', align: 'center' },
                { text: 'yy', columngroup: 'tglinput', filtertype: 'checkedlist', datafield: 'tahun', width: '5%', cellsalign: 'center', align: 'center' },
                { text: 'Jenis', datafield: 'jenis', filtertype: 'checkedlist', width: '10%', cellsalign: 'center', align: 'center' },
                { text: 'Deskripsi', datafield: 'deskripsi', width: '25%', cellsalign: 'left', align: 'center' },
                { text: 'MASUK', datafield: 'pemasukan', width: '10%', cellsalign: 'right', align: 'center' },
                { text: 'KELUAR', datafield: 'pengeluaran', width: '10%', cellsalign: 'right', align: 'center' },
                { text: 'Masa Expired', datafield: 'masa_expired', width: '12%', cellsalign: 'center', align: 'center' },
                { text: 'Keterangan', datafield: 'keterangan', width: '8%', cellsalign: 'right', align: 'center' },
                { text: 'Edit', columntype: 'button', width: '10%', cellsrenderer: function () { return "Edit";
                    }, buttonclick: function (row) {	
						editrow 		= row;
						var offset 		= $("#gridreportblnini").offset();
						var dataRecord 	= $("#gridreportblnini").jqxGrid('getrowdata', editrow);
						var tanggal 	= dataRecord.tanggal;
						var bulan 		= dataRecord.bulan;
						var tahun 		= dataRecord.tahun;
						var tulis 		= tahun+'-'+bulan+'-'+tanggal;
						$("#edit_deskripsi").val(dataRecord.deskripsi);
						$("#edit_id").val(dataRecord.id);
						$("#edit_pos").val(dataRecord.jenis);
						$("#edit_total").val(dataRecord.total);
						$("#edit_tanggal").val(tulis);
						$("#edit_masa_expired").val(dataRecord.masa_expired || '');
						$("#modaleditor").modal('show');
                    }
                },		
            ],
            columngroups: 
            [
                { text: 'Tanggal', align: 'center', name: 'tglinput' },                
            ]
        });
    }
    $(document).ready(function() {
		var token=document.getElementById('token').value;
	var reportInited = false;
	var jenisTableInited = false;

	function initReportIfNeeded(){
		if(reportInited){ return; }
		openedpage();
		reportInited = true;
	}

	function initJenisTableIfNeeded(){
		if(jenisTableInited){ return; }
		$('#gridjenisTable').DataTable();
		jenisTableInited = true;
	}

	if($('#tab_report').hasClass('active')){
		initReportIfNeeded();
	}
	if($('#tab_master').hasClass('active')){
		initJenisTableIfNeeded();
	}
	$('a[href="#tab_report"]').on('shown.bs.tab', function(){
		initReportIfNeeded();
	});
	$('a[href="#tab_master"]').on('shown.bs.tab', function(){
		initJenisTableIfNeeded();
	});
		var snapshotUrl = "{{ route('simbhp.snapshot') }}";
		var refreshInFlight = false;

		var jenisRows = @json($jenisRows ?? []);
		var opInLines = [];
		var currentDetail = null;

		function escapeHtml(value){
			var v = (value === undefined || value === null) ? '' : String(value);
			return $('<div>').text(v).html();
		}

		function formatInt(value){
			var n = parseInt(value, 10);
			if(isNaN(n)){ n = 0; }
			try { return n.toLocaleString('en-US'); } catch(e){ return (''+n); }
		}

	function normalizeKode(value){
		return (value || '').toString()
			.toUpperCase()
			.trim()
			.replace(/\s+/g, '')
			.replace(/[^A-Z0-9._-]/g, '')
			.substring(0, 40);
	}

		function parseBarcodeInput(value){
			var v = normalizeKode(value);
			if(!v){ return { kode: '', jenis_id: null, mode: 'besar', barcode_value: '' }; }

			var n = v.match(/^91(\d{8})([12])$/);
			if(n){
				var id = parseInt(n[1], 10);
				var unitDigit = (n[2] || '1').toString();
				return { kode: '', jenis_id: id, mode: (unitDigit === '2' ? 'kecil' : 'besar'), barcode_value: v };
			}

			var m = v.match(/^(.*)-(B|K)$/);
			if(m){
				var base = normalizeKode(m[1] || '');
				var suf = (m[2] || 'B').toString();
				return { kode: base, jenis_id: null, mode: (suf === 'K' ? 'kecil' : 'besar'), barcode_value: base + '-' + suf };
			}
			return { kode: v, jenis_id: null, mode: 'besar', barcode_value: v };
		}

		function buildBarcodeValueById(jenisId, mode){
			var id = parseInt(jenisId || 0, 10);
			if(!id || id <= 0){ return ''; }
			var idPart = id.toString().padStart(8, '0');
			var unitDigit = (mode === 'kecil') ? '2' : '1';
			return '91' + idPart + unitDigit;
		}

		function buildKodeMap(rows){
			var map = {};
			(rows || []).forEach(function(r){
				var kode = normalizeKode((r && r.kodejenis) ? r.kodejenis : (r ? r.jenis : ''));
			if(kode){
				map[kode.toUpperCase()] = r;
			}
		});
		return map;
		}

		var kodeMap = buildKodeMap(jenisRows);

		function buildIdMap(rows){
			var map = {};
			(rows || []).forEach(function(r){
				var id = parseInt((r && r.id) ? r.id : 0, 10);
				if(id > 0){
					map[id] = r;
				}
			});
			return map;
		}

		var idMap = buildIdMap(jenisRows);

		function renderStatPerjenis(tbodyId, rows){
			var html = '';
			(rows || []).forEach(function(r){
				html += '<tr>' +
					'<td>' + escapeHtml(r.jenis || '-') + '</td>' +
					'<td class="text-right">' + formatInt(r.masuk || 0) + '</td>' +
					'<td class="text-right">' + formatInt(r.keluar || 0) + '</td>' +
				'</tr>';
			});
			if(!html){
				html = '<tr><td colspan="3" class="text-center">Belum ada transaksi</td></tr>';
			}
			$(tbodyId).html(html);
		}

		function renderStats(stat){
			if(!stat){ return; }
			var harian = (stat && stat.harian) ? stat.harian : {};
			var bulanan = (stat && stat.bulanan) ? stat.bulanan : {};
			var tahunan = (stat && stat.tahunan) ? stat.tahunan : {};
			$('#stat_harian_masuk').text(formatInt(harian.masuk || 0));
			$('#stat_harian_keluar').text(formatInt(harian.keluar || 0));
			$('#stat_bulanan_masuk').text(formatInt(bulanan.masuk || 0));
			$('#stat_bulanan_keluar').text(formatInt(bulanan.keluar || 0));
			$('#stat_tahunan_masuk').text(formatInt(tahunan.masuk || 0));
			$('#stat_tahunan_keluar').text(formatInt(tahunan.keluar || 0));
			renderStatPerjenis('#stat_perjenis_harian_body', harian.perjenis || []);
			renderStatPerjenis('#stat_perjenis_bulanan_body', bulanan.perjenis || []);
			renderStatPerjenis('#stat_perjenis_tahunan_body', tahunan.perjenis || []);
		}

		function renderWarnings(warnings){
			var html = '';
			(warnings || []).forEach(function(w){
				html += '<div class="alert alert-danger m-b-10">' +
					'<b>' + escapeHtml(w.jenis || '-') + '</b> tersisa ' + escapeHtml(w.saldo || '-') + '. ' +
					'Stok minimum: ' + formatInt(w.minimum || 0) + ' ' + escapeHtml(w.satuan_kecil || '-') + '.' +
				'</div>';
			});
			if(!html){
				html = '<div class="alert alert-success m-b-0">Semua stok masih aman.</div>';
			}
			$('#warningStockList').html(html);
		}

		function renderExpiring(items){
			var $tbody = $('#expiringSoonBody');
			if(!$tbody.length){ return; }
			var html = '';
			(items || []).forEach(function(e){
				html += '<tr>' +
					'<td>' + escapeHtml(e.jenis || '-') + '</td>' +
					'<td>' + escapeHtml(e.deskripsi || '-') + '</td>' +
					'<td class="text-center">' + escapeHtml(e.tanggal_masuk || '-') + '</td>' +
					'<td class="text-center">' + escapeHtml(e.masa_expired || '-') + '</td>' +
					'<td class="text-right">' + formatInt(e.qty || 0) + '</td>' +
					'<td class="text-center">' + escapeHtml((e.satuan || '').toString().toUpperCase() || '-') + '</td>' +
					'<td class="text-center"><span class="badge badge-' + escapeHtml(e.badge || 'warning') + '">' + escapeHtml(e.sisa_hari || 0) + ' hari</span></td>' +
				'</tr>';
			});
			$tbody.html(html || '<tr><td colspan="7" class="text-center text-muted">Tidak ada data.</td></tr>');
		}

		function rebuildJenisTable(rows){
			var $table = $('#gridjenisTable');
			if(!$table.length){ return; }
			var html = '';
			(rows || []).forEach(function(row){
				var kode = normalizeKode((row && row.kodejenis) ? row.kodejenis : (row ? row.jenis : ''));
				var konv = parseInt((row && row.konversi_kecil) ? row.konversi_kecil : 1, 10);
				if(!konv || konv <= 0){ konv = 1; }
				var satuanKecil = ((row && row.satuan_kecil) ? row.satuan_kecil : '').toString().trim();
				var hasBreakdown = (satuanKecil !== '' && konv > 1);
				html += '<tr>' +
					'<td class="text-center"><code>' + escapeHtml(kode) + '</code></td>' +
					'<td>' + escapeHtml((row && row.jenis) ? row.jenis : '-') + '</td>' +
					'<td>' + escapeHtml((row && row.satuan) ? row.satuan : '-') + '</td>' +
					'<td>' + escapeHtml((row && row.satuan_kecil) ? row.satuan_kecil : '') + '</td>' +
					'<td class="text-right">' + formatInt(konv) + '</td>' +
					'<td class="text-right">' + formatInt((row && row.stok_minimum) ? row.stok_minimum : 0) + '</td>' +
					'<td>' + escapeHtml((row && row.saldo) ? row.saldo : '-') + '</td>' +
					'<td class="text-center">' + escapeHtml((row && row.warning) ? row.warning : '-') + '</td>' +
					'<td class="text-center">' +
						'<button type="button" class="btn btn-sm btn-info btnprintbarcode" data-id="' + escapeHtml((row && row.id) ? row.id : '') + '" data-jenis="' + escapeHtml((row && row.jenis) ? row.jenis : '') + '" data-mode="besar" data-satuan="' + escapeHtml((row && row.satuan) ? row.satuan : '') + '">Besar</button> ' +
						(hasBreakdown ? '<button type="button" class="btn btn-sm btn-info btnprintbarcode" data-id="' + escapeHtml((row && row.id) ? row.id : '') + '" data-jenis="' + escapeHtml((row && row.jenis) ? row.jenis : '') + '" data-mode="kecil" data-satuan="' + escapeHtml((row && row.satuan_kecil) ? row.satuan_kecil : '') + '">Kecil</button>' : '') +
					'</td>' +
					'<td class="text-center">' +
						'<button type="button" class="btn btn-sm btn-primary btndetailbarang" ' +
							'data-id="' + escapeHtml((row && row.id) ? row.id : '') + '" ' +
							'data-kode="' + escapeHtml(kode) + '" ' +
							'data-jenis="' + escapeHtml((row && row.jenis) ? row.jenis : '') + '" ' +
							'data-satuan="' + escapeHtml((row && row.satuan) ? row.satuan : '') + '" ' +
							'data-has-breakdown="' + (hasBreakdown ? '1' : '0') + '" ' +
							'data-satuan-kecil="' + escapeHtml((row && row.satuan_kecil) ? row.satuan_kecil : '') + '" ' +
							'data-konversi="' + escapeHtml(konv) + '" ' +
							'data-saldo="' + escapeHtml((row && row.saldo) ? row.saldo : '') + '">Detail</button>' +
					'</td>' +
					'<td class="text-center">' +
						'<button type="button" class="btn btn-sm btn-warning btneditjenis" ' +
							'data-id="' + escapeHtml((row && row.id) ? row.id : '') + '" ' +
							'data-kodejenis="' + escapeHtml(kode) + '" ' +
							'data-jenis="' + escapeHtml((row && row.jenis) ? row.jenis : '') + '" ' +
							'data-satuan="' + escapeHtml((row && row.satuan) ? row.satuan : '') + '" ' +
							'data-satuan-kecil="' + escapeHtml((row && row.satuan_kecil) ? row.satuan_kecil : '') + '" ' +
							'data-konversi-kecil="' + escapeHtml(konv) + '" ' +
							'data-stok-minimum="' + escapeHtml((row && row.stok_minimum) ? row.stok_minimum : 0) + '">Edit</button>' +
					'</td>' +
				'</tr>';
			});
			if(!html){
				html = '<tr><td colspan="11" class="text-center text-muted">Belum ada data.</td></tr>';
			}

			var hadDataTable = ($.fn.DataTable && $.fn.DataTable.isDataTable && $.fn.DataTable.isDataTable('#gridjenisTable'));
			if(hadDataTable){
				try{ $('#gridjenisTable').DataTable().destroy(); } catch(e){}
				jenisTableInited = false;
			}
			$('#gridjenisTable tbody').html(html);
			if(hadDataTable){
				initJenisTableIfNeeded();
			}
		}

		function rebuildSelectOptions(jjenis){
			var items = (jjenis || []).filter(function(x){
				return x && (x.jenis || '').toString().trim() !== '' && (x.jenis || '') !== 'Belum Ada Jenis Barang';
			});

			function makeOption(r){
				var kode = (((r && r.kodejenis) ? r.kodejenis : '') || '').toString();
				if(kode.trim() === ''){ kode = (r.jenis || '').toString().replace(/\s+/g, ''); }
				kode = normalizeKode(kode);
				var satuan = ((r && r.satuan) ? r.satuan : '').toString();
				var satuanKecil = ((r && r.satuan_kecil) ? r.satuan_kecil : '').toString();
				var konv = parseInt((r && r.konversi_kecil) ? r.konversi_kecil : 1, 10);
				if(!konv || konv <= 0){ konv = 1; }
				return '<option value="' + escapeHtml(r.jenis) + '"' +
					' data-kodejenis="' + escapeHtml(kode) + '"' +
					' data-jenisid="' + escapeHtml((r && r.id) ? r.id : '') + '"' +
					' data-satuan="' + escapeHtml(satuan) + '"' +
					' data-satuan-kecil="' + escapeHtml(satuanKecil) + '"' +
					' data-konversi="' + escapeHtml(konv) + '">' +
					escapeHtml(kode + ' - ' + r.jenis + ' ( ' + satuan + ' )') +
				'</option>';
			}

			// Stok opname select (punya opsi Barang Baru)
			var currentOp = $('#op_in_pos').val();
			var htmlOp = '<option value=\"\" selected disabled>-- Pilih Barang --</option>';
			items.forEach(function(r){ htmlOp += makeOption(r); });
			htmlOp += '<option value=\"__NEW__\">+ Barang Baru (Input Manual)</option>';
			$('#op_in_pos').html(htmlOp);
			if(currentOp){
				$('#op_in_pos').val(currentOp);
			}
			syncOpInSelected();

			// Legacy selects (modal lama / editor)
			var legacyIds = ['#in_pos', '#out_pos'];
			legacyIds.forEach(function(sel){
				var current = $(sel).val();
				var html = '';
				items.forEach(function(r){
					var kode = normalizeKode((((r && r.kodejenis) ? r.kodejenis : '') || r.jenis || '').toString());
					html += '<option value="' + escapeHtml(r.jenis) + '"' +
						' data-kodejenis="' + escapeHtml(kode) + '"' +
						' data-jenisid="' + escapeHtml((r && r.id) ? r.id : '') + '"' +
						' data-satuan="' + escapeHtml((r && r.satuan) ? r.satuan : '') + '"' +
						' data-satuan-kecil="' + escapeHtml((r && r.satuan_kecil) ? r.satuan_kecil : '') + '"' +
						' data-konversi="' + escapeHtml((r && r.konversi_kecil) ? r.konversi_kecil : 1) + '">' +
						escapeHtml(kode + ' - ' + r.jenis + ' ( ' + ((r && r.satuan) ? r.satuan : '') + ' )') +
					'</option>';
				});
				$(sel).html(html);
				if(current){ $(sel).val(current); }
				syncSatuanMode(sel, (sel === '#in_pos' ? '#in_satuan_transaksi' : '#out_satuan_transaksi'));
			});
		}

		function applySnapshot(data){
			if(!data){ return; }
			if(Array.isArray(data.jenisRows)){
				jenisRows = data.jenisRows;
				kodeMap = buildKodeMap(jenisRows);
				idMap = buildIdMap(jenisRows);
				rebuildJenisTable(jenisRows);
			}
			if(Array.isArray(data.warningstok)){
				renderWarnings(data.warningstok);
			}
			if(Array.isArray(data.expiringSoon)){
				renderExpiring(data.expiringSoon);
			}
			if(data.stat){
				renderStats(data.stat);
			}
			if(Array.isArray(data.jjenis)){
				rebuildSelectOptions(data.jjenis);
			}
		}

		window.gudangRefresh = function(){
			if(refreshInFlight){ return; }
			refreshInFlight = true;

			// Refresh report grid
			try{
				if($("#gridreportblnini").data('jqxGrid')){
					$("#gridreportblnini").jqxGrid('updatebounddata');
				}else if(typeof openedpage === 'function'){
					openedpage();
				}
			}catch(e){
				try{ if(typeof openedpage === 'function'){ openedpage(); } }catch(_){}
			}

			$.ajax({ url: snapshotUrl, method: 'GET' })
				.done(function(resp){
					applySnapshot(resp);
					if (window.Livewire && typeof window.Livewire.dispatch === 'function') {
						window.Livewire.dispatch('gudangpos-refresh');
					}
				})
				.always(function(){
					refreshInFlight = false;
				});
		};

		(function initGudangRefreshListener(){
			function attach(){
				if(!window.Livewire || typeof window.Livewire.on !== 'function'){ return; }
				window.Livewire.on('gudang-refresh', function(){
					if(typeof window.gudangRefresh === 'function'){
						window.gudangRefresh();
					}
				});
			}
			if(document.readyState === 'loading'){
				document.addEventListener('livewire:init', attach, { once: true });
			}else{
				document.addEventListener('livewire:init', attach);
				attach();
			}
		})();

	function syncSatuanMode(itemSelect, satuanSelect){
		var selected = $(itemSelect).find('option:selected');
		var satuanKecil = (selected.data('satuan-kecil') || '').toString().trim();
		var konversi = parseInt(selected.data('konversi') || 1, 10);
		var hasBreakdown = satuanKecil !== '' && konversi > 1;
		$(satuanSelect).find('option[value="kecil"]').prop('disabled', !hasBreakdown);
		if(!hasBreakdown && $(satuanSelect).val() === 'kecil'){
			$(satuanSelect).val('besar');
		}
	}

		function setSelectByKode(itemSelect, kode){
			var parsed = parseBarcodeInput(kode);
			if(parsed.jenis_id){
				var foundById = idMap[parsed.jenis_id];
				if(!foundById || !foundById.jenis){ return false; }
				$(itemSelect).val(foundById.jenis).trigger('change');
				return { ok:true, mode: parsed.mode, kode: normalizeKode(foundById.kodejenis || ''), jenis_id: parsed.jenis_id };
			}

			kode = (parsed.kode || '').toUpperCase();
			if(!kode){ return { ok:false, mode:'besar', kode:'', jenis_id:null }; }
			var found = kodeMap[kode];
			if(!found || !found.jenis){ return false; }
			$(itemSelect).val(found.jenis).trigger('change');
			return { ok:true, mode: parsed.mode, kode: kode, jenis_id: found.id || null };
		}

	function renderBarcodeInto(svgEl, kode){
		try{
			JsBarcode(svgEl, kode, {
				format: "CODE128",
				displayValue: true,
				height: 45,
				margin: 0
			});
		}catch(e){
			console.error(e);
		}
	}

		function printBarcode(barcodeValue, jenis, satuan){
			barcodeValue = normalizeKode(barcodeValue);
			if(!barcodeValue){
				$.toast({ heading: 'Gagal', text: 'Kode barang kosong', position: 'top-right', loaderBg: '#bf441d', icon: 'error', hideAfter: 3000, stack: 1 });
				return;
			}
			if (typeof window.jspdf === 'undefined' || typeof JsBarcode === 'undefined') {
				alert('Kesalahan: Library jsPDF atau JsBarcode belum dimuat.');
				return;
			}

		const { jsPDF } = window.jspdf;
		const doc = new jsPDF({
			orientation: 'landscape',
			unit: 'mm',
			format: [50, 35]
		});
		const leftMargin = 2;
		const contentWidth = 50 - (leftMargin * 2);
		let yPosition = 4;

		let nama = (jenis || '').toString().trim();
		if (nama.length > 18) {
			nama = nama.substring(0, 18) + ".";
		}

		doc.setFont('helvetica', 'bold');
		doc.setFontSize(7);
		doc.text(nama, leftMargin, yPosition, { maxWidth: contentWidth });
		yPosition += 4;

		try {
			const canvas = document.createElement('canvas');
			JsBarcode(canvas, barcodeValue, {
				format: "CODE128",
				displayValue: false,
				height: 40,
				width: 1.5,
				margin: 5
			});
			const barcodeDataUrl = canvas.toDataURL('image/png');
			const barcodeHeight = 10;
			doc.addImage(barcodeDataUrl, 'PNG', leftMargin, yPosition, contentWidth, barcodeHeight);
			yPosition += barcodeHeight + 3;
			doc.setFont('helvetica', 'bold');
			doc.setFontSize(9);
			const centerX = 50 / 2;
			doc.text(barcodeValue, centerX, yPosition, { align: 'center' });
			yPosition += 4;
		} catch (e) {
			console.error("Gagal membuat barcode:", e);
			doc.text("Error Barcode", leftMargin, yPosition);
			yPosition += 12;
		}

		doc.setFont('helvetica', 'normal');
		doc.setFontSize(6.5);
		doc.text(('Satuan: ' + (satuan || '').toString()), leftMargin, yPosition, { maxWidth: contentWidth });

		doc.output('dataurlnewwindow');
	}

	$('#in_pos').on('change', function(){ syncSatuanMode('#in_pos', '#in_satuan_transaksi'); });
	$('#out_pos').on('change', function(){ syncSatuanMode('#out_pos', '#out_satuan_transaksi'); });
	$('#op_in_pos').on('change', function(){ syncSatuanMode('#op_in_pos', '#op_in_satuan_transaksi'); });
	syncSatuanMode('#in_pos', '#in_satuan_transaksi');
	syncSatuanMode('#out_pos', '#out_satuan_transaksi');
	syncSatuanMode('#op_in_pos', '#op_in_satuan_transaksi');

		function syncOpInSelected(){
			var val = $('#op_in_pos').val();
			if(val === '__NEW__'){
				$('#op_in_new_fields').show();
				$('#op_in_kode_barang').prop('readonly', false).val('');
				$('#op_in_barcode').val('');
				$('#op_in_new_jenis').val('');
				$('#op_in_new_satuan').val('');
				$('#op_in_new_satuan_kecil').val('');
				$('#op_in_new_konversi').val('1');
				$('#op_in_new_stok_minimum').val('0');
				$('#op_in_satuan_transaksi').val('besar');
				$('#op_in_satuan_transaksi option[value="kecil"]').prop('disabled', true);
				return;
			}
			$('#op_in_new_fields').hide();
			var selected = $('#op_in_pos option:selected');
			var kode = normalizeKode(selected.data('kodejenis') || '');
			$('#op_in_kode_barang').prop('readonly', true).val(kode);
			syncSatuanMode('#op_in_pos', '#op_in_satuan_transaksi');
			var jenisId = parseInt(selected.data('jenisid') || 0, 10);
			var mode = $('#op_in_satuan_transaksi').val() || 'besar';
			$('#op_in_barcode').val(buildBarcodeValueById(jenisId, mode));
		}

	$('#op_in_pos').on('change', function(){
		syncOpInSelected();
	});
	syncOpInSelected();

		$('#op_in_kode_barang').on('input', function(){
			if($('#op_in_pos').val() !== '__NEW__'){ return; }
			$(this).val(normalizeKode($(this).val()));
		});

		function syncOpInNewSatuanAvailability(){
			if($('#op_in_pos').val() !== '__NEW__'){ return; }
			var satuanKecil = ($('#op_in_new_satuan_kecil').val() || '').toString().trim();
			var konv = parseInt($('#op_in_new_konversi').val() || 1, 10);
			var hasBreakdown = satuanKecil !== '' && konv > 1;
			$('#op_in_satuan_transaksi option[value="kecil"]').prop('disabled', !hasBreakdown);
			if(!hasBreakdown && $('#op_in_satuan_transaksi').val() === 'kecil'){
				$('#op_in_satuan_transaksi').val('besar');
			}
		}

		$('#op_in_new_satuan_kecil').on('input', syncOpInNewSatuanAvailability);
		$('#op_in_new_konversi').on('input', syncOpInNewSatuanAvailability);

		$('#op_in_satuan_transaksi').on('change', function(){
			if($('#op_in_pos').val() === '__NEW__'){ return; }
			var selected = $('#op_in_pos option:selected');
			var jenisId = parseInt(selected.data('jenisid') || 0, 10);
			var mode = $('#op_in_satuan_transaksi').val() || 'besar';
			$('#op_in_barcode').val(buildBarcodeValueById(jenisId, mode));
		});

	$("#topbtntambahjenis").click(function(){
		$("#jenis_idne").val('new');
		$("#jenis_deskripsi").val('');
		$("#jenis_kode").val('').data('manual', 0);
		$("#jenis_satuan").val('');
		$("#jenis_satuan_kecil").val('');
		$("#jenis_konversi_kecil").val('1');
		$("#jenis_stok_minimum").val('0');
		$("#modaltambahjenisbrg").modal('show');
	});
		$("#topbtnhapus").click(function(){ $("#modaleditor").modal('show'); $("#edit_id").val('delete'); });
	$(document).on('click', '.btneditjenis', function(){
		$("#jenis_idne").val($(this).data('id'));
		$("#jenis_deskripsi").val($(this).data('jenis'));
		$("#jenis_kode").val($(this).data('kodejenis') || '').data('manual', 1);
		$("#jenis_satuan").val($(this).data('satuan'));
		$("#jenis_satuan_kecil").val($(this).data('satuan-kecil'));
		$("#jenis_konversi_kecil").val($(this).data('konversi-kecil'));
		$("#jenis_stok_minimum").val($(this).data('stok-minimum'));
		$("#modaltambahjenisbrg").modal('show');
	});

	function sanitizeKodeBarang(value){
		return (value || '').toString()
			.toUpperCase()
			.replace(/\s+/g,'')
			.replace(/[^A-Z0-9._-]/g,'')
			.substring(0, 40);
	}

	function autogenKodeFromJenis(){
		var jenis = $('#jenis_deskripsi').val();
		$('#jenis_kode').val(sanitizeKodeBarang(jenis)).data('manual', 0);
	}

	$('#btn_autokode').on('click', function(){
		autogenKodeFromJenis();
	});

	$('#jenis_kode').on('input', function(){
		$(this).data('manual', 1);
		$(this).val(sanitizeKodeBarang($(this).val()));
	});

	$('#jenis_deskripsi').on('input', function(){
		var manual = parseInt($('#jenis_kode').data('manual') || 0, 10);
		if(manual === 0){
			autogenKodeFromJenis();
		}
	});

		$(document).on('click', '.btnprintbarcode', function(){
			var id = parseInt($(this).data('id') || 0, 10);
			var mode = ($(this).data('mode') || 'besar').toString();
			var barcodeValue = buildBarcodeValueById(id, mode);
			printBarcode(barcodeValue, $(this).data('jenis'), $(this).data('satuan'));
		});

		$(document).on('click', '.btndetailbarang', function(){
			currentDetail = {
				id: parseInt($(this).data('id') || 0, 10),
				kode: $(this).data('kode'),
				jenis: $(this).data('jenis'),
				satuan: $(this).data('satuan'),
				hasBreakdown: parseInt($(this).data('has-breakdown') || 0, 10) === 1,
			satuanKecil: $(this).data('satuan-kecil'),
			konversi: $(this).data('konversi'),
			saldo: $(this).data('saldo')
		};
		$('#detail_kode').text(currentDetail.kode || '-');
		$('#detail_jenis').text(currentDetail.jenis || '-');
		$('#detail_satuan').text(currentDetail.satuan || '-');
		$('#detail_satuan_kecil').text(currentDetail.satuanKecil || '-');
		$('#detail_konversi').text(currentDetail.konversi || '-');
		$('#detail_saldo').text(currentDetail.saldo || '-');
		$('#modalDetailBarang').modal('show');
		$('#detail_barcode_mode').val('besar');
		$('#detail_barcode_mode option[value="kecil"]').prop('disabled', !currentDetail.hasBreakdown);
		if(!currentDetail.hasBreakdown){
			$('#detail_barcode_mode').val('besar');
		}
			setTimeout(function(){
				var el = document.getElementById('detail_barcode_svg');
				if(el){
					var mode = $('#detail_barcode_mode').val() || 'besar';
					var val = buildBarcodeValueById(currentDetail.id, mode);
					$('#detail_barcode_value').text(val || '-');
					renderBarcodeInto(el, val);
				}
			}, 100);
		});

	$('#detail_barcode_mode').on('change', function(){
		if(!currentDetail){ return; }
		var el = document.getElementById('detail_barcode_svg');
		if(!el){ return; }
		var mode = $('#detail_barcode_mode').val() || 'besar';
			if(mode === 'kecil' && !currentDetail.hasBreakdown){
				mode = 'besar';
				$('#detail_barcode_mode').val('besar');
			}
			var val = buildBarcodeValueById(currentDetail.id, mode);
			$('#detail_barcode_value').text(val || '-');
			renderBarcodeInto(el, val);
		});

	$('#btn_detail_print_barcode').on('click', function(){
		if(!currentDetail){ return; }
		var mode = $('#detail_barcode_mode').val() || 'besar';
			if(mode === 'kecil' && !currentDetail.hasBreakdown){
				mode = 'besar';
			}
			var sat = (mode === 'kecil' ? (currentDetail.satuanKecil || currentDetail.satuan) : currentDetail.satuan);
			printBarcode(buildBarcodeValueById(currentDetail.id, mode), currentDetail.jenis, sat);
		});
	$('#btn_detail_quick_masuk').on('click', function(){
		if(!currentDetail){ return; }
		$('#modalDetailBarang').modal('hide');
		$('a[href="#tab_masuk"]').tab('show');
		setSelectByKode('#op_in_pos', currentDetail.kode);
		setTimeout(function(){ $('#op_in_total').focus(); }, 200);
	});
	$('#btn_detail_quick_keluar').on('click', function(){
		if(!currentDetail){ return; }
		$('#modalDetailBarang').modal('hide');
		$('a[href="#tab_keluar"]').tab('show');
		if (window.Livewire && typeof window.Livewire.dispatch === 'function') {
			window.Livewire.dispatch('gudangpos-select', { kode: currentDetail.kode });
		}
	});

	// DataTable di-init saat tab report dibuka (lihat initJenisTableIfNeeded)

	$("#btnsimpanjenis").click(function(){
		var val01=document.getElementById('jenis_idne').value;
		var val02=document.getElementById('jenis_deskripsi').value;
		var val03=document.getElementById('jenis_satuan').value;
		var val04=document.getElementById('jenis_konversi_kecil').value;
		var val05='jenis';
		var val06=document.getElementById('jenis_kode').value;
		var val07='';
		var val08=document.getElementById('jenis_satuan_kecil').value;
		var val09=document.getElementById('jenis_konversi_kecil').value;
		var val10=document.getElementById('jenis_stok_minimum').value;
		var val11='besar';
		$("#modaltambahjenisbrg").modal('hide');
		$.post('simbhp/exaddbarang', { _token: token, set01: val01, set02: val02, set03: val03, set04: val04, set05: val05, set06: val06, set07: val07, set08: val08, set09: val09, set10: val10, set11: val11 },
		function(data){
            var status  = data.status;
			var message = data.message;
			$.toast({
				heading: status,
				text: message,
				position: 'top-right',
				loaderBg: data.warna,
				icon: data.icon,
				hideAfter: 3000,
				stack: 1
			});
			if(typeof window.gudangRefresh === 'function'){
				window.gudangRefresh();
			}
			return false;
		});	
	});
    $("#btnsimpanpemasukan").click(function(){
		var val01=document.getElementById('in_deskripsi').value;
		var val02=document.getElementById('in_pos').value;	
		var val03=document.getElementById('in_tanggal').value;
		var val04=document.getElementById('in_total').value;
		var val05='pemasukan';
		var val06='';
		var val07='';
		var val08='';
		var val09='';
		var val10='';
		var val11=document.getElementById('in_satuan_transaksi').value;
		var val12=document.getElementById('in_masa_expired').value;
		$.post('simbhp/exaddbarang', { _token: token, set01: val01, set02: val02, set03: val03, set04: val04, set05: val05, set06: val06, set07: val07, set08: val08, set09: val09, set10: val10, set11: val11, set12: val12 },
		function(data){			
			$("#modalpemasukan").modal('hide');	
			var status  = data.status;
			var message = data.message;
			$.toast({
				heading: status,
				text: message,
				position: 'top-right',
				loaderBg: data.warna,
				icon: data.icon,
				hideAfter: 5000,
				stack: 1
			});
            openedpage();
			if(typeof window.gudangRefresh === 'function'){
				window.gudangRefresh();
			}
			return false;
		});	
	});
    $("#btnsimpanpengeluaran").click(function(){
		var val01=document.getElementById('out_deskripsi').value;
		var val02=document.getElementById('out_pos').value;	
		var val03=document.getElementById('out_tanggal').value;
		var val04=document.getElementById('out_total').value;
		var val05='pengeluaran';
		var val06='';
		var val07='';
		var val08='';
		var val09='';
		var val10='';
		var val11=document.getElementById('out_satuan_transaksi').value;
		var val12='';
		$.post('simbhp/exaddbarang', { _token: token, set01: val01, set02: val02, set03: val03, set04: val04, set05: val05, set06: val06, set07: val07, set08: val08, set09: val09, set10: val10, set11: val11, set12: val12 },
		function(data){			
			$("#modalpengeluaran").modal('hide');	
			var status  = data.status;
			var message = data.message;
			$.toast({
				heading: status,
				text: message,
				position: 'top-right',
				loaderBg: data.warna,
				icon: data.icon,
				hideAfter: 5000,
				stack: 1
			});
            openedpage();
			if(typeof window.gudangRefresh === 'function'){
				window.gudangRefresh();
			}
			return false;
		});	
	});
	$("#btnsimpanedit").click(function(){
		var val01=document.getElementById('edit_deskripsi').value;
		var val02=document.getElementById('edit_pos').value;	
		var val03=document.getElementById('edit_tanggal').value;
		var val04=document.getElementById('edit_total').value;
		var val05='editor';
		var val06=document.getElementById('edit_id').value;
		var val07=document.getElementById('edit_alasan').value;
		var val08='';
		var val09='';
		var val10='';
		var val11='besar';
		var val12=document.getElementById('edit_masa_expired').value;
		$.post('simbhp/exaddbarang', { _token: token, set01: val01, set02: val02, set03: val03, set04: val04, set05: val05, set06: val06, set07: val07, set08: val08, set09: val09, set10: val10, set11: val11, set12: val12 },
		function(data){			
			$("#modaleditor").modal('hide');	
			var status  = data.status;
			var message = data.message;
			$.toast({
				heading: status,
				text: message,
				position: 'top-right',
				loaderBg: data.warna,
				icon: data.icon,
				hideAfter: 5000,
				stack: 1
			});
            openedpage();
			if(typeof window.gudangRefresh === 'function'){
				window.gudangRefresh();
			}
			return false;
		});	
	});
	$("#btnsimpanhapus").click(function(){
		var val01=document.getElementById('edit_deskripsi').value;
		var val02=document.getElementById('edit_pos').value;	
		var val03=document.getElementById('edit_tanggal').value;
		var val04=document.getElementById('edit_total').value;
		var val05='hapus';
		var val06=document.getElementById('edit_id').value;
		var val07=document.getElementById('edit_alasan').value;
		var val08='';
		var val09='';
		var val10='';
		var val11='besar';
		var val12='';
		$.post('simbhp/exaddbarang', { _token: token, set01: val01, set02: val02, set03: val03, set04: val04, set05: val05, set06: val06, set07: val07, set08: val08, set09: val09, set10: val10, set11: val11, set12: val12 },
		function(data){			
			$("#modaleditor").modal('hide');	
			var status  = data.status;
			var message = data.message;
			$.toast({
				heading: status,
				text: message,
				position: 'top-right',
				loaderBg: data.warna,
				icon: data.icon,
				hideAfter: 5000,
				stack: 1
			});
            openedpage();
			if(typeof window.gudangRefresh === 'function'){
				window.gudangRefresh();
			}
			return false;
		});	
	});
    $("#btnviewdata").click(function(){
		openedpage();
	});
	$("#in_total").autoNumeric(	'init', {aSep: ',', mDec: '0', vMax: '99999999999999999999999999'} );
	$("#out_total").autoNumeric( 'init', {aSep: ',', mDec: '0', vMax: '99999999999999999999999999'} );
	$("#op_in_total").autoNumeric( 'init', {aSep: ',', mDec: '0', vMax: '99999999999999999999999999'} );

		function renderOpInLines(){
			if(!opInLines.length){
				$('#op_in_lines').html('<tr><td colspan="6" class="text-center text-muted">Belum ada item.</td></tr>');
				return;
			}
			var html = '';
			opInLines.forEach(function(line, idx){
				html += '<tr>' +
					'<td class="text-center"><code>' + (line.barcode_value || line.kode || '') + '</code></td>' +
					'<td>' + (line.jenis || '') + '</td>' +
					'<td class="text-right">' + (line.qty || '') + '</td>' +
					'<td class="text-center">' + (line.satuan_transaksi || '') + '</td>' +
					'<td class="text-center">' + (line.masa_expired || '-') + '</td>' +
					'<td class="text-center"><button type="button" class="btn btn-sm btn-danger btn_op_in_remove" data-index="' + idx + '">Hapus</button></td>' +
				'</tr>';
			});
			$('#op_in_lines').html(html);
		}

	function getSelectedKode(selectId){
		var selected = $(selectId).find('option:selected');
		return normalizeKode(selected.data('kodejenis') || '');
	}

		$('#op_in_scan').on('keypress', function(e){
			if(e.which === 13){
				e.preventDefault();
				var scanVal = $(this).val();
				var ok = setSelectByKode('#op_in_pos', scanVal);
				$(this).val('');
				if(ok){
					if(ok.mode){
						$('#op_in_satuan_transaksi').val(ok.mode);
					}
					syncOpInSelected();
					setTimeout(function(){ $('#op_in_total').focus(); }, 100);
				}else{
					$.toast({ heading: 'Gagal', text: 'Kode barang tidak ditemukan', position: 'top-right', loaderBg: '#bf441d', icon: 'error', hideAfter: 3000, stack: 1 });
				}
			}
		});

		$('#btn_op_in_addline').on('click', function(){
			var jenisSelect = $('#op_in_pos').val();
			var jenis = jenisSelect;
			var kode = '';
			var isNew = false;
			var satuanBesarNew = '';
			var satuanKecilNew = '';
			var konversiNew = 1;
			var stokMinNew = 0;

				if(jenisSelect === '__NEW__'){
					isNew = true;
					jenis = ($('#op_in_new_jenis').val() || '').toString().trim();
					kode = normalizeKode($('#op_in_kode_barang').val());
					satuanBesarNew = ($('#op_in_new_satuan').val() || '').toString().trim();
					satuanKecilNew = ($('#op_in_new_satuan_kecil').val() || '').toString().trim();
					konversiNew = parseInt($('#op_in_new_konversi').val() || 1, 10);
					stokMinNew = parseInt($('#op_in_new_stok_minimum').val() || 0, 10);
				} else {
					kode = getSelectedKode('#op_in_pos');
				}

			var qty = $('#op_in_total').val();
			var satuanTransaksi = $('#op_in_satuan_transaksi').val();
			var expired = $('#op_in_masa_expired').val();
			if(!jenis || !qty){
				$.toast({ heading: 'Gagal', text: 'Barang dan jumlah wajib diisi', position: 'top-right', loaderBg: '#bf441d', icon: 'error', hideAfter: 3000, stack: 1 });
				return;
			}
				if(isNew){
					if(!kode || kode.length < 2){
						$.toast({ heading: 'Gagal', text: 'Kode barang (internal) barang baru wajib (min 2 karakter)', position: 'top-right', loaderBg: '#bf441d', icon: 'error', hideAfter: 3500, stack: 1 });
						return;
					}
				if(!satuanBesarNew){
					$.toast({ heading: 'Gagal', text: 'Satuan besar barang baru wajib diisi', position: 'top-right', loaderBg: '#bf441d', icon: 'error', hideAfter: 3500, stack: 1 });
					return;
				}
				if(satuanKecilNew !== '' && (!konversiNew || konversiNew <= 1)){
					$.toast({ heading: 'Gagal', text: 'Jika memakai satuan kecil, konversi harus > 1', position: 'top-right', loaderBg: '#bf441d', icon: 'error', hideAfter: 3500, stack: 1 });
					return;
				}
				if(satuanTransaksi === 'kecil' && satuanKecilNew === ''){
					$.toast({ heading: 'Gagal', text: 'Satuan transaksi kecil dipilih, tapi satuan kecil barang baru belum diisi', position: 'top-right', loaderBg: '#bf441d', icon: 'error', hideAfter: 3500, stack: 1 });
					return;
				}
				}

				var barcodeValue = '';
				var jenisId = null;
				if(!isNew){
					var selected = $('#op_in_pos option:selected');
					jenisId = parseInt(selected.data('jenisid') || 0, 10);
					barcodeValue = buildBarcodeValueById(jenisId, satuanTransaksi);
				}
				opInLines.push({
					jenis_id: jenisId,
					kode: kode,
					barcode_value: barcodeValue,
					jenis: jenis,
					qty: qty,
				satuan_transaksi: satuanTransaksi,
				masa_expired: expired,
				is_new: isNew,
				new_satuan: satuanBesarNew,
				new_satuan_kecil: satuanKecilNew,
				new_konversi: konversiNew,
				new_stok_minimum: stokMinNew
			});
			$('#op_in_total').val('');
			$('#op_in_masa_expired').val('');
			renderOpInLines();
		});

	$(document).on('click', '.btn_op_in_remove', function(){
		var idx = parseInt($(this).data('index'), 10);
		if(!isNaN(idx)){ opInLines.splice(idx, 1); renderOpInLines(); }
	});

	function runBatchPost(lines, buildPayload, onDone){
		var i = 0;
		function next(){
			if(i >= lines.length){
				onDone(true);
				return;
			}
			var payload = buildPayload(lines[i]);
			i++;
			$.ajax({ url: 'simbhp/exaddbarang', method: 'POST', data: payload })
				.done(function(resp){
					if(resp && resp.status && resp.status.toString().toLowerCase() !== 'success'){
						onDone(false, resp && resp.message ? resp.message : 'Gagal menyimpan');
						return;
					}
					next();
				})
				.fail(function(){
					onDone(false, 'Request gagal');
				});
		}
		next();
	}

		$('#btn_op_in_commit').on('click', function(){
			if(!opInLines.length){
				$.toast({ heading: 'Info', text: 'Daftar barang masuk masih kosong', position: 'top-right', loaderBg: '#3b98b5', icon: 'info', hideAfter: 2500, stack: 1 });
				return;
			}
			var supplier = $('#op_in_supplier').val();
			var tanggal = $('#op_in_tanggal').val();
			var $btn = $(this);
			$btn.prop('disabled', true).text('Menyimpan...');

			var i = 0;
			function next(){
				if(i >= opInLines.length){
					$btn.prop('disabled', false).text('Simpan Semua Barang Masuk');
					$.toast({ heading: 'Success', text: 'Barang masuk berhasil disimpan', position: 'top-right', loaderBg: '#5ba035', icon: 'success', hideAfter: 2500, stack: 1 });
					opInLines = [];
					renderOpInLines();
					if(typeof window.gudangRefresh === 'function'){
						window.gudangRefresh();
					}
					return;
				}

				var line = opInLines[i];
				i++;

				function postPemasukan(){
					$.ajax({
						url: 'simbhp/exaddbarang',
						method: 'POST',
						data: {
							_token: token,
							set01: supplier,
							set02: line.jenis,
							set03: tanggal,
							set04: line.qty,
							set05: 'pemasukan',
							set06: '',
							set07: '',
							set08: '',
							set09: '',
							set10: '',
							set11: line.satuan_transaksi,
							set12: line.masa_expired
						}
					}).done(function(resp){
						if(resp && resp.status && resp.status.toString().toLowerCase() !== 'success'){
							$btn.prop('disabled', false).text('Simpan Semua Barang Masuk');
							$.toast({ heading: 'Gagal', text: (resp && resp.message) ? resp.message : 'Gagal menyimpan', position: 'top-right', loaderBg: '#bf441d', icon: 'error', hideAfter: 4500, stack: 1 });
							return;
						}
						next();
					}).fail(function(){
						$btn.prop('disabled', false).text('Simpan Semua Barang Masuk');
						$.toast({ heading: 'Gagal', text: 'Request gagal', position: 'top-right', loaderBg: '#bf441d', icon: 'error', hideAfter: 4500, stack: 1 });
					});
				}

				if(line.is_new){
					$.ajax({
						url: 'simbhp/exaddbarang',
						method: 'POST',
						data: {
							_token: token,
							set01: 'new',
							set02: line.jenis,
							set03: line.new_satuan,
							set04: line.new_konversi,
							set05: 'jenis',
							set06: line.kode,
							set07: '',
							set08: line.new_satuan_kecil,
							set09: line.new_konversi,
							set10: line.new_stok_minimum,
							set11: 'besar'
						}
					}).done(function(resp){
						if(resp && resp.status && resp.status.toString().toLowerCase() !== 'success'){
							$btn.prop('disabled', false).text('Simpan Semua Barang Masuk');
							$.toast({ heading: 'Gagal', text: (resp && resp.message) ? resp.message : 'Gagal membuat barang baru', position: 'top-right', loaderBg: '#bf441d', icon: 'error', hideAfter: 4500, stack: 1 });
							return;
						}
						postPemasukan();
					}).fail(function(){
						$btn.prop('disabled', false).text('Simpan Semua Barang Masuk');
						$.toast({ heading: 'Gagal', text: 'Request gagal', position: 'top-right', loaderBg: '#bf441d', icon: 'error', hideAfter: 4500, stack: 1 });
					});
				} else {
					postPemasukan();
				}
			}

			next();
		});

	renderOpInLines();
    $('#btnexportreport').click(function(){
		var bln = $('#cekbln').val();
		var thn = $('#cekthn').val();
		var url = "{{ route('reportBHPExport') }}" + "?bulan=" + encodeURIComponent(bln) + "&tahun=" + encodeURIComponent(thn);
		window.open(url, '_blank');
		return false;
	});
});
</script>
@endpush
