<style>
    .show {
        display: none !important;
    }
</style>
<?php
$form = $this->beginWidget('CActiveForm', array(
    'id' => 'transfer-form',
    'enableAjaxValidation' => false,
    'enableClientValidation' => false,
));

// var_dump($frm);
?>
<ul class="clearfix form-ul material">
    <?php if ($frm == 'in') {
        $Inhid = 'show';
    } else {
        $Inhid = '';
    }
    // var_dump( $Inhid);
    ?>
    <li class="col-sm-2 m-select <?php echo $Inhid; ?>">
        <?php
        if (empty($model->from_warehouse_id) && $frm == 'out') {
            $model->from_warehouse_id = 1;
        }
        if (empty($model->from_warehouse_id) && $frm == 'in') {
            $model->from_warehouse_id = 4;
        }
        ?>
        <?php echo $form->dropDownList($model, 'from_warehouse_id', MasInventoryWarehouse::getWarehouses(), array('class' => '', 'onChange' => 'getTowareHouse(this.value);', 'data-label' => 'From Warehouse <span style="color:red">*</span>', 'empty' => '--Select--')); ?>
        <?php echo $form->hiddenField($model, 'id'); ?>
        <input type="hidden" name="frm" id="frm" value="<?php echo $frm; ?>">
        <input type="hidden" name="hid_from_warehouse_id" id="hid_from_warehouse_id"
            value="<?php echo $model->from_warehouse_id; ?>">
        <input type="hidden" name="hid_dest_warehouse_id" id="hid_dest_warehouse_id"
            value="<?php echo $model->destination_warehouse; ?>">
    </li>
    <!--,'onchange'=>'getid()'-->
    <?php if ($frm == 'out') {
        $hid = 'show';
    } else {
        $hid = '';
    } ?>
    <div id="div_towarehouse" class="<?php echo $hid; ?>">
        <li class="col-sm-2" id="to_ware_house_data">
            <?php
            if (empty($model->to_warehouse_id) && $frm == 'out') {
                $model->to_warehouse_id = 4;
                $readonly = 'readonly';
            } else {
                $readonly = '';

            }
            ?>
            <?php
            if (empty($model->id)) {
                if ($frm == 'in') {
                    echo $form->dropDownList($model, 'to_warehouse_id', MasInventoryWarehouse::getToWarehouses(4), array('class' => '', 'data-label' => 'To Warehouse <span style="color:red">*</span>', 'empty' => '--Select--', 'onChange' => 'getReferenceIds(this.value);', 'readonly' => $readonly));
                } else {
                    echo $form->dropDownList($model, 'to_warehouse_id', array(), array('class' => '', 'data-label' => 'To Warehouse <span style="color:red">*</span>', 'empty' => '--Select--', 'onChange' => 'getDestinationwareHouse(this.value);', 'readonly' => $readonly));
                }
            } else {
                echo $form->dropDownList($model, 'to_warehouse_id', MasInventoryWarehouse::getToWarehouses($model->from_warehouse_id), array('class' => '', 'data-label' => 'To Warehouse <span style="color:red">*</span>', 'empty' => '--Select--', 'onChange' => 'getDestinationwareHouse(this.value);', 'readonly' => $readonly));
            }
            ?>
        </li>
    </div>
    <?php if ($frm == 'out'): ?>
        <div id="div_destinationwarehouse">
            <li class="col-sm-2" id="destination_ware_house_data">
                <?php
                if (empty($model->id)) {
                    echo $form->dropDownList($model, 'destination_warehouse', array(), array('class' => '', 'data-label' => 'Destination <span style="color:red">*</span>', 'empty' => '--Select--'));
                }
                ?>
            </li>
        </div>
    <?php endif; ?>
    <?php if ($frm == 'in'): ?>
        <div id="refenence_id_div">
            <li class="col-sm-3">
                <?php echo $form->textField($model, 'reference', array('class' => 'tooltipster', 'title' => 'Reference', 'data-label' => 'Reference')); ?>
            </li>
        </div>
    <?php else: ?>
        <li class="col-sm-3">
            <?php echo $form->textField($model, 'reference', array('class' => 'tooltipster', 'title' => 'Reference', 'data-label' => 'Reference')); ?>
        </li>
    <?php endif; ?>
    <li class="col-sm-2">
        <?php echo $form->textField($model, 'transfer_date', array('class' => 'datepicker', 'title' => 'Transfer Date', 'data-label' => 'Transfer Date  <span style="color:red">*</span>', 'value' => date('d/m/y'))); ?>
    </li>

    <li class="col-sm-3 <?php echo $hid; ?>">
        <?php echo $form->textArea($model, 'direct_transfer_description', array('class' => 'tooltipster', 'title' => 'Description', 'data-label' => 'Description')); ?>
    </li>
</ul>

<?php

$cs = Yii::app()->getClientScript();
$baseUrl = Yii::app()->baseUrl;

?>
<div class="table-responsive">
    <table class="table table-hover table-bordered personal-task" id="transfer_item_table">
        <tr>
            <th>No</th>
            <th>Item</th>
            <th>Barcode</th>
            <th>Item Description</th>
            <th>Available Qty <span style="color:red">(Base Qty)</span></th>
            <th>Transfer Qty</th>
            <th>Unit</th>
            <th class="text-center">
                <a class="btn btn-sm btn-theme " href="javascript:void(0);"
                    onclick="addTransferTableRow($('#transfer_item_table'));"><i class="fa fa-plus"></i></a>
            </th>

        </tr>

        <?php

        foreach ($model_items as $i => $modeltransfer) {
            if ((int) $model->id > 0) {
                $modeltransfer->missing_qty = (float) ProductLocation::model()->find(array('select' => 'SUM(quantity) as quantity', 'condition' => 'product_id="' . $modeltransfer->item_id . '" AND warehouse_id=' . $model->from_warehouse_id))->quantity;
            }
            ?>

            <tr>

                <td><label><?php echo ($i + 1); ?></label></td>
                <td>
                    <?php echo $form->textField($modeltransfer, "[" . $i . "]item_name", array('class' => 'tooltipster go', 'placeholder' => 'Type & Select', 'onKeyup' => 'js:autoCompleteProduct(this.id,"transfer");', 'title' => 'Select product')); ?>

                    <?php echo $form->hiddenField($modeltransfer, "[" . $i . "]id"); ?>
                    <?php echo $form->hiddenField($modeltransfer, "[" . $i . "]item_id"); ?>
                    <?php echo $form->error($modeltransfer, "[" . $i . "]id"); ?>

                </td>
                <td>

                    <?php
                    echo $form->textField($modeltransfer, "[" . $i . "]bar_code", array(
                        'class' => 'tooltipster go myTextField',
                        'placeholder' => 'Type',
                        'onkeydown' => 'handleKeyPress(event, this)',
                        'title' => 'Select product'
                    ));
                    ?>

                </td>



                <td>
                    <?php echo $form->textArea($modeltransfer, "[" . $i . "]item_description", array('class' => 'tooltipster desc go', 'title' => 'Add Description here')); ?>
                    <?php echo $form->error($modeltransfer, "[" . $i . "]item_description"); ?>

                </td>
                <td>
                    <?php echo $form->textField($modeltransfer, "[" . $i . "]missing_qty", array('class' => 'qty go cell-center text-right', 'readonly' => true)); ?>
                    <?php echo $form->error($modeltransfer, "[" . $i . "]missing_qty"); ?>
                </td>
                <td>
                    <?php echo $form->textField($modeltransfer, "[" . $i . "]transfer_qty", array('class' => 'qty go cell-center text-right', 'onkeypress' => 'return isPositiveNumber(event)', 'onkeyup' => 'checkVal(this.id,this.value);', )); ?>
                    <?php echo $form->error($modeltransfer, "[" . $i . "]transfer_qty"); ?>
                </td>
                <td id="unit_<?php echo $i; ?>">
                    <?php
                    ($modeltransfer->item_id > 0) ? $data = UnitOfMeasurement::getUnits($modeltransfer->item_id) : $data = array();
                    ?>
                    <?php echo $form->dropdownlist($modeltransfer, "[" . $i . "]unit", $data, array('class' => 'qty go')); ?>

                </td>

                <td class="text-center nw" width="1%">
                    <?php echo CHtml::link('<i class="fa fa-times"></i>', 'javascript:void(0);', array('class' => 'btn btn-sm btn-danger', 'onclick' => 'rmRow($(\'#transfer_item_table\'),this,this.id)', 'title' => 'Remove this item', 'id' => 'ProductLocation_' . $i)); ?>
                </td>

            </tr>
        <?php } ?>

    </table>
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
    <?php
    //if($type != 'view'){
    $url = Yii::app()->createUrl('iwarehouse/SaveTransfer');
    echo CHtml::ajaxSubmitButton('Transfer', $url, array(
        'dataType' => 'json',
        'type' => 'post',
        'success' => 'function(data) {
                                    if(data.status=="success"){  
                                         t8.success("Tansfer No. "+data.id+" Saved Successfully!");
                                         $(".x.close").click();
                                         $("#loader").hide();
                                         $("#pk_li").click();
                                         reloadTable("#tbl_directtransfer_details");
                                         reloadTable("#tbl_packing_list");
                                    } else { 
                                         $("#loader").hide();
                                         $.each(data, function(key, val) {
                                                t8.error(""+val+""); 
                                         }); 
                                    } 
                                    }',

        'beforeSend' => 'function(){                                        
                                        $(".toast8-error").hide();
                                        $("#loader").show();
                                                                         
                        }'

    ), array('id' => 'mybtn' . rand(), 'class' => 'transfer-save-btn btn btn-theme'));
    //}
    
    ?>

</div>
<?php $this->endWidget(); ?>

<?php
$cs = Yii::app()->getClientScript();
$cs->registerScript("getTowareHouse", " function getTowareHouse(from_id) {
    if(from_id>0){
        $('#stock_details_table').html('');
    }    
    jQuery.ajax({
        'dataType':'json', 
        'type': 'post',
        'url': '" . Yii::app()->createUrl('iwarehouse/getTowarehouseLocation') . "',
        'data': {'from_id':from_id},
        'cache': false,
        'success': function(data) {            
            $('#to_ware_house_data').html(data.towarehouse);
            var frm = $('#frm').val();
            if (frm === 'out') {
                var select = $('#InventoryDirectTransfer_to_warehouse_id');
                if (select.length > 0) {
                    select.val('4').trigger('change');
                     select.css({
                        'pointer-events': 'none',
                     })
                }
            }
        }
    });

}", CClientScript::POS_HEAD);

$cs->registerScript("getDestinationwareHouse", "
    function getDestinationwareHouse(to_id) {
        if (to_id > 0) {
            $('#stock_details_table').html('');
        }
        var frm = $('#frm').val();
        console.log(frm);
        var from_id = $('#InventoryDirectTransfer_from_warehouse_id').val();
        var dest_id = $('#hid_dest_warehouse_id').val();
        if(frm == 'out'){
            jQuery.ajax({
                dataType: 'json',
                type: 'post',
                url: '" . Yii::app()->createUrl('iwarehouse/getDestinationwarehouseLocation') . "',
                data: { to_id: to_id, from_id: from_id, dest_id: dest_id },
                cache: false,
                success: function(data) {
                    $('#destination_ware_house_data').html(data.towarehouse);
                }
            });
        }
    }

    // On page load
    jQuery(function() {
        var to_id = $('#InventoryDirectTransfer_to_warehouse_id').val();
        if (to_id) {
            getDestinationwareHouse(to_id);
        }

        // Change event for to_warehouse
        $('#InventoryDirectTransfer_to_warehouse_id').on('change', function() {
            var to_id = $(this).val();
            getDestinationwareHouse(to_id);
        });

        var frm = $('#frm').val();
        if (frm === 'out') {
            var from_id = $('#InventoryDirectTransfer_from_warehouse_id').val();
            if (from_id) {
                getTowareHouse(from_id);
            }

            // Optionally bind change event if you want it dynamic too
            $('#InventoryDirectTransfer_from_warehouse_id').on('change', function() {
                var from_id = $(this).val();
                if (from_id) {
                    getTowareHouse(from_id);
                }
            });
        }
    });
", CClientScript::POS_HEAD);

$cs->registerScript("checkVal", "function checkVal(field_id,qty)
    {
            var arr_fields= field_id.split('_');
            var model_name   = arr_fields[0];
            var row_field  = arr_fields[1];   
            var max_qty = parseFloat($('#InventoryDirectTransferItem_'+row_field+'_available_qty').val());
            if(parseFloat(qty) > max_qty){
                $('#InventoryDirectTransferItem_'+row_field+'_transfer_qty').val('');
            }
            
            var current_product_id = parseInt($('#InventoryDirectTransferItem_'+row_field+'_item_id').val());
            var table_length = $('#transfer_item_table').find('tr:gt(0)').length; 
            if(table_length>0){
                var prd_qty=0;
                for(i=0;i<table_length;i++){
                    var product_id = $('#InventoryDirectTransferItem_'+i+'_item_id').val();
                    var product_qty = parseInt($('#InventoryDirectTransferItem_'+i+'_transfer_qty').val());
                    if(current_product_id==product_id){
                        prd_qty+=product_qty;
                    }
                }
            }
            if(parseInt(prd_qty) > max_qty){
                $('#InventoryDirectTransferItem_'+row_field+'_transfer_qty').val('');
                t8.error('Quatity not available for this product','');
            }
    }", CClientScript::POS_HEAD);

?>

<?php
$cs = Yii::app()->getClientScript();
$cs->registerScript("autoCompleteProduct", "function autoCompleteProduct(field_id,frm)
{
        var from_warehouse_id   = $('#InventoryDirectTransfer_from_warehouse_id').val();
        var to_warehouse_id     = $('#InventoryDirectTransfer_to_warehouse_id').val();
        
        if(from_warehouse_id==''){
            t8.error('Please select from warehouse'); 
             $('#'+field_id).val('');
            return false;
        }
        else{
            var url = '" . Yii::app()->createUrl('iwarehouse/GetAllProducts') . "'+'&frm='+frm+'&from_warehouse_id='+from_warehouse_id;
            $('#'+field_id).autocomplete({
                minLength   : 1,
                source      : function (request, response) { autoCompleteSource(request, response,url) },
                focus       : function( event, ui ) { $(this).val((ui.item.label)); return false;},
                select          : function( event, ui ) {
                    event.preventDefault();
                    trigger_target_id   =   $(event.target).attr('id');
                    var product_id=ui.item.value;
                    var id=ui.item.value;
                    var desc=ui.item.description;
                    var quantity=ui.item.total_q;
                    if(quantity == null){
                        quantity=0;
                    }
                    var unit_id=ui.item.unit_id;
                    var unit_name=ui.item.unit_name;
                    var arr_fields= field_id.split('_');
                    var model_name   = arr_fields[0];
                    var row_field  = arr_fields[1];
                    var part_number=ui.item.part_number;
                      var bar_code= ui.item.bar_code;
                      
                    var available_qty= ui.item.other;
                    console.log(available_qty);
                    $('#InventoryDirectTransferItem_'+row_field+'_item_name').val(part_number);
                    $('#InventoryDirectTransferItem_'+row_field+'_item_description').val(desc);
                    $('#InventoryDirectTransferItem_'+row_field+'_unit_id').val(unit_id); //for showing hidden field
                    $('#InventoryDirectTransferItem_'+row_field+'_unit').val(unit_name); //FOR SHOWING UNIT NAME
                    $('#InventoryDirectTransferItem_'+row_field+'_product_id').val(product_id);
                    $('#InventoryDirectTransferItem_'+row_field+'_item_id').val(id);
                    $('#InventoryDirectTransferItem_'+row_field+'_missing_qty').val(available_qty);
                     $('#InventoryDirectTransferItem_'+row_field+'_bar_code').val(bar_code); 
                     
                    if(product_id > 0){
                        jQuery.ajax({
                           'type': 'post',
                           'dataType': 'json',
                           'url': '" . Yii::app()->createUrl('iwarehouse/GetProductOtherDetails') . "',
                           'data': {'row_field' : row_field, 'product_id' : product_id,'from_warehouse_id':from_warehouse_id,'type' : 'direct'},
                           'cache': false,
                           'success': function(data) {
                                var total_allocated_qty         =   data.total_allocated_qty;
                                var total_available_qty         =   data.total_available_qty;
                                var warehouse_available_qty     =   data.warehouse_available_qty;
                                console.log(warehouse_available_qty);
                                //var free_qty                    =   warehouse_available_qty-allocated_qty;                         
                                //$('#InventoryDirectTransferItem_'+row_field+'_allocated_qty').val(allocated_qty);
                                $('#InventoryDirectTransferItem_'+row_field+'_missing_qty').val(warehouse_available_qty);
                                $('#unit_'+row_field).html(data.unitdrop);
                                return false;
                           }
                       });
                    }
                   
                }
    
            })
        }
       

    }", CClientScript::POS_HEAD);

?>
<?php
$cs = Yii::app()->getClientScript();
$cs->registerScript("FetchData", "function FetchData(Qty,field_id,event)
    {
        if (event.keyCode == 13) {

            event.preventDefault();
            var arr_fields   = field_id.split('_');
            var model_name   = arr_fields[0];
            var row_field    = arr_fields[1];
            
            var from_warehouse = $('#InventoryDirectTransfer_from_warehouse_id').val();
            var to_warehouse = $('#InventoryDirectTransfer_to_warehouse_id').val();
            var product_id = $('#InventoryDirectTransferItem_'+row_field+'_item_id').val();
            var rows = $('#table-stock-details').find('tr:gt(0)').length;
            
            if(rows>0){
                var lastRowId = $('#table-stock-details').find('tr:last input:first').attr('id');
                var split_id  = lastRowId.match(/\d+/g);
                var rows   = Number(split_id);
                rows  = rows+1;
           }

            if(from_warehouse > 0 && to_warehouse > 0){
                if(from_warehouse === to_warehouse){
                    t8.error('Choose Distinct Warehouses!');
                    return false;
                }else{
                    var i=0;
                    var products = [];
        
                    for (i=0; i<= rows; i++){
                        try{
                            if($('#Data_'+i+'_product_id').val() > 0 && products.includes($('#Data_'+i+'_product_id').val()) === false)
                                products.push($('#Data_'+i+'_product_id').val());
                        }catch(e){}
                    } 
                    
                    var sum_qty  = 0;
                    $('#table-stock-details').find('tr.transfer_pro_'+product_id).remove();
                    if(products.includes(product_id)){
                        
                        for (j=0; j<= rows; j++){
                            
                            if($('#InventoryDirectTransferItem_'+j+'_item_id').val() == product_id & $('#InventoryDirectTransferItem_'+j+'_transfer_qty').val() >0){
                                sum_qty+=parseInt($('#InventoryDirectTransferItem_'+j+'_transfer_qty').val());
                                
                            }
                        }
                        Qty  = sum_qty;
                    }
                    
                    //if(products.includes(product_id))
                        //return false;
                    //else{
                       
                            if(product_id > 0 && Qty > 0){
                                
                                jQuery.ajax({
                                    'type': 'post',
                                    'url': '" . Yii::app()->createUrl('iwarehouse/getStockDetails') . "',
                                    'data': {'product_id' : product_id, 'Qty' : Qty, 'length' : rows, 'from_warehouse' : from_warehouse, 'to_warehouse' : to_warehouse},
                                    'cache': false,
                                    'success': function(data) {
                                        $('#div_stock').show();
                                        if(data != '')
                                            $('.no-data-tr').remove(); 
                                        $('#stock_details_table').append(data);
                                        return false;
                                    }
                                });
                            }
                        return false;
                    }
               // }
            }else{
                t8.error('Choose Warehouses!');
                return false;
            }
        }
    }", CClientScript::POS_HEAD);

$cs->registerScript("verifyQty", "function verifyQty(field_id,qty)
    {
    
         if(parseInt(qty) > 0){
            var arr_fields= field_id.split('_');
            var model_name   = arr_fields[0];
            var row_field  = arr_fields[1];   
            
            var max_qty = parseInt($('#Data_'+row_field+'_qty_available').val());
           
            if(parseInt(qty) > max_qty){
                $('#Data_'+row_field+'_available_qty').val('');
            }

          

        }
        
    }", CClientScript::POS_HEAD);

$cs->registerScript("rmRow ", "function rmRow(jQtable,evt,field_id) {
            
            var arr_fields= field_id.split('_');
            var row_field=arr_fields[1];
            var rows = $('#table-stock-details').find('tr:gt(0)').length;
            var pro_id = $('#InventoryDirectTransferItem_'+row_field+'_item_id').val();
            var num_rows    =   jQtable.find('tr:gt(0)').length;
            if(num_rows>1){
                $(evt).parents('tr').remove();
                for (i=0; i<= rows; i++){
                    try{
                        if($('#Data_'+i+'_product_id').val()  === pro_id){
                                $('.pro'+pro_id).remove();
                        }

                    }catch(e){}
                } 
                autoarrange();
            }else{
                alert('Atleast one item needed here','Alert');
            }
                
        };", CClientScript::POS_HEAD);


$cs->registerScript("autoarrange", "function autoarrange(){                                
                    var i=0;
                   $('#table-stock-details').find('tr:gt(0)').each(function() {       
                            $(this).find('input,tr,select,textarea,.errorMessage').each(function()
                            {                   
                                old_id   =   $(this).attr('id');
                                new_id   =   old_id.replace(/\d+/,i);
                                $(this).attr('id',new_id);
                               
                                old_name =   $(this).attr('name');
                                if(old_name!==undefined) {
                                    new_name =   old_name.replace(/\d+/,i);
                                    $(this).attr('name',new_name);
                                } 
                            });
                            $(this).find('td:first label').html(++i); 
                    });         
    }", CClientScript::POS_HEAD);

$cs->registerScript("getFactor", "function getFactor(field_id,value)
    {
        var arr_fields= field_id.split('_');
        var model_name   = arr_fields[0];
        var row_field  = arr_fields[1];   
        jQuery.ajax({
            'type': 'post',
            'url': '" . Yii::app()->createUrl('iwarehouse/GetFactor') . "',
            'data': {'value' : value},
            'cache': false,
            'success': function(data) {
                $('#InventoryDirectTransferItem_'+row_field+'_factor').val(data);
                return false;
            }
        });
        
    }", CClientScript::POS_HEAD);

// $cs->registerScript("clearTableInputs", "function clearTableInputs(frm_warehouse_id) { 
//       if($('#InventoryDirectTransferItem_0_item_id').val() > 0){
//       var r = confirm('Are you sure you want to change From Warehouse? If you change warehouse, the below table content will be lose');
// 	        if(r==true)
// 	        {
// 	            $('#hid_from_warehouse_id').val(frm_warehouse_id);

//               $('#transfer_item_table').find(':input').each(function() {

//                             $(this).val('');

//                      });
// 	        }
// 	        else{
// 	                var old_from_warehouse_id = $('#hid_from_warehouse_id').val();
// 	                $('#InventoryDirectTransfer_from_warehouse_id').val(old_from_warehouse_id);

// 	        }
//       }
//       else{
//           $('#hid_from_warehouse_id').val(frm_warehouse_id);
//       }

//   }", CClientScript::POS_HEAD);
$cs->registerScript("addTransferTableRow", " function addTransferTableRow(jQtable) {
        var table_length=$('#transfer_item_table').find('tr:gt(0)').length;
        if(table_length<30){
            formId              =   jQtable.attr('id');
            formIdStarter       =   jQtable.attr('id').split(/_(.+)?/)[0];
    
            lastId = jQtable.find('tr:last input:first').attr('id');
    
            thenum = lastId.match(/\d+/g);
            //alert(lastId);
    
            newId = Number(thenum) + 1;
            newrow= jQtable.find('tr:last').clone();
            newrow.find('label:first').html(newId+1);
            newrow.attr('class',newId);
            newrow.find('div,input,textarea,checkbox,td,select,.errorMessage,a,span').each(function() {
                this.id= this.id.replace(/\d+/,newId);
                this.value  = '';
                (this.name!==undefined) ? this.name= this.name.replace(/\d+/,newId) : this.style  =   '';
            });
            jQtable.append(newrow);
            $('#InventoryIndirectTransferItem_'+newId+'_factor').val(1);
            $('#QuotesItem_'+newId+'_product_name').focus();
        }else{
            t8.error('Maximum number of rows exceeded');
        }

    }", CClientScript::POS_HEAD); ?>


<?php
$script = "
    function handleKeyPress(event, field) {
        if (event.key === 'Enter') {
            event.preventDefault();

            var field_id = field.id;
            var barcode = field.value;

            var arr_fields = field_id.split('_');
            var model_name = arr_fields[0];
            var row_field = arr_fields[1];

            entertext(field_id, barcode);
        }
    }

    function entertext(field_id, barcode) {
        var arr_fields = field_id.split('_');
        var model_name = arr_fields[0];
        var row_field = arr_fields[1];
  var from_warehouse_id = $('#InventoryDirectTransfer_from_warehouse_id').val();
    var to_warehouse_id = $('#InventoryDirectTransfer_to_warehouse_id').val();

    if (from_warehouse_id == '') {
        t8.error('Please select from warehouse');
        $('#' + field_id).val('');
        return false;
    } else {

         $.ajax({
                    url: '" . Yii::app()->createUrl('iwarehouse/GetProductsWithBarcode') . "',
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        from_warehouse_id: from_warehouse_id,
                        to_warehouse_id: to_warehouse_id,
                        barcode: barcode
                    },
                   'cache': false,
            'success': function(data) { 
            if(data.msg=='success'){
                
                 
        
        
                   var arr_fields = field_id.split('_');
                   var model_name = arr_fields[0];
                   var row_field = arr_fields[1];
                   var product_id = data.product_id;
    
                    $('#InventoryDirectTransferItem_' + row_field + '_item_description').val(data.description);
                    $('#InventoryDirectTransferItem_'+row_field+'_item_name').val(data.part_number);
                    $('#InventoryDirectTransferItem_'+row_field+'_unit_id').val(data.unit_id); 
                    $('#InventoryDirectTransferItem_'+row_field+'_unit').val(data.unit_name); 
                    $('#InventoryDirectTransferItem_'+row_field+'_item_id').val(product_id); 




                if(product_id > 0){
                            jQuery.ajax({
                               'type': 'post',
                               'dataType': 'json',
                               'url': '" . Yii::app()->createUrl('iwarehouse/GetProductOtherDetails') . "',
                               'data': {'row_field' : row_field, 'product_id' : product_id,'from_warehouse_id':from_warehouse_id,'type' : 'direct'},
                               'cache': false,
                               'success': function(data) {
                                    var total_allocated_qty         =   data.total_allocated_qty;
                                    var total_available_qty         =   data.total_available_qty;
                                    var warehouse_available_qty     =   data.warehouse_available_qty;
                                    //var free_qty                    =   warehouse_available_qty-allocated_qty;                         
                                    //$('#InventoryDirectTransferItem_'+row_field+'_allocated_qty').val(allocated_qty);
                                    $('#InventoryDirectTransferItem_'+row_field+'_missing_qty').val(warehouse_available_qty);
                                    $('#unit_'+row_field).html(data.unitdrop);
                                    return false;
                               }
                           });
                
            }

                }else{
                    
                      t8.error('This Barcode Not Exist');
       
        return false;
                    
                    
                    
                }
            
            }
                });
    
    
    }
      
    }
";
$cs->registerScript("getReferenceIds", " function getReferenceIds(from_id) {
    if(from_id>0){
        $('#stock_details_table').html('');
    }    
    jQuery.ajax({
        'dataType':'json', 
        'type': 'post',
        'url': '" . Yii::app()->createUrl('iwarehouse/getReferenceIds') . "',
        'data': {'from_id':from_id},
        'cache': false,
        'success': function(data) {            
             $('#refenence_id_div').html(data.dt);
        }
    });

}", CClientScript::POS_HEAD);
Yii::app()->getClientScript()->registerScript('entertext', $script, CClientScript::POS_READY);
?>
<script>
    $(document).on('change', '.multi-select', function () {
        if ($(this).val()?.includes('all')) {
            $(this).find('option').prop('selected', true);
            $(this).trigger('change'); // trigger change to update UI
        }
    });
</script>