<?php

use yii\helpers\Html;
use yii\helpers\Url;
use yii\bootstrap\ActiveForm;
use kartik\select2\Select2;
use wbraganca\dynamicform\DynamicFormWidget;
use yii\web\JsExpression;
use common\models\Divisiprincipal;
use yii\helpers\ArrayHelper;
use kartik\depdrop\DepDrop;
use kartik\file\FileInput;
use common\models\Cabang;
use common\models\Expeditur;
use nota\models\Metodepembayaran;
use common\models\Sumberorder;
use yii\web\View;

$cabang = 1;
// $tempPath = ($cabang == 1) ? '@web/frontend/web/js/orb3jkzxigcmvxdwvzda' : '@web/js/orb3jkzxigcmvxdwvzda';
// $pathAsset = (Yii::$app->user->identity->cabang == 1) ? "@web/" : Yii::$app->params['WebUrl'];
// //$this->registerJsFile($pathAsset . "assets/js-all/sales-order/sales.js?v" . date('y.m.d'), ['position' => \yii\web\View::POS_END]);
// $this->registerJsFile($tempPath . "/template-s2.js?v".Yii::$app->params['versionRelease'], ['position' => View::POS_HEAD]);
// $this->registerJsFile($tempPath . "/wbraganca-init.js?v".Yii::$app->params['versionRelease'], ['depends' => [\yii\web\JqueryAsset::className()]]);
echo $this->registerJsFile("http://10.40.93.5/sarerea/sarerea/guru/nota/web/sales-kasir.js", ['depends' => [\yii\web\JqueryAsset::className()]]);

$searchSejenisUrl = Url::to(['so/search-sejenis']);
Yii::$app->params['id-enduser'] = 12121;
Yii::$app->params['id-sektor-enduser'] = 121323;
Yii::$app->params['id-alamat-enduser'] = 1223232;
// var_dump($modelsAddress);die;
?>
<!-- <script src="http://10.40.93.5/sarerea/sarerea/guru/nota/web/sales-kasir.js"></script> -->
<style>
    .padding-5 {
        padding-left: 5px !important;
        padding-right: 5px !important;
    }
</style>
<script>
    var id_login = "<?= Yii::$app->user->identity->id ?>";
</script>
<script>
    var nilaippn = "<?= $ppn->iPpn ?>";
</script>
<!-- Modal Produk Sejenis -->
<div class="modal fade" id="modal-sejenis" tabindex="-1" role="dialog" aria-labelledby="produkSejenisModal" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Produk Sejenis</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span>&times;</span>
        </button>
      </div>
      <div class="modal-body" id="produk-sejenis-content">
        <!-- Isi akan di-load AJAX -->
      </div>
      <div id="pagination-container-sejenis" class="text-center" style="margin-top: 10px;"></div>
    </div>
  </div>
</div>

<div class="customer-form">
    <?php $form = ActiveForm::begin(['id' => 'dynamic-form', 'options' => ['enctype' => 'multipart/form-data']]); ?>
    <?= $form->errorSummary($modelCustomer); ?>
    <div class="row">
        <div class="col-sm-12">
            <div class="">
                <!-- panel customerx -->
                <div class="panel panel-info">
                    <div class="panel-heading primary">
                        <h4 class="panel-title pull-right">
                            <a data-toggle="collapse" href="#customer-panel"><i class="fa fa-address-card"></i> Data
                                Pelanggan</a>
                        </h4>
                        <div class="clearfix"></div>
                    </div>
                    <div class="panel-body container-items panel-collapse  in" id="customer-panel">
                        <div class="row">
                            <div class="col-sm-6">
                                <?= $form->field($modelCustomer, 'vNama')->textInput([
                                    'placeholder' => 'Masukkan Nama',
                                ])->label('Nama Pelanggan') ?>
                            </div>
                            <div class="col-sm-6">
                                <?= $form->field($modelCustomer, 'vAddress2')->textInput([
                                    'placeholder' => 'Masukkan Alamat',
                                ]) ?>
                            </div>
                            <div class="col-sm-6">
                                <?= $form->field($modelCustomer, 'vPhone')->textInput([
                                    'placeholder' => 'Masukkan No. Telepon',
                                ]) ?>
                            </div>
                            <div class="col-sm-6">
                                <?= $form->field($modelCustomer, 'vKetBaru')->textInput(['maxlength' => true]) ?>
                            </div>
                            <div style="display:none;">   
                                <?= $form->field($modelCustomer, 'iPelangganId')->hiddenInput(['value'=>Yii::$app->params['id-enduser']])->label(false) ?>
                                <?= $form->field($modelCustomer, 'iSektorpelangganid')->hiddenInput(['id' => 'sektor-id','value'=>Yii::$app->params['id-sektor-enduser']])->label(false) ?>
                                <?= $form->field($modelCustomer, 'iAlamatpelangganid')->hiddenInput(['id' => 'alamat-id','value'=>Yii::$app->params['id-alamat-enduser']])->label(false) ?>
                                <?= $form->field($modelCustomer, 'iCabangid')->hiddenInput(['value'=>$cabang])->label(false) ?>
                                <?= $form->field($modelCustomer, 'iTOP')->hiddenInput(['value'=>1])->label(false) ?>
                                <?= $form->field($modelCustomer, 'eTipesektor')->hiddenInput(['id' => 'etipe','value'=>'Regular'])->label(false) ?>
                                <?= $form->field($modelCustomer, 'eJenisOrder')->hiddenInput(['value'=>'Cash'])->label(false) ?>
                                <?= $form->field($modelCustomer, 'eJenisOrder2')->hiddenInput(['value'=>'Cash'])->label(false) ?>
                                <?= $form->field($modelCustomer, 'eSumberOrder')->hiddenInput(['value'=>'Datang Langsung'])->label(false) ?>
                                <?= $form->field($modelCustomer, 'iExpedisi')->hiddenInput(['value'=>'4'])->label(false) ?>
                                <?= $form->field($modelCustomer, 'eBiayaRacik')->hiddenInput(['value'=>'Tidak'])->label(false) ?>
                                <?= $form->field($modelCustomer, 'iBiayakirim')->hiddenInput(['value'=>'0'])->label(false) ?>
                                <?= $form->field($modelCustomer, 'iBiayaracik')->hiddenInput(['value'=>'0'])->label(false) ?>
                                <span id="upload-id"></span>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- end of panel customer -->

                <div>
                    <div class="panel panel-primary">
                    <div class="panel-heading">
                        <div class="clearfix"></div>
                    </div>
                    <div class="panel-body container-items panel-collapse  in" id="detail-panel">
                        <div class="row align-items-end">
                            <div class="col-sm-8">
                                <div class="form-group">
                                    <label for="input-nama-barang">Cari Nama Barang :</label>
                                    <?= Html::textInput('nama_barang', '', [
                                        'id' => 'input-nama-barang',
                                        'class' => 'form-control',
                                        'placeholder' => 'Ketik nama barang ...'
                                    ]) ?>
                                </div>
                            </div>
                            <div class="col-sm-2">
                                <div class="form-group">
                                    <label>&nbsp;</label>
                                    <button class="btn btn-secondary btn-block" type="button" id="clear-search">Clear</button>
                                </div>
                            </div>
                        </div>

                        <div id="result-container">
                            <!-- Hasil pencarian akan muncul di sini -->
                        </div>
                        <div id="pagination-container" class="text-center" style="margin-top: 10px;"></div>
                    </div>
                </div>
            </div>

                <!-- styling line in detail -->
                <div class="col-sm-12">
                    <div class="line line-dashed"></div>
                </div>
                <input type="hidden" id="collect-id">
             

                 <?php DynamicFormWidget::begin([
    'widgetContainer' => 'dynamicform_wrapper',
    'widgetBody' => '.container-items',
    'widgetItem' => '.item',
    'limit' => 50,
    'min' => 1,
    'insertButton' => '.add-item',
    'deleteButton' => '.remove-item',
    'model' => $modelsAddress[0],
    'formId' => 'dynamic-form',
    'formFields' => [
        'barang',
        'qty',
        'harga',
        'total',
    ],
]); ?>
                <!-- panel detail barang -->
                 <button type="button" class="add-item btn btn-success">
        + Tambah Barang
    </button>
                <div class="panel panel-info">
                    <div class="panel-heading">
                        <h4 class="panel-title pull-right">
                            <a data-toggle="collapse" href="#detail-panel"><i class="fa fa-envelope" add-item></i> Detail
                                Barang</a>
                        </h4>
                        <div class="clearfix"></div>
                    </div>
                    <div class="panel-body container-items panel-collapse  in" id="detail-panel">
                        <!-- widgetContainer -->
                        <?php foreach ($modelsAddress as $index => $modelAddress) : ?>
                            <div class="item panel panel-default" style="border:none;">
                                <div class="panel-body" style="padding:10px;">
                                    <!-- // necessary for update action. -->
                                    <?= (!$modelAddress->isNewRecord) ? Html::activeHiddenInput($modelAddress, "[{$index}]iId") : null; ?>
                                    <div class="row">
                                        <div class="col-sm-3 padding-5">
                                            <div class="row">
                                                <div class="col-sm-1">
                                                    <!-- <b class="place-number"></b> -->
                                                </div>
                                                <div class="col-sm-11">
                                                    <input type="hidden" id="torderdt-<?= $index?>-ibarangid" class="form-control" name="Torderdt[<?= $index?>][iBarangId]" onchange="datakemasan(this.value,this.id)">
                                                    <input type="hidden" id="torderdt-<?= $index?>-golongan">
                                                    <div class="form-group field-torderdt-<?= $index?>-namabarang">
                                                        <label class="control-label" for="torderdt-<?= $index?>-namabarang">Nama Barang</label>
                                                        <input type="text" id="torderdt-<?= $index?>-namabarang" class="form-control" readonly/>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-sm-9">
                                            <div class="row">
                                                <div class="col-sm-1 padding-5">
                                                    <?= $form->field($modelAddress, "[{$index}]qty_stock")->textInput(['readonly' => true, 'data-input' => 'stock']) ?>
                                                </div>
                                                <div class="col-sm-2 padding-5">
                                                    <?= $form->field($modelAddress, "[{$index}]iKemasanpakaiid")->dropDownList(
                                                        [],
                                                        [
                                                            'prompt'        => 'Pilih Kemasan',
                                                            'onChange'      => 'hitungHarga(this.id,1)',
                                                            'data-input'    => 'kemasan'
                                                        ]
                                                    )
                                                    ?>
                                                </div>
                                                <div class="col-sm-4">
                                                    <div class="row">
                                                        
                                                        <div class="col-sm-4 padding-5">
                                                            <?= $form->field($modelAddress, "[{$index}]batch")->textInput(['readonly' => true, 'data-input' => 'stock'])->label('Batch') ?>
                                                        </div>
                                                        <div class="col-sm-4 padding-5">
                                                            <?= $form->field($modelAddress, "[{$index}]iQty")->textInput(['maxlength' => true, 'onChange' => 'hitungHarga(this.id,0)', 'data-input' => 'qty']) ?>
                                                        </div>
                                                        <div class="col-sm-4 padding-5">
                                                            <?= $form->field($modelAddress, "[{$index}]fDiscount")->textInput(['maxlength' => true, 'onChange' => 'hitungHarga(this.id,0)']) ?>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="col-sm-4">
                                                    <div class="row">                                                        
                                                        <div class="col-sm-4 padding-5">
                                                            <?= $form->field($modelAddress, "[{$index}]fHargaJual")->widget(\yii\widgets\MaskedInput::className(), [
                                                                'options' => [
                                                                    'readonly' => true,
                                                                    'class' => 'form-control',
                                                                    'onChange' => 'hitungHarga(this.id,9)',
                                                                    'data-input' => 'hna',
                                                                    'data-number' => 0
                                                                ],
                                                                'clientOptions' => [
                                                                    'readonly' => true,
                                                                    'alias' => 'decimal',
                                                                    'digits' => 2,
                                                                    'text-Align' => 'left',
                                                                    'digitsOptional' => true,
                                                                    //'radixPoint' => ',',
                                                                    'groupSeparator' => '.',
                                                                    'autoGroup' => true,
                                                                    'removeMaskOnSubmit' => true,
                                                                ],
                                                            ]) ?>
                                                        </div>
                                                        <div class="col-sm-4 padding-5">
                                                            <?= $form->field($modelAddress, "[{$index}]fTotal")->widget(\yii\widgets\MaskedInput::className(), [
                                                                'options' => [
                                                                    'readonly' => true,
                                                                    'class' => 'form-control',
                                                                    'data-input' => 'total',
                                                                    'data-number' => 0
                                                                ],
                                                                'clientOptions' => [
                                                                    'alias' => 'decimal',
                                                                    'digits' => 2,
                                                                    'text-Align' => 'left',
                                                                    'digitsOptional' => true,
                                                                    //'radixPoint' => ',',
                                                                    'groupSeparator' => '.',
                                                                    'autoGroup' => true,
                                                                    'removeMaskOnSubmit' => true,
                                                                ],
                                                            ]) ?>
                                                            <input type="hidden" id="torderdt-<?= $index?>-ppn">
                                                        </div>
                                                        <div class="col-sm-2 padding-5">
                                                            <button type="button"
                                                                class="pull-right remove-item btn btn-danger btn-xs"
                                                                style="margin-top:30px;">
                                                                <i class="fa fa-minus"></i>
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <div class="panel-footer text-right" style="display:block;">
                        <button type="button" class="pull-left add-item btn btn-success btn-xs"><i
                                class="fa fa-plus"></i></button>
                        <div class="clearfix"></div>
                    </div>
                </div>
                <!-- end of panel detail barang -->

                <!-- Resep -->
                <div class="panel panel-success">
                    <div class="panel-heading">
                        <h4 class="panel-title pull-left">
                            <a data-toggle="collapse" href="#resepx"><i
                                    class="fa fa-dollar-sign"></i> Resep</a>
                        </h4>
                        <div class="clearfix"></div>
                    </div>
                    <div class="panel-body container-item panel-collapse collapse in" id="resepx">
                        <div class="row">
                            <div class="col-md-3">
                                <?= $form->field($modelCustomer, 'eResepdokter')->dropDownList(
                                    ['Tidak' => 'Tidak', 'Ya' => 'Ya'],
                                    [
                                        'prompt' => 'Pilih',
                                        'id' => 'resep-id',
                                        'onChange' => 'showUpload(this.value)'
                                    ]
                                ) ?>
                            </div>
                        </div>
                    </div> 
                </div>

                <!-- panel summary harga -->
                <div class="panel panel-success">
                    <div class="panel-heading">
                        <h4 class="panel-title pull-right">
                            <a data-toggle="collapse" href="#summary-panel"><i class="fa fa-dollar-sign"></i> Ringkasan
                                Harga</a>
                        </h4>
                        <div class="clearfix"></div>
                    </div>
                    <div class="panel-body container-item panel-collapse collapse in" id="summary-panel">
                        <div class="row">
                            <div class="col-md-6">
                                
                                <?php
                                    $aman  = ArrayHelper::map(Metodepembayaran::find()->where(['eDeleted' => 'Tidak'])->andWhere(['like', 'iKasir', '1'])->all(), 'vNama', 'vNama');
                                ?>
                                <div class="col-sm-6">
                                <?= $form->field($modelCustomer, 'eBayar')->dropDownList(
                                    $aman,
                                    [
                                        'prompt' => 'Pilih Metode Pembayaran',
                                        'onChange' => 'sumberOrder(this.value);',
                                    ]
                                );
                                ?>
                                </div>
                                <div id="tunai" style="display:none;">
                                    <div class="col-sm-3">
                                        <?= $form->field($modelCustomer, 'dUangDiterima')->textInput([
                                            'placeholder' => 'Masukkan Uang Diterima',
                                            'id' => 'uang-diterima',
                                            //'onkeyup' => 'hitungKembalian()',
                                        ])->label('Uang Diterima') ?>
                                    </div>
                                    
                                    <div class="col-sm-3">
                                        <?= $form->field($modelCustomer, 'dKembalian')->textInput([
                                            'placeholder' => 'Hasil Kembalian',
                                            'id' => 'kembalian',
                                            'readonly' => true
                                        ])->label('Kembalian') ?>
                                    </div>
                                </div>
                            </div>
                                
                            <div class="col-md-6" style="font-size:16px; font-weight: bold;">
                                <br>
                                <!-- total divs -->
                                <div class="col-md-7">
                                    <span class="pull-right">Total Harga : </span>
                                    <?= $form->field($modelCustomer, 'fHargaHPP')->hiddenInput(['id' => 'total-form'])->label(false); ?>
                                </div>
                                <div class="col-md-4">
                                    <span id="total-all" class="pull-right">-</span>
                                </div>
                                <!-- PPN divs -->
                                <div class="col-md-7">
                                    <span class="pull-right">PPN <?= $ppn->iPpn ?>% : </span>
                                    <?= $form->field($modelCustomer, 'fTotalPPN')->hiddenInput(['id' => 'ppn-form'])->label(false); ?>
                                </div>
                                <div class="col-md-4">
                                    <span id="ppn-all" class="pull-right">-</span>
                                </div>
                                <div style="display:none">
                                    <!-- biaya kirim divs -->
                                    <div class="col-md-8">
                                        <span class="pull-right">Biaya Kirim : </span>
                                        <?= $form->field($modelCustomer, 'iBiayakirim')->hiddenInput(['id' => 'kirim-form'])->label(false); ?>
                                    </div>
                                    <div class="col-md-3">
                                        <span id="biaya-kirim">-</span>
                                    </div>
                                    <!-- biaya racik divs -->
                                    <div class="col-md-8">
                                        <span class="pull-right">Biaya Racik : </span>
                                        <?= $form->field($modelCustomer, 'iBiayaracik')->hiddenInput(['id' => 'racik-form'])->label(false); ?>
                                    </div>
                                    <div class="col-md-3">
                                        <span id="biaya-racik">-</span>
                                    </div>
                                </div>
                                <!-- grand total all divs -->
                                <div class="col-md-7">
                                    <span class="pull-right">Total : </span>
                                    <?= $form->field($modelCustomer, 'iTotal')->hiddenInput(['id' => 'grandtotal-form'])->label(false); ?>
                                </div>
                                <div class="col-md-4">
                                    <span id="grandtotal-all" class="pull-right">-</span>
                                    <br><br>
                                </div>
                                <div class="col-sm-7" id="tunai2" style="display:none;">
                                    <span class="pull-right">Penyesuaian : </span>
                                </div>
                                <div class="col-sm-4" id="tunai3" style="display:none;">
                                    <?= $form->field($modelCustomer, 'dPenyesuaian')->textInput([
                                        'placeholder' => 'Masukkan Penyesuaian',
                                        'id' => 'penyesuaian',
                                        'readonly' => true,
                                        'style' => 'text-align: right;',
                                    ])->label(false) ?>
                                </div>
                        </div>          
                    </div>
                </div>            
                <!-- end of panel summary harga -->
                <?php DynamicFormWidget::end(); ?>
                <!-- action button -->
                <div class="form-group pull-right">
                    <?= Html::a('<i class="fa fa-arrow-circle-left "></i> Kembali', ['listkasir'], ['class' => 'btn btn-warning']) ?>
                    <?= Html::submitButton($modelAddress->isNewRecord ? '<i class="fa fa-save "></i> Simpan' : 'Ubah', ['class' => 'btn btn-primary', 'id' => 'submit-button', 'data-toggle' => 'modal', 'data-target' => '#exampleModalCenter']) ?>
                </div>
            </div>
        </div>
    </div>
    <?php ActiveForm::end(); ?>
</div>
<script>
    const baseCU = '/salesorder';
    document.addEventListener("DOMContentLoaded", function(event) {
        $('.kv-plugin-loading').hide();
        $('#salesorder-iKemasanpakaiid').attr('readonly', true);
        $('#upload-id').hide();

        setnumber('kirim');
        setnumber('racik');

        $('#torderhd-ibiayaracik').keyup(function() {
            var val = $(this).val();
            var condition = (val.length > 0) ? val : '-';
            $('#biaya-racik').html(condition);
            $('#racik-form').val(condition);
            helper.grandTotal();
        });

        $('#submit-button').click(function(event) {
            var nama_user = $('#torderhd-vnama').val().toLowerCase();
            var msg = '';

            const elements = document.querySelectorAll('[id*="golongan"]');
            elements.forEach(element => {
                if(element.value == 'Keras' && (nama_user == '' || nama_user == 'end user')){
                    msg += 'Terdapat Obat Keras, Mohon isi nama pelanggan ';
                }
            });


            if (msg !== '') {
                alert(msg);
                return false;
            }

            return true;
        });

        $('#torderhd-ibiayakirim').keyup(function() {
            var val = $(this).val();
            var condition = (val.length > 0) ? val : '-';
            $('#biaya-kirim').html(condition);
            $('#kirim-form').val(condition);
            helper.grandTotal();
        });

        $(".dynamicform_wrapper").on("afterDelete", function(e, item) {
            let serialNumber = $('.place-number').length
            if (serialNumber > 0) {
                $('.item.panel').each(function(k) {
                    $('.place-number').eq(k).text(k + 1)
                })
            }
        });

        $('#torderhd-vnama').on('input', function () {
            this.value = this.value.toUpperCase();
        });

        $('#torderhd-vaddress2').on('input', function () {
            this.value = this.value.toUpperCase();
        });

        $('#torderhd-vketbaru').on('input', function () {
            this.value = this.value.toUpperCase();
        });

        $(document).on('click', '.remove-item', function (event) {
            let id = (this.parentElement.previousElementSibling.childNodes[1].className).replace('form-group field-','');
            let index = id.split('-');
            hitungUlang(index[1]);
        });
    });

    function sumberOrder(val) {
        if (val == "TUNAI") {
            $('#tunai').show();
            $('#tunai2').show();
            $('#tunai3').show();
        }else{
            $('#tunai').hide();
            $('#tunai2').hide();
            $('#tunai3').hide();
        }
    }

    function setnumber(id) {
        var num = 0;
        $('#torderhd-ibiaya' + id).val(num);
        $('#biaya-' + id).html(num);
        $('#' + id + '-form').val(num);
    }

    function showUpload(val) {
        if (val == 'Ya') {
            $('#upload-id').show();
        } else if (val == 'Tidak') {
            $('#upload-id').hide();
        }
    }

    function datakemasan(val, id) {
        var url = "<?= \yii\helpers\Url::to(['kemasan']) ?>";
        var id_kemasan = id.replace('ibarangid', 'ikemasanpakaiid');
        var id_hargajual = id.replace('ibarangid', 'fhargajual');
        var diskon_id = id.replace('ibarangid', 'fdiscount');
        var stock_id = id.replace('ibarangid', 'qty_stock');
        var batch = id.replace('ibarangid', 'batch');
        var id_golongan = id.replace('ibarangid', 'golongan');

        $.ajax({
            url: url,
            type: 'GET',
            data: {
                'id_barang': val,
            },
            dataType: 'json',
            success: function(res) {
                if (res.status) {
                    $('#' + diskon_id).attr('readonly', false);

                    var option = '';
                    let chooseSelected = "";
                    for (var i = 0; i < res.data.length; i++) {
                        var split = res.data[i].id.split('|');
                        if(i == 0){
                            chooseSelected = res.data[i].id;
                        }
                        option += '<option value="' + res.data[i].id + '">' + res.data[i].text +
                            '</option>';
                    }


                    $('#' + id_kemasan).attr('disabled', false);
                    $('#' + id_kemasan).html(option);

                    $('#'+stock_id).attr('data-besar', res.stock.besar)
                    $('#'+stock_id).attr('data-kecil', res.stock.kecil)

                    let tempKemasan = $('#' + id_kemasan).val()
                    if (tempKemasan != 'Pilih Kemasan' && tempKemasan !== null) {
                        let splitKemasan = tempKemasan.split('|')
                        if (splitKemasan[1] == 1) {
                            $('#'+stock_id).val(res.stock.besar)
                        } else {
                            $('#'+stock_id).val(res.stock.kecil)
                        }
                    }

                    $('#'+batch).val(res.stock.batch);
                    if(chooseSelected){
                        $('#' + id_kemasan).val(chooseSelected).trigger('change');
                    }

                    $('#'+id_golongan).val(res.info.eGolongan);
                }
            },
            error: function(request, error) {
                alert("Request: " + JSON.stringify(request));
            }
        });
    }

    function hitungHarga(id, from) {
        var urldetailbarang = "<?= \yii\helpers\Url::to(['detailbarang']) ?>";
        var indexMatch = id.match(/\d+/);
        if (!indexMatch) return;
        var index = indexMatch[0];

        if (from == 1) {
            var stock_id = id.replace('ikemasanpakaiid', 'qty_stock');
            var stockB = $('#'+stock_id).attr('data-besar')
            var stockK = $('#'+stock_id).attr('data-kecil')
    
            let tempKemasan = $('#' + id).val();
            if (tempKemasan != 'Pilih Kemasan' && tempKemasan !== null) {
                let splitKemasan = tempKemasan.split('|')
                if (splitKemasan[1] == 1) {
                    $('#'+stock_id).val(stockB)
                } else {
                    $('#'+stock_id).val(stockK)
                }
            }
        }

        var kemasanPakai = $('#torderdt-' + index + '-ikemasanpakaiid').val();
        var qty = $('#torderdt-' + index + '-iqty').val();
        var idbarang = $('#torderdt-' + index + '-ibarangid').val();
        let persendiskon = ($('#torderdt-' + index + '-fdiscount').val() != "") ? $('#torderdt-' + index + '-fdiscount').val() : 0;

        $.ajax({
            url: urldetailbarang,
            type: 'GET',
            data: {
                'id_barang': idbarang,
                'diskon': persendiskon,
                'kemasanpakai': kemasanPakai,
                'qty':qty
            },
            dataType: 'json',
            success: function(res) {
                if (res.status) {
                    $('#torderdt-' + index + '-fhargajual').val(res.data.hargajual);
                    $('#torderdt-' + index + '-ftotal').val(res.data.total);
                    $('#torderdt-' + index + '-ppn').val(res.data.ppn);
                    helper.grandTotal();
                }
            }
        });

    }

    /* helper untuk reusable code */
    helper = {
        grandTotal: function() {
            const elements = document.querySelectorAll('[id*="ibarangid"]');
            let totalHPP = 0;
            let totalPPN = 0;
            let listidbarang = [];

            if(elements.length > 0){
                for(let i = 0; i < elements.length; i++){
                    var id = elements[i].id;
                    var value_barang = elements[i].value;

                    totalHPP = totalHPP + parseFloat(
                        ($('#'+id.replace('ibarangid', 'ftotal')).val()).replace(',','')
                    );
                    totalPPN = totalPPN + parseFloat(
                        ($('#'+id.replace('ibarangid', 'ppn')).val()).replace(',','')
                    );
                    listidbarang.push(value_barang.toString());
                }
            }

            $('#collect-id').val(listidbarang.join('|'));

            totalHPP = totalHPP.toFixed(2);
            totalPPN = totalPPN.toFixed(2);

            $('#total-all').html(helper.numberWithCommas(totalHPP));
            $('#total-form').val(totalHPP);

            $('#ppn-all').html(helper.numberWithCommas(totalPPN));
            $('#ppn-form').val(totalPPN);

            var biayaRacik = (helper.valueToNumber($('#racik-form').val())) ? helper.valueToNumber($('#racik-form')
                .val()) : 0;
            var biayaKirim = (helper.valueToNumber($('#kirim-form').val())) ? helper.valueToNumber($('#kirim-form')
                .val()) : 0;

            var grandTotal = helper.rounding(helper.valueToNumber(totalHPP) + helper.valueToNumber(totalPPN));

            var all = helper.rounding(biayaRacik + biayaKirim + grandTotal);

            $('#grandtotal-all').html(helper.numberWithCommas(all.toFixed(2)));
            $('#grandtotal-form').val(all.toFixed(2));
            var penyesuaian;
            var kelipatan = 100;
            var sisa = all % kelipatan;

            if (sisa >= 50) {
                // Naik ke kelipatan berikutnya
                penyesuaian = all + (kelipatan - sisa);
            } else {
                // Turun ke kelipatan sebelumnya
                penyesuaian = all - sisa;
            }

            $('#penyesuaian').val(penyesuaian);
        },

        numberWithCommas: function(number) {
            return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        },

        valueToNumber: function(string) {
            return parseFloat(string.replace(',', ''));
        },

        rounding: function(float) {
            return Math.ceil(float);
        },

        floor: function(float) {
            return Math.floor(float);
        },

        rand: function() {
            var rand = "<?php echo (isset($_GET['uid']) && $_GET['uid']) ? $_GET['uid'] : ''; ?>";
            return rand;
        },
    }


    function deleteDynamicItem(divElement = false, inputElement = "", qty = false) {
        //  
    }

    function hitungUlang(index) {
        helper.grandTotal();
    }
</script>
<script>
let barangRow;
let baseUrlLocation = window.location.href.split("/");
// alert(baseUrlLocation);
console.log(baseUrlLocation);

let baseUrlKasir = baseUrlLocation
  .map((_, index) =>
    index < baseUrlLocation.length - 1 ? baseUrlLocation[index] : null
  )
  .filter((item) => item !== null)
  .join("/");
let baseUrlPL = baseUrlLocation
  .map((_, index) =>
    index < baseUrlLocation.length - 2 ? baseUrlLocation[index] : null
  )
  .filter((item) => item !== null)
  .join("/");

const pathONKasir = {
  createUrl: function (path = null, params = null) {
    let url = baseUrlKasir + "/" + path;

    if (typeof params === "object" && params !== null) {
      if (Object.keys(params).length > 0) {
        url += "?";
        $.each(params, function (key, value) {
          url += `${key}=${encodeUrl(value)}&`;
        });
      }
    }
    return trims(url, "&");
  },
  createUrlPl: function (path = null, params = null) {
    let url = baseUrlPL + "/" + path;

    if (typeof params === "object" && params !== null) {
      if (Object.keys(params).length > 0) {
        url += "?";
        $.each(params, function (key, value) {
          url += `${key}=${encodeUrl(value)}&`;
        });
      }
    }
    return trims(url, "&");
  },
};

(function () {
  let currentKeyword = "";
  let currentBarangName = "";

  function loadBarang(page = 1) {
    if (currentKeyword.length < 2) return;

    const url = pathONKasir.createUrl("search");

    $.get(url, { q: currentKeyword, page: page }, function (res) {
      $("#result-container").html(res.html);
      $("#pagination-container").html(res.pagination);
    });
  }

  function toggleClearButton() {
    if ($("#input-nama-barang").val().length > 0) {
      // $('#clear-search').show();
    } else {
      // $('#clear-search').hide();
    }
  }

  function cariProdukSejenis(iId, namaBarang) {
    currentKeyword = iId;
    currentBarangName = namaBarang;
    loadBarangSejenis(1);
    $("#modal-sejenis").modal("show");
  }

  function loadBarangSejenis(page = 1) {
    if (currentKeyword.length < 2) return;

    const url = pathONKasir.createUrl("search-sejenis");

    $.get(url, { q: currentKeyword, page: page }, function (res) {
      $("#produk-sejenis-content").html(res.html);
      $("#pagination-container-sejenis").html(res.pagination);
      $("#modal-sejenis .modal-title").html(
        "Produk Sejenis - <strong>" + currentBarangName + "</strong>"
      );
    }).fail(function () {
      $("#produk-sejenis-content").html(
        '<p class="text-danger">Gagal memuat produk sejenis.</p>'
      );
      $("#pagination-container-sejenis").empty();
    });
  }

  function setBarangToAdd(barang) {
    if (isBarangAlreadyAdded(barang.iBarangId.toString())) {
      barangRow = "";
      swal({
        icon: "warning",
        title: "Oops...",
        text: "Barang sudah ada di list!",
        confirmButtonColor: "#3085d6",
      });
      return false;
    } else {
      barangRow = barang;
      var id_barang = $("#collect-id").val();

      if (id_barang) {
        var split = id_barang.split("|");
        split.push(barang.iBarangId.toString());
        var joined = split.join("|");
        $("#collect-id").val(joined);
      } else {
        $("#collect-id").val(barang.iBarangId.toString());
      }
      // ðŸ”¹ Trigger tambah row (INI TERAKHIR)
      $(".panel-info .add-item").trigger("click");
    }
  }

  function setBarangToAdd2(barang) {
    if (isBarangAlreadyAdded(barang.iBarangId)) {
      swal({
        icon: "warning",
        title: "Oops...",
        text: "Barang sudah ada di list!",
        confirmButtonColor: "#3085d6",
      });
      return;
    }

    $(".panel-info .add-item").click();

    setTimeout(function () {
      let $lastItem = $(".dynamicform_wrapper .item").last();
      let $selectProduk = $lastItem.find('[data-input="produk"]');

      // Tambahkan jika belum ada
      if (
        $selectProduk.find("option[value='" + barang.iBarangId + "']")
          .length === 0
      ) {
        let newOption = new Option(barang.vNama, barang.iBarangId, true, true);
        $selectProduk.append(newOption).trigger("change");
      } else {
        $selectProduk.val(barang.iBarangId).trigger("change");
      }

      $lastItem.find('[data-input="stok"]').val(barang.stok);
      $lastItem.find('[data-input="harga"]').val(barang.harga_jual);
      $lastItem.find('[data-input="kemasan"]').val(barang.iKemasanId);

      // âœ… Simpan eGolongan di elemen
      $lastItem.attr("data-golongan", barang.eGolongan || "");

      // âœ… Jika golongan keras, set resep ke "Ya"
      if (barang.eGolongan === "Keras") {
        $("#resep-id").val("Ya").trigger("change");
      }

      // âª Cek ulang apakah masih ada "Keras" di semua item
      cekGolonganKeras();
      // Alert sukses elegan
      swal({
        title: "Berhasil!",
        text: barang.vNama + " berhasil ditambahkan.",
        type: "success",
        html: true,
        timer: 1500,
        showConfirmButton: false,
      });
    }, 100);
  }

  // Event klik tombol hapus di tiap item
  $(document).on("click", ".remove-item", function () {
    let $item = $(this).closest(".item");
    let namaBarang = $item.find('[data-input="produk"] option:selected').text();

    $item.remove();

    // Cek ulang golongan keras
    cekGolonganKeras();

    swal({
      title: "Dihapus!",
      text: (namaBarang || "Barang") + " berhasil dihapus.",
      type: "success",
      timer: 1500,
      showConfirmButton: false,
    });
  });

  function cekGolonganKeras() {
    let adaKeras = false;

    $(".dynamicform_wrapper .item").each(function () {
      let golongan = $(this).attr("data-golongan");
      if (golongan === "Keras") {
        adaKeras = true;
        return false; // break loop
      }
    });

    let $vNama = $("#torderhd-vnama");
    let $label = $('label[for="torderhd-vnama"]');

    if (adaKeras) {
      $("#resep-id").val("Ya").trigger("change");
      $("#upload-idx").css("display", "block");

      $vNama.attr("required", true);

      if ($vNama.val().trim() === "") {
        // kosong â†’ merah + teks
        $vNama.addClass("border-danger animate__animated animate__pulse");
        if ($label.find("span.text-danger").length === 0) {
          $label
            .css("color", "#d9534f")
            .append(' <span class="text-danger fw-bold">(wajib diisi)</span>');
        }
      } else {
        // sudah ada isi â†’ hilangkan merah + teks
        $vNama.removeClass("border-danger animate__animated animate__pulse");
        $label.css("color", "").find("span.text-danger").remove();
      }

      // listener input sekali saja
      if (!$vNama.data("listener")) {
        $vNama.on("input change", function () {
          if ($(this).val().trim() !== "") {
            $(this).removeClass(
              "border-danger animate__animated animate__pulse"
            );
            $label.css("color", "").find("span.text-danger").remove();
          } else {
            $(this).addClass("border-danger animate__animated animate__pulse");
            if ($label.find("span.text-danger").length === 0) {
              $label
                .css("color", "#d9534f")
                .append(
                  ' <span class="text-danger fw-bold">(wajib diisi)</span>'
                );
            }
          }
        });
        $vNama.data("listener", true);
      }
    } else {
      $("#resep-id").val("Tidak").trigger("change");
      $("#upload-idx").css("display", "none");

      $vNama
        .removeAttr("required")
        .removeClass("border-danger animate__animated animate__pulse");
      $label.css("color", "").find("span.text-danger").remove();
    }
  }

  function isBarangAlreadyAdded(iBarangId) {
    let exists = false;

    var id_barang = $("#collect-id").val();
    if (id_barang) {
      var split = id_barang.split("|");
      if (split.indexOf(iBarangId) !== -1) {
        return true;
      }
    }
    return exists;
  }

  function parseNumber(val) {
    val = val.toString().replace(/[^0-9.-]/g, "");
    return parseFloat(val) || 0;
  }

  function hitungKembalian() {
    var uang = parseNumber($("#uang-diterima").val());
    var penyesuaian = parseNumber($("#penyesuaian").val());
    var hasil = uang - penyesuaian;
    $("#kembalian").val(hasil.toFixed(2));
  }

  $(document).ready(function () {
    $("#uang-diterima, #penyesuaian").on("keyup change", function () {
      hitungKembalian();
    });

    $("#input-nama-barang").on("keyup", function () {
      currentKeyword = $(this).val();
      toggleClearButton();
      loadBarang(1);
    });

    $("#clear-search").on("click", function () {
      $("#input-nama-barang").val("");
      currentKeyword = "";
      $("#result-container").html("");
      $("#pagination-container").html("");
      toggleClearButton();
    });

    // Tangani klik pada pagination
    $(document).on("click", ".page, .page-next, .page-prev", function (e) {
      e.preventDefault();
      const page = $(this).data("page");
      loadBarang(page);
    });

    $(document).on("click", ".pagination-ajax-sejenis a", function (e) {
      e.preventDefault();
      let page = $(this).data("page");
      loadBarangSejenis(page);
    });

    toggleClearButton();

    $(document).on("click", ".remove-item", function () {
      setTimeout(() => {
        cekGolonganKeras();
      }, 100);
    });

    if (typeof tipeChanel === "function") {
      tipeChanel(78150);
    }
  });

  // Ekspor fungsi ke global scope agar bisa dipanggil dari HTML
  window.cariProdukSejenis = cariProdukSejenis;
  window.setBarangToAdd = setBarangToAdd;

  $(document).on(
    "select2:opening",
    '[data-input="produk"][readonly]',
    function (e) {
      e.preventDefault(); // blok user membuka select2 jika readonly
    }
  );
})();

//CREATE PL
function validateStock() {
  let flag = true;

  $('.item').each(function () {
    let qty = parseInt($(this).find('[data-input="qty"]').val()) || 0;

    // khusus qty stock â€” bukan batch
    let stock = parseInt(
      $(this).find('input[id$="qty_stock"]').val()
    ) || 0;

    // console.log(qty, stock);

    if (qty > stock) {
      flag = false;
      return false;
    }
  });

  $("#btn-check-out").prop("disabled", !flag);
}


function onLoadingPage() {
  calert.info("Sedang memuat data...\nMohon menunggu...", false);

  setTimeout(() => {
    calert.close(); // atau calert.success('Data berhasil dimuat');
  }, 1000); // tutup alert setelah 1 detik
}

function showModalCheckout() {
  let obj = url2Obj();
  let param = {};
  param[yii.getCsrfParam()] = yii.getCsrfToken();

  let url = pathONKasir.createUrl("check-pl", { id: obj.id });
  let params = ajaxParams(url, "POST", param);

  $.ajax(params).done(function (response) {
    if (response.status) {
      let dataH = response.data.header;
      let dataD = response.data.details;

      swal.close();

      // Header info
      $("#co-invoice").text(dataH.invoice);
      $("#co-tgl-order").text(dataH.tanggal);
      $("#co-nama").text(dataH.nama);
      $("#co-alamat").text(dataH.alamat);
      $("#co-catatan").text(dataH.catatan);
      $("#co-keterangan").text(dataH.keterangan);
      $("#co-expedisi").text(dataH.expedisi);

      //alert(dataD.length);
      // Detail produk table
      if (dataD.length > 0) {
        let tBody = createHTML.tableBody(dataD, {
          autoNumber: true,
          coloums: [
            { label: "hna", format: "number" },
            { label: "total", format: "number" },
          ],
          footer: {
            total: "total",
            ppn: mppn,
            // kirim: dataH.kirim,
            // racik: dataH.racik,
            grandtotal: true,
          },
        });
        $("#co-detail-produk").html(tBody);
      }

      // Tampilkan modal
      //$('#modalCheckout').modal({ backdrop: 'static', keyboard: false });
      $("#modalCheckout").modal("show");

      // Set tombol link
      $("#co-edit-batch").attr(
        "href",
        pathONKasir.createUrlPl("pl/update", { id: dataH.id })
      );
      //$('#co-create-invoice').attr('href', pathON.createUrl('/pl/confirm', { id: dataH.id }));
      $("#cancel-invoice").replaceWith(`
                <button id="cancel-invoice" type="button" class="btn btn-danger" onclick="konfirmasiClose(${dataH.id})">
                    <i class="fa fa-ban"></i> Cancel Invoice
                </button>
            `);
      $("#co-create-invoice").replaceWith(`
                <button id="co-create-invoice" type="button" class="btn btn-success" onclick="konfirmasiCheckout(${dataH.id})">
                    <i class="fa fa-check"></i> Create Invoice
                </button>
            `);
    } else {
      calert.error(response.error);
    }
  });
}

function konfirmasiCheckout(id) {
  calert.info("Mengkonfirmasi dan membuat invoice ...", false);

  const param = {};
  param[yii.getCsrfParam()] = yii.getCsrfToken();

  $.ajax({
    url: pathONKasir.createUrlPl("pl/confirm-kasir", { id: id }),
    method: "POST",
    data: param,
    dataType: "json", // pastikan ini agar jQuery hanya proses jika valid JSON
    success: function (res) {
      console.log("Response sukses:", res);
      swal.close(); // pastikan swal ditutup di semua kondisi
      if (res.status) {
        if (res.redirect) {
          window.location.href = res.redirect;
        } else {
          // Reload halaman jika tidak ada URL redirect
          location.reload();
        }
        localStorage.setItem("showModalCheckoutAfterReload", id);
        location.reload();
      } else {
        calert.error(res.message || "Gagal konfirmasi.");
      }
    },
    error: function (xhr) {
      swal.close();

      let message = "...";
      if (xhr.responseText) {
        try {
          const json = JSON.parse(xhr.responseText);
          message = json.message || message;
        } catch (e) {
          message = xhr.responseText; // fallback jika response bukan JSON
        }
      }

      console.log("Server Error:", xhr.responseText); // bantu debug
      calert.error(message);
    },
  });
}

function konfirmasiClose(id) {
  calert.info("Mengkonfirmasi dan membuka checkout...", false);

  const param = {};
  param[yii.getCsrfParam()] = yii.getCsrfToken();

  $.ajax({
    url: pathONKasir.createUrlPl("pl/close-kasir", { id: id }),
    method: "POST",
    data: param,
    success: function (res) {
      if (res.status) {
        // Sukses konfirmasi, reload lalu tampilkan modalCheckout
        swal.close();

        // Reload halaman dan tampilkan modal setelah reload selesai
        localStorage.setItem("showModalCheckoutAfterReload", id);
        location.reload();
      } else {
        calert.error(res.error || "Gagal konfirmasi.");
      }
    },
    error: function () {
      calert.error("Gagal menghubungi server.");
    },
  });
}

document.addEventListener("DOMContentLoaded", function (event) {
  // $(document).ready(function () {
  //   const id = localStorage.getItem("showModalCheckoutAfterReload");
  //   if (id) {
  //     localStorage.removeItem("showModalCheckoutAfterReload");
  //     showModalCheckout(id); // Fungsi ini memanggil modalCheckout dan ambil data
  //   }
  // });

  const dynamicFormWrapper = document.querySelector(".dynamicform_wrapper");
  const containerItems = dynamicFormWrapper.querySelector(".container-items");

  const observer = new MutationObserver(function (mutationsList, observer) {
    mutationsList.forEach(function (mutation) {
      if (mutation.type === "childList") {
        mutation.addedNodes.forEach(function (addedNode) {
          // Check if the added node is a row (item)
          if (addedNode.classList && addedNode.classList.contains("item")) {
            let row = $(addedNode);
            const namabarang = addedNode.querySelector(
              'input[id*="namabarang"]'
            );
            const idbarang = addedNode.querySelector('input[id*="ibarangid"]');

            namabarang.value = barangRow.vNama;
            idbarang.value = barangRow.iBarangId;
            $(idbarang).trigger("change");

            // Fill other fields
            row.find('[data-input="stok"]').val(barangRow.stok || 0);
            row.find('[data-input="harga"]').val(barangRow.harga_jual || 0);

            // Store the golongan data
            row.attr("data-golongan", barangRow.eGolongan || "");

            // If golongan is "Keras", set resep = "Ya"
            if (barangRow.eGolongan === "Keras") {
              $("#resep-id").val("Ya").trigger("change");
            }

            // Re-check all items if function `cekGolonganKeras` exists
            if (typeof cekGolonganKeras === "function") {
              cekGolonganKeras();
            }

            // Show success alert
            swal({
              title: "Berhasil!",
              text: barangRow.vNama + " berhasil ditambahkan.",
              type: "success",
              timer: 1200,
              showConfirmButton: false,
            });
          }
        });
      }
    });
  });

  // Configure the observer to watch for child additions inside the container
  observer.observe(containerItems, {
    childList: true, // Observe direct children (added or removed)
    subtree: true, // Observe all descendants
  });

  $("#btn-check-out").click(function (e) {
    var nama_user = $("#torderhd-vnama").val().toLowerCase();
    var msg = "";

    const elements = document.querySelectorAll('[id*="golongan"]');
    elements.forEach((element) => {
      if (
        element.value == "Keras" &&
        (nama_user == "" || nama_user == "end user")
      ) {
        msg += "Terdapat Obat Keras, Mohon isi nama pelanggan ";
      }
    });

    if (msg !== "") {
      alert(msg);
      $(this).attr("disabled", false);
      return false;
    }

    swal({
      title: "MDC Says",
      text: "Lanjutkan order berikut, Akan membuat PL ? \n Jika ada perubahan data, update terlebih dahulu!",
      icon: "warning",
      closeOnClickOutside: false,
      buttons: {
        cancel: true,
        confirm: "Next",
      },
    }).then((willApprove) => {
      if (willApprove) {
        calert.info("Sedang mengirim data...", false);
        let obj = url2Obj();
        let param = {};
        param[yii.getCsrfParam()] = yii.getCsrfToken();
        let params = ajaxParams(
          pathONKasir.createUrl("check-out", { id: obj.id }),
          "POST",
          param
        );
        $.ajax(params).done(function (response) {
          if (response.status) {
            let dataH = response.data.header;
            let dataD = response.data.details;
            swal.close();

            $("#co-invoice").text(dataH.invoice);
            $("#co-tgl-order").text(dataH.tanggal);
            $("#co-nama").text(dataH.nama);
            $("#co-alamat").text(dataH.alamat);
            $("#co-catatan").text(dataH.catatan);
            $("#co-keterangan").text(dataH.keterangan);
            $("#co-expedisi").text(dataH.expedisi);

            if (dataD.length > 0) {
              let tBody = createHTML.tableBody(dataD, {
                autoNumber: true,
                coloums: [
                  { label: "hna", format: "number" },
                  { label: "total", format: "number" },
                ],
                footer: {
                  total: "total", //kolom yg akan di SUM
                  ppn: mppn,
                  // kirim : dataH.kirim,
                  // racik : dataH.racik,
                  grandtotal: true,
                },
              });
              $("#co-detail-produk").html(tBody);
            }
            $("#modalCheckout").modal({ backdrop: "static", keyboard: false });
            $("#btn-check-out").remove();
            $("#btn-pl").show();
            $("#co-edit-batch").attr(
              "href",
              pathONKasir.createUrl("pl/update", { id: dataH.id })
            );
            //$('#co-create-invoice').attr('href', pathON.createUrl('/pl/confirm', {id: dataH.id}))
            $("#cancel-invoice").replaceWith(`
                            <button id="cancel-invoice" type="button" class="btn btn-danger" onclick="konfirmasiClose(${dataH.id})">
                                <i class="fa fa-ban"></i> Cancel Invoice
                            </button>
                        `);
            $("#co-create-invoice").replaceWith(`
                            <button id="co-create-invoice" type="button" class="btn btn-success" onclick="konfirmasiCheckout(${dataH.id})">
                                <i class="fa fa-check"></i> Create Invoice
                            </button>
                        `);
          } else {
            calert.error(response.error);
          }
        });
      } else {
        // swal("Anda membatalkan action");
        swal.close();
      }
    });
  });

  $(document).on("click", "#co-create-invoice", function (e) {
    $(this).button("loading");
    $("#modalCheckout").modal("hide");
  });

  onLoadingPage();
});

window.addEventListener("load", (event) => {
  setTimeout(function () {
    validateStock();
    swal.close();
    console.log("The page has fully loaded");
  }, 1000);
  // Your code here
});

</script>