<?php
/**
 * Last Modified by Jobin
 */
$cs = Yii::app()->getClientScript();
$baseUrl = Yii::app()->baseUrl;
$total_vat = 0;
$model_settings         = new MasCompanySettings();
$crm_login_company_id   = Yii::app()->user->master_user_company_id;        
$model_settings         = $model_settings->find(array('condition'=>'crm_company_id='.$crm_login_company_id));  
$allow_change           = $model_settings->allow_change_description;
//$bonus_quantity         = $model_settings->bonus_quantity;
echo CHtml::hiddenField('allow_change',$allow_change);
echo CHtml::hiddenField('bonus_quantity', $bonus_quantity);
$company = MasCompany::model()->findByPk((int) Yii::app()->user->master_user_company_id);
$no_of_decimals_rate = $company->no_of_decimals_rate;
?>
<div id ="div_service_item_details">
<div class="table-responsive">
    <table class="table table-hover table-bordered personal-task" id="order_item_table">        
        <tr>            
            <th>No</th>
<!--            <th> Exp.DeliveryDate</th> -->
            <th>Product</th>        
            <th>Description</th>     
            <th>Qty</th>
            <th>Unit</th>           
            <th>Rate</th>            
            <th>Amount</th>        
            <th>Tax(%)</th>  
            <!--th class="bg-success text-center">+/-</th-->           
            <th class="bg-danger text-center">Discount</th>           
            <th>Net</th>            
            <th class="text-center">
                <a class="btn btn-xs btn-theme" href="javascript:void(0);" onclick="addTableRow($('#order_item_table'));"><i class="fa fa-plus"></i></a></th>  
        </tr>
       <?php
        foreach($modelOrderItems as $i => $modelOrderItems): ?>
        <tr>                
            <td><label><?php echo ($i+1); ?></label></td>
            <?php 
                $product_inventory_type = "";
                if($modelOrderItems->id > 0){
                    $modelOrderItems->expected_delivery_date = date("d/m/Y", strtotime($modelOrderItems->expected_delivery_date));
                }else{
                     $modelOrderItems->expected_delivery_date = date("d/m/Y");
                }
                ?>
<!--            <td><?php //echo $form->hiddenField($modelOrderItems, "[" . $i . "]expected_delivery_date", array('class' => 'datepicker go ')); ?>                    
                <?php // echo $form->error($modelOrderItems, "[" . $i . "]expected_delivery_date"); ?>  </td> -->
         <?php 
             if($modelOrderItems->product_id == 999999){
                 $product_name = 'memo';
                 $disabled = true;
                 $modelOrderItems->unit = '';
                 
             }
             else{
                 $product_name = $modelOrderItems->product->part_number;
                 $disabled = false;
                 $product_inventory_type  = $modelOrderItems->product->inventory_item_type;
            }
         ?>
            <td><?php  
           // echo $modelOrderItems->product->part_number;
            //echo $modelOrderItems->tax_vat_percentage;
            
            echo $form->textField($modelOrderItems, "[" . $i . "]product_name", array('class'=>'form-control', 'placeholder' => 'Type & Select',
                'onKeyup' => 'js:autoCompleteProduct(this.id,"order");','value'=>$product_name, 'style'=>'width: 120px',
                'title' => 'Select product')); ?>                                        

                <?php echo $form->hiddenField($modelOrderItems, "[" . $i . "]product_id"); ?> 
                <?php echo $form->hiddenField($modelOrderItems, "[" . $i . "]quotes_item_id"); ?> 
                 <?php echo $form->error($modelOrderItems, "[" . $i . "]product_id"); ?>  
                 <?php echo CHtml::hiddenField('product['.$i.'][inventorytype]',$product_inventory_type); ?> 
            </td>
<!--            <td>
                <?php // echo $form->textField($modelOrderItems, "[" . $i . "]product_generic_name", array( 'class' => 'tooltipster desc desc2 go',  'title' => 'Generic Name'));  ?>
                <?php // echo $form->error($modelOrderItems, "[" . $i . "]product_generic_name"); ?>
             </td>-->
            <td>
                <div id="div_description">                
                <?php 
                if($allow_change=="N" && $modelOrderItems->product_id != 999999){
                    echo $form->textArea($modelOrderItems, "[" . $i . "]description", array( 'class' => 'tooltipster desc desc2 go en-text-area',  'title' => 'Add Description here','readonly'=>'true'));                                
                }else{
                    echo $form->textArea($modelOrderItems, "[" . $i . "]description", array( 'class' => 'tooltipster desc desc2 go en-text-area',  'title' => 'Add Description here'));     
                }
                ?>
                <?php echo $form->error($modelOrderItems, "[" . $i . "]description"); ?>                
               </div>
            </td>   
<!--            <td>
                   <?php // echo $form->dropDownList($modelOrderItems, "[" . $i . "]brand_class_id", ProductClass::getAllProductClass(), array('class' => 'go ', 'prompt' => 'Select', 'title' => 'Brand/Calss','data-label'=>'Industry','data-search'=>'true')); ?>
                   <?php // echo $form->error($modelOrderItems, "[" . $i . "]brand_class_id"); ?>
            </td>-->
    <?php  $modelOrderItems->quantity = number_format( $modelOrderItems->quantity,$no_of_decimals_rate); ?>
            <td><?php echo $form->textField($modelOrderItems, "[" . $i . "]quantity", array('class' => 'qty go text-right', 'onkeypress' => 'return isPositiveNumber(event)', 'onkeyup' => 'calculateorderValue($("#order_item_table"),this.id);','readonly' => $disabled)); ?>                    
                <?php echo $form->error($modelOrderItems, "[" . $i . "]quantity"); ?>  
            </td> 
            <td id="unit_<?php echo $i; ?>">
                             <?php 
                               ($modelOrderItems->product_id > 0) ? $data = UnitOfMeasurement::getUnits($modelOrderItems->product_id) : $data = array();
                             ?>
                             <?php echo $form->dropdownlist($modelOrderItems, "[" . $i . "]unit_id",$data, array('class'=>'qty go')); ?>
                             
            </td>         
            <td><?php
                            // if($type=="view" || $type=="approve" )
                             $modelOrderItems->rate = number_format( $modelOrderItems->rate,$no_of_decimals_rate);
                             ?>
                  <?php echo $form->textField($modelOrderItems, "[" . $i . "]rate", array('class' => 'rate go text-right to_be_calculated', 'onkeypress' => 'return isNumberKey(event)', 'onkeyup' => 'calculateorderValue($("#order_item_table"),this.id);','readonly' => $disabled)); ?>                    
                  <?php echo $form->error($modelOrderItems, "[" . $i . "]rate"); ?>                
            </td>                  
        
            <td>
                    <?php echo $form->textField($modelOrderItems, "[" . $i . "]amount", array('class' => 'amt go text-right', 'onkeypress' => 'return isNumberKey(event)', 'readonly' => true)); ?>                    
                    <?php echo $form->error($modelOrderItems, "[" . $i . "]amount"); ?>               
            </td>  
             <td>
                <?php if($modelOrderItems->product_id > 0){
                            $modelOrderItems->tax_vat_percentage = $modelOrderItems->product->tax->percentage; 
                            $modelOrderItems->tax_vat_amount = ($modelOrderItems->net_amount * $modelOrderItems->product->tax->percentage)/100;
                            $model->total_tax_amount += $modelOrderItems->tax_vat_amount;
                    } ?>
                  <?php echo $form->textField($modelOrderItems, "[" . $i . "]tax_vat_percentage", array('class' => 'rate go text-right to_be_calculated','readonly'=>true)); ?>                    
                  <?php echo $form->hiddenField($modelOrderItems, "[" . $i . "]tax_vat_amount"); ?>
                  <?php echo $form->error($modelOrderItems, "[" . $i . "]tax_vat_percentage"); ?>  
                  <input type="hidden" id="check_tax_vat_percentage_<?php echo $i; ?>" value="<?php echo $modelOrderItems->product->tax->percentage;//echo $modelOrderItems->tax_vat_percentage;//// ?>" />
                                
            </td>                
            <!--td class="bg-success nw">
                    <?php //echo $form->textField($modelOrderItems, "[" . $i . "]addition_percentage", array('class' => 'txt-6 go exception text-right', 'onkeypress' => 'return isNumberKey(event)', 'onkeyup' => 'calculateorderValue($("#order_item_table"),this.id);','disabled' => $disabled)); ?>                    
                    <?php //echo $form->error($modelOrderItems, "[" . $i . "]addition_percentage"); ?>                    
                    <?php //echo $form->textField($modelOrderItems, "[" . $i . "]addition_amount", array('class' => 'txt-6 go exception text-right additions', 'readonly' => true)); ?>                   
                    <?php //echo $form->error($modelOrderItems, "[" . $i . "]addition_amount"); ?>                             
            </td-->                

        <td class="bg-danger nw">
            
                <?php echo $form->hiddenField($modelOrderItems, "[" . $i . "]addition_percentage", array('class' => 'txt-6 go exception text-right', 'onkeypress' => 'return isNumberKey(event)', 'onkeyup' => 'calculateorderValue($("#order_item_table"),this.id);','disabled' => $disabled)); ?>                    
                    <?php echo $form->hiddenField($modelOrderItems, "[" . $i . "]addition_amount", array('class' => 'txt-6 go exception text-right additions', 'readonly' => true)); ?>                   
                    <?php echo $form->hiddenField($modelOrderItems, "[" . $i . "]deduction_percentage", array('class' => 'txt-6 go exception text-right', 'onkeypress' => 'return isPositiveInteger(event,this.value);', 'onkeyup' => 'calculateorderValue($("#order_item_table"),this.id);','disabled' => $disabled)); ?>                    
                    <?php echo $form->hiddenField($modelOrderItems, "[" . $i . "]deduction_amount", array('class' => 'txt-6 go exception text-right deductions', 'readonly' => true)); ?>   
           
                <?php echo $form->textField($modelOrderItems, "[" . $i . "]deduction_percentage", array('class' => 'txt-6 go exception text-right', 'onkeypress' => 'return isPositiveInteger(event,this.value);', 'onkeyup' => 'calculateorderValue($("#order_item_table"),this.id);','disabled' => $disabled)); ?>                    
                <?php echo $form->error($modelOrderItems, "[" . $i . "]deduction_percentage"); ?>                    

                <?php echo $form->textField($modelOrderItems, "[" . $i . "]deduction_amount", array('class' => 'txt-6 go exception text-right deductions', 'readonly' => true)); ?>                    
                 <?php echo $form->error($modelOrderItems, "[" . $i . "]deduction_amount"); ?>                
          
        </td>                

        

            <td>
                
                <?php echo $form->textField($modelOrderItems, "[" . $i . "]net_amount", array('class' => 'amt go text-right', 'readonly' => true)); ?>                    



                <?php echo $form->error($modelOrderItems, "[" . $i . "]net_amount"); ?>                    



                    <?php $total+=$modelOrderItems->amount; 
                    $total_vat += $modelOrderItems->tax_vat_amount; 
                    
                    ?>                



           </td>                



            <td class="text-center nw" width="1%">  
                    <?php //echo CHtml::link('<i class="fa fa-paper-plane-o"></i>', 'javascript:void(0);', array('class' => 'btn btn-primary btn-xs','id'=>'order'.$i, 'title' => 'Insert A Row','onclick' => 'InsertNewRow($(\'#order_item_table\'),this.id)')); ?>                  
                        <?php //echo CHtml::link('<i class="fa fa-arrow-up"></i>', 'javascript:void(0);', array('class' => 'up btn btn-primary btn-xs', 'title' => 'Move to Up')); ?>
                            <?php //echo CHtml::link('<i class="fa fa-arrow-down"></i>', 'javascript:void(0);', array('class' => 'down btn btn-primary btn-xs', 'title' => 'Move to Down')); ?>
                        <?php echo CHtml::link('<i class="fa fa-times"></i>', 'javascript:void(0);', array('class'=>'btn btn-xs btn-danger','onclick' => 'removeTableRow($(\'#order_item_table\'),this)', 'title' => 'Remove this item')); ?>                

            </td>            



        </tr>        



            <?php endforeach; 
            
             $sub_total = $total - $model->total_discount_amount;
            ?>    



    </table>

    <table class="table table-hover table-bordered table-nexted order_total">

            <tr class="bg-total">

                <td width="70%" class="text-right table_total_title">

                    <h2>Total</h2>

                </td>

                <td width="30%" class="text-right table_total">

                    <h2 class="total" class="text-right"><?php echo Yii::app()->numberFormatter->formatCurrency($total, " "); ?></h2>

                </td>

            </tr>

        </table>

       <?php $grand_total = $total; ?>   

    <!--table id="order_final_add_table" class="table table-hover table-bordered table-nexted">        

       <?php  /*foreach($modelOrderAdditions as $i => $eachadd): 
                 
           ?>            

        <tr>               

             <td class="text-right td-in-6">

                 Additions                    

                <a class="btn btn-xs btn-theme " href="javascript:void(0);" onclick="addTableRow($('#order_final_add_table'));"><i class="fa fa-plus"></i></a>

                </td>   

                <td>
                    <?php echo $form->dropDownList($eachadd,  "[" . $i . "]particular", MasFooterItems::getSaleAdditions(), array('prompt' => 'Select','class'=>'form-control', 'style' => 'width:150px')); ?> 
                    <?php // echo $form->textField($eachadd, "[" . $i . "]particular", array('class' => 'go particular', 'placeholder' => 'Particulars')); ?>                    

                </td>

                <td>

                        <?php echo $form->textField($eachadd, "[" . $i . "]particular_value", array('onkeyup' => 'calculateorderValue($("#order_item_table"));', 'onkeypress' => 'return isNumberKey(event)', 'class' => 'value_rate go text-right', 'placeholder' => '0.00')); ?>                    

                </td>

                <td>

                        <?php echo $form->textField($eachadd, "[" . $i . "]calculated_value", array('readonly' => true, 'class' => 'value_rate additions_value go text-right')); ?>                    

                </td>

                <td width="0">                    

                    <?php echo CHtml::link('<i class="fa fa-times"></i>', 'javascript:void(0);', array('class'=>'btn btn-xs btn-danger','onclick' => 'removeExtrasRow($("#order_final_add_table"), this)')); ?>                    

                </td>                

                <?php $grand_total +=$eachadd->calculated_value; ?>            

        </tr>       

 <?php
 endforeach;*/ ?>   

    </table>    

    <table id="order_final_ded_table" class="table table-hover table-bordered  table-nexted">        



        <?php  /*foreach ($modelOrderDeductions as $i => $eachded):
                 
            ?>           

        <tr>                
                    <td class="text-right td-in-6">

                            Deductions               

                <a class="btn btn-xs btn-theme " href="javascript:void(0);" onclick="addTableRow($('#order_final_ded_table'));"><i class="fa fa-plus"></i></a>             

                    </td>

                    <td>

                    <?php // echo $form->textField($eachded, "[" . $i . "]particular", array('class' => 'go particular', 'placeholder' => 'Particulars')); ?>                    
                    <?php echo $form->dropDownList($eachded,  "[" . $i . "]particular", MasFooterItems::getSaleDeductions(), array('prompt' => 'Select','class'=>'form-control', 'style' => 'width:150px')); ?>     
                    </td>

                    <td>

                     <?php echo $form->textField($eachded, "[" . $i . "]particular_value", array('onkeyup' => 'calculateorderValue($("#order_item_table"),this.id);', 'onkeypress' => 'return isNumberKey(event)', 'class' => 'value_rate go text-right', 'placeholder' => '0.00')); ?>                    

                    </td>

                    <td>

                     <?php echo $form->textField($eachded, "[" . $i . "]calculated_value", array('readonly' => true, 'class' => 'value_rate deductions_value go text-right')); ?>                                    

                    </td>    

                    <td width="0">

                    <?php echo CHtml::link('<i class="fa fa-times"></i>', 'javascript:void(0);', array('class'=>'btn btn-xs btn-danger','onclick' => 'removeExtrasRow($("#order_final_ded_table"), this)')); ?>                    

                    </td>      

                  <?php $grand_total -=$eachded->calculated_value; ?>            



        </tr>        



            <?php 
         
            endforeach;*/ ?>    



    </table-->  
    <table class="table table-hover table-bordered table-nexted order_grand_total">
			
        
         <tr class="summary_tr total_val">
                <td class="text-right table_total_title" width="70%">
                    <h2>Discount(%)</h2>
                </td>
                <td width="30%" class="text-right table_total bg-danger nw">
                        <div class="tex-ed-nw">
                        <?php echo $form->textField($model, 'total_discount_percentage', array('class' => 'col-sm-3 txt-6  form-control_1 text-right', 'placeholder'=>'%','onkeypress' => 'return isPositiveNumber(event)','onkeyup'=>'calculateOrderTableDiscount($("#order_item_table"),this.id);'));?>
                        <?php echo  $form->hiddenField($model,'total_discount_amount');?><h1 class="cell-right"><span id="span_total_discount_amount" class="txt2nw"><?php echo number_format($model->total_discount_amount,2);?></span></h1>
                    </div>
                </td>
            </tr>
            
             <tr class="" style="background-color:#e7e7e7c7;">
                <td class="text-right table_total_title" width="70%">
                    <h2>Total After Discount</h2>
                </td>
                <td width="30%" class="text-right table_total">
                    <h2 class="cell-right subtotal">
                        <?php echo Yii::app()->numberFormatter->formatCurrency($sub_total,"");?>
                    </h2>
                </td>
            </tr>
            
            	<tr class="summary_tr total_val">
            <td class="text-right table_total_title" width="70%">
                <h1>VAT</h1></td>
            <td width="30%" class="text-right table_total">
                <h1 class="vat_total_val cell-right">
                    <?php echo Yii::app()->numberFormatter->formatCurrency($total_vat, " "); 
                    $grand_total+=$total_vat;
                    ?>
                </h1>
            </td>
        </tr>
        
            <tr class="summary_tr bg-total">

                <td width="70%" class="text-right table_total_title">

                    <h1>Grand Total</h1></td>

                <td width="30%" class="text-right table_total">

                    <h1 class="grandtotal" class="text-right">

                <?php echo Yii::app()->numberFormatter->formatCurrency($grand_total, " "); ?>

                </h1></td>

            </tr>

        </table>

</div>
</div>
<?php 

$cs = Yii::app()->getClientScript();
$cs->registerScript('InsertNewRow', 'function InsertNewRow(table_id,rowid)
        {
        //    var current_row = $(this).closest("table").children("tr:last");
    
    
         var jQtable=table_id;
        $(".quotation-helper,.purchase-helper,.stock-helper").each(function(){ 
        $(this).hide(); 
        $(this).find("table").remove();
        });
        
                formIdStarter   =   jQtable.attr("id").split(/_(.+)?/)[0];
                lastId = jQtable.find("tr:last input:first").attr("id");
                
                thenum = lastId.match(/\d+/g);
                newId = Number(thenum) + 1;
                
                newrow= jQtable.find("tr:last").clone();
                newrow.find("label:first").html(newId+1);
                newrow.find("input,textarea,checkbox,select,.errorMessage").each(function() {
                    this.id= this.id.replace(/\d+/,newId);
                   if(!$(this).is(":checkbox"))
                        this.value  = "";
                    else
                        $(this).prop("checked", false);
                    (this.name!==undefined) ? this.name= this.name.replace(/\d+/,newId) : this.style  =   "display:none;";});
                jQtable.append(newrow);
                //auto_complete2(formIdStarter,newId);
                //$.colorbox.resize();
                
                var current_row = $("#"+rowid).parents("tr:last");
                
                lastrow=newId;
                
                
                lastId = $("#"+rowid).closest("tr").find("input[type=text]").attr("id");
                
                thenum = lastId.match(/\d+/g);
                
                
                thenum=parseInt(thenum);
                
                
                lastrow=parseInt(lastrow);
                diff=lastrow-thenum;
                
                
                for(j=thenum;j<lastrow;j++)
                {
                if(j==thenum)
                {
                    
                row_need_to_replace    =   current_row.next();
                }
                else {
                    
                row_need_to_replace    =   row_need_to_replace.next();
                }
                }
                last_replace=row_need_to_replace;
                for(j=lastrow;j>thenum;j--)
                {
                if(j==thenum)
                {
                    
                row_need_to_replace    =   current_row.next();
                
                if(current_row.find("input,textarea").length>0)
                {
                     
                var i=0;
                row_need_to_replace.find(":input").each(function(){
                input_need_to_replace=current_row.find(":input :eq("+i+")");
                temp   =   input_need_to_replace.val();
                input_need_to_replace.val($(this).val());
                $(this).val(temp);
                this_readonly=$(this).is(\'[readonly]\')
                input_need_to_replace_readonly=input_need_to_replace.is(\'[readonly]\');
                $(this).attr(\'readonly\',input_need_to_replace_readonly);
                input_need_to_replace.attr(\'readonly\',this_readonly);
                i++;
            });
        }
                }
                else {
                    
                if(j==lastrow)
                {
                    
                pre=last_replace;
                row_need_to_replace    =   last_replace.prev();
                }
                else {
                    
                pre=row_need_to_replace;
                row_need_to_replace    =   row_need_to_replace.prev();
                }
                if(pre.find("input,textarea").length>0)
        {
            
            var i=0;
                row_need_to_replace.find(":input").each(function(){
                input_need_to_replace=pre.find(":input :eq("+i+")");
                temp   =   input_need_to_replace.val();
                input_need_to_replace.val($(this).val());
                $(this).val(temp);
                this_readonly=$(this).is(\'[readonly]\')
                input_need_to_replace_readonly=input_need_to_replace.is(\'[readonly]\');
                $(this).attr(\'readonly\',input_need_to_replace_readonly);
                input_need_to_replace.attr(\'readonly\',this_readonly);
                i++;
            });
        }
                }
                }

        }', CClientScript::POS_HEAD);

?> 
<?php

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

$cs->registerScript("autoCompleteProduct", "function autoCompleteProduct(field_id,frm)
{
    var customer_id =$('#Order_customer_id').val();
    if(customer_id==''){
            t8.error('Please select a customer'); 
            return false;
        }else{ 
    var arr_fields= field_id.split('_');
    var model_name   = arr_fields[0];
    var row_field  = arr_fields[1];
    var all_str  = $('#'+field_id).val();

    if(all_str == 'memo'){
        $('#OrderItem_'+row_field+'_quantity').attr( 'readonly', true );
        $('#OrderItem_'+row_field+'_rate').attr( 'readonly', true );
        $('#OrderItem_'+row_field+'_unit').attr( 'readonly', true );
        $('#OrderItem_'+row_field+'_addition_percentage').attr( 'readonly', true );
        $('#OrderItem_'+row_field+'_deduction_percentage').attr( 'readonly', true );
        $('#OrderItem_'+row_field+'_description').attr( 'readonly', false );
        $('#OrderItem_'+row_field+'_description').val('');
        $('#OrderItem_'+row_field+'_quantity').val('');
        $('#OrderItem_'+row_field+'_unit').val('');
        $('#OrderItem_'+row_field+'_addition_percentage').val('');
        $('#OrderItem_'+row_field+'_deduction_percentage').val('');
        $('#OrderItem_'+row_field+'_addition_amount').val('');
        $('#OrderItem_'+row_field+'_deduction_amount').val('');
        $('#OrderItem_'+row_field+'_product_id').val('');

    }else{

        $('#OrderItem_'+row_field+'_quantity').attr( 'readonly', false );
        $('#OrderItem_'+row_field+'_rate').attr( 'readonly', false );
        $('#OrderItem_'+row_field+'_unit').attr( 'readonly', false );
        $('#OrderItem_'+row_field+'_addition_percentage').attr( 'readonly', false );
        $('#OrderItem_'+row_field+'_deduction_percentage').attr( 'readonly', false );
        $('#OrderItem_'+row_field+'_deduction_percentage').attr( 'readonly', false );
        }

        var url = '" . Yii::app()->createUrl('quotation/GetProducts') . "'+'&frm='+frm;
        $('#'+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 desc=ui.item.description; 
                var unit_id=ui.item.unit_id;  
                var unit_name=ui.item.unit_name;
                var tax_percentage = 0;
                //alert(ui.item.tax_code);
                if(ui.item.tax_code!=null)
                    tax_percentage = ui.item.tax_code;
                $('#OrderItem_'+row_field+'_description').val(desc);
                $('#OrderItem_'+row_field+'_unit').val(unit_name); 
                $('#OrderItem_'+row_field+'_product_name').val(ui.item.part_number); 
                $('#OrderItem_'+row_field+'_unit_id').val(unit_id);  
                $('#OrderItem_'+row_field+'_product_id').val(product_id); 
                                
                var item_type = ui.item.other;

                $('#product_'+row_field+'_inventorytype').val(item_type); 


                if(product_id > 0){
                    jQuery.ajax({
                       'type': 'post',
                       'dataType': 'json',
                       'url': '" . Yii::app()->createUrl('order/getunitdrop') . "',
                       'data': {'row_field' : row_field, 'product_id' : product_id},
                       'cache': false,
                       'success': function(data) {
                           $('#unit_'+row_field).html(data.drop);
                           return false;
                       }
                   });
                   var exchange_rate = $('#Order_exchange_rate').val();
                   jQuery.ajax({
                       'type': 'post',
                       'dataType': 'json',
                       'url': '" . Yii::app()->createUrl('quotation/getalldetailsforproduct') . "',
                       'data': {'product_id' : product_id,'customer_id':customer_id},
                       'cache': false,
                       'success': function(data) {
                       //alert(data.price);
                       //alert(row_field);
                            var item_price=data.price;
                            var bonus_qty=data.bonus_qty;
                            if(exchange_rate > 0){
                            item_price = (item_price / exchange_rate).toFixed(3);
                           }
                            $('#OrderItem_'+row_field+'_rate').val(item_price);
                            if(item_price>0){
                                 $('#OrderItem_'+row_field+'_rate').attr( 'readonly', true );  
                            }
                            $('#OrderItem_'+row_field+'_bonus_qty').val(bonus_qty);
                           calculateorderValue($('#order_item_table'));
                           return false;
                       }
                   });


                }
                                
                                
                var Order_invoice_type_id  = $('#Order_invoice_type_id').val(); 
                if(ui.item.label == 'memo'){                                    
                    $('#OrderItem_'+row_field+'_quantity').attr( 'readonly', true );
                    $('#OrderItem_'+row_field+'_rate').attr( 'readonly', true );
                    $('#OrderItem_'+row_field+'_unit').attr( 'readonly', true );
                    $('#OrderItem_'+row_field+'_addition_percentage').attr( 'readonly', true );
                    $('#OrderItem_'+row_field+'_deduction_percentage').attr( 'readonly', true );
                    $('#OrderItem_'+row_field+'_description').attr( 'readonly', false );
                    $('#OrderItem_'+row_field+'_description').val('');
                    $('#OrderItem_'+row_field+'_quantity').val('');
                    $('#OrderItem_'+row_field+'_amount').val('');                                    
                    $('#OrderItem_'+row_field+'_unit').val('');
                    $('#OrderItem_'+row_field+'_addition_percentage').val('');
                    $('#OrderItem_'+row_field+'_deduction_percentage').val('');
                    $('#OrderItem_'+row_field+'_addition_amount').val('');
                    $('#OrderItem_'+row_field+'_deduction_amount').val('');

                    $('#OrderItem_'+row_field+'_product_id').val('');

                }
                if(Order_invoice_type_id>0){

                        jQuery.ajax({
                                'dataType' : 'json',
                              'type'  : 'post',
                              'data'  : 'id='+Order_invoice_type_id,
                              'url'  : $('#liveSite').val()+'index.php?r=masinvoicetype/getInvoiceTypeTax',
                              'cache': false,
                              'success':function(data){

                                if(data.status=='success'){ 
                                    if(item_type == '2'){  // itemtype = 2 means service items
                                        $('#OrderItem_'+row_field+'_tax_vat_percentage').val(tax_percentage);
                                                $('#check_tax_vat_percentage_'+row_field).val(tax_percentage);
                                        calculateorderValue($('#order_item_table'));
                                    }
                                    else{
                                        if(data.tax == 'Y'){
                                                $('#OrderItem_'+row_field+'_tax_vat_percentage').val(tax_percentage);
                                                $('#check_tax_vat_percentage_'+row_field).val(tax_percentage); 
                                            }
                                        else{
                                            $('#OrderItem_'+row_field+'_tax_vat_percentage').val(0);
                                                $('#check_tax_vat_percentage_'+row_field).val(tax_percentage); 
                                        }
                                        calculateorderValue($('#order_item_table'));
                                    }

                                }
                               }
                            });

                    }
		
                                
                                
                                 
                                 

                            }

			})


}
		}", CClientScript::POS_HEAD);

$cs->registerScript("checkall" ,"function checkall()
        {
        $('#ckbCheckAll').click(function () {
            $('.checkBoxClass').prop('checked', $(this).prop('checked'));
        })
    }", CClientScript::POS_HEAD);
    
    $cs->registerScript("calculateorderValue", " function calculateorderValue(jQtable,id,frm) {
        formIdStarter =   jQtable.attr('id').split(/_(.+)?/)[0];
        var count,qty,rate,amount,add_ded,discount,net,count_hash;
        field_val='';
        if(id!=undefined){
            arr_field_id =  id.split('_');
            field_val = arr_field_id[2];
        }
        var other_additions = 0;
        var other_deductions = 0;
        var total = 0;
        var grand_total =   0;
        var total_vat_amount	= 0;
        var vat_percentage  = $('#Order_vat_percentage').val();
        var cnt=0;
        
        //code added by mereena
        var total_discount_percentage  = $('#Order_total_discount_percentage').val();
        var total_deduction_amt=0;
        var total_amount_without_discount=0;
        jQtable.find('tr:gt(0)').each(function() {
        //if($('#OrderItem_'+cnt+'_checked').prop('checked')==true){
            net = 0;
            qty =   $(this).find('[id $=_quantity]').val();
            if(qty==undefined)
            qty=0;
            rate =   $(this).find('[id $=_rate]').val();
            if(rate==undefined)
            rate=0;
            amount  =   (Number(qty)*Number(rate)).toFixed(2);
            
            //code added by mereena on 10/11/2023
            total_amount_without_discount+=Number(amount);
            //end
            
            add_ded  =   $(this).find('[id $=_addition_percentage]').val();
            discount  =   $(this).find('[id $=_deduction_percentage]').val();
            if(add_ded === '-' || add_ded === '*'){
                add_ded = '';
            }
            if(add_ded!=undefined)
            {
                count = add_ded.match(/%/g);
                count_hash=add_ded.match(/#/g);
                add_ded   =   add_ded.replace(/#/,'');
                add_ded   =   add_ded.replace(/%/,'');              
                var value = Number(add_ded)/100;
            }else{
                add_ded=0;
            }                   
            if(isNumber(add_ded)){
                add_ded  =   (count!==null && count.length>0) ? (amount*value) : add_ded;
                add_ded  =   (count_hash!==null && count_hash.length>0) ? (Number(add_ded)*qty) : add_ded;
            }else{
                add_ded=0;
            }
            if(discount!=undefined)

            {

                count = discount.match(/%/g);

                discount   =   discount.replace(/%/,'');

                var value = Number(discount)/100;

            }

            if(isNumber(discount)){
                //discount  =  (count!==null && count.length>0) ? ((Number(add_ded)+Number(amount))*value) : discount;
                 discount  =  ((Number(add_ded)+Number(amount))*value);
            }
            else{
                discount   =0;
            }
            net =   Number(add_ded) - Number(discount);

            

            net =   (Number(net)+Number(amount)).toFixed(2);

            if(net != 0){

                total   =   Number(total)+Number(net);

            }

            else{

                total   =   Number(total);

            }




            $(this).find('[id $=_amount]').val(Number(amount).toFixed(2));

                    if($(this).find('[id $=_tax_vat_percentage]').length > 0)
                    {
                     tax_percentage = $(this).find('[id $=_tax_vat_percentage]').val();
                         var  tax_amount = (net * tax_percentage) / 100;
                                     $(this).find('[id $=_tax_vat_amount]').val(Number(tax_amount).toFixed(2));

                         total_vat_amount+=tax_amount;
                    }
            $(this).find('[id $=_addition_amount]').val(Number(add_ded).toFixed(2));

            $(this).find('[id $=_deduction_amount]').val(Number(discount).toFixed(2));

            $(this).find('[id $=_net_amount]').val(Number(net).toFixed(2));
            //}
             cnt++;
             
             
             //code added by mereena on 09/11/2023 to calculate total discount
                total_deduction_amt+=Number(discount);
        });
        other_additions    = 0.00;
        other_deductions   = 0.00;

        /*other_additions    =   calculateExtra($('#'+formIdStarter+'_final_add_table'),total);

        other_deductions  =    calculateExtra($('#'+formIdStarter+'_final_ded_table'),total);*/




            grand_total =   Number(total)   +   Number(other_additions);

            grand_total -=  Number(other_deductions);



                    if($('.'+formIdStarter+'_grand_total .vat_total_val').length > 0){
                    $('.'+formIdStarter+'_grand_total .vat_total_val').text(Number(total_vat_amount).toFixed(2));
                    grand_total = parseFloat(grand_total) + parseFloat(total_vat_amount);
            }

            /* if(other_deductions > total && frm!=''){
                $('#'+frm).val('');
                calculateorderValue(jQtable,frm);
            }else{*/
                $('.'+formIdStarter+'_total .total').html(Number(total_amount_without_discount).toFixed(2));
                $('.'+formIdStarter+'_grand_total .subtotal').html(Number(total).toFixed(2));
                $('.'+formIdStarter+'_grand_total .grandtotal').text(Number(grand_total).toFixed(2));
                $('#grnd_total_id').val(Number(grand_total).toFixed(2));
            //}
            
             //code added by mereena on 09/11/2023
                
                $('#Order_total_discount_amount').val(Number(total_deduction_amt).toFixed(2));
                
                $('#span_total_discount_amount').html(Number(total_deduction_amt).toFixed(2));
                var average_discount = '';
                if(total_amount_without_discount > 0 && total_deduction_amt > 0){
                    average_discount = (Number(total_deduction_amt) / Number(total_amount_without_discount) * 100);
                }
                console.log(field_val);
                if(field_val=='deduction'){
                    $('#Order_total_discount_percentage').val(Number(average_discount).toFixed(2));
                }
            
            calculateOrderTableDiscount($('#order_item_table'),$('#Order_total_discount_percentage'));
            
            return false;
    }", CClientScript::POS_HEAD);
     /*$cs->registerScript("calculateorderValue", " function calculateorderValue(jQtable,frm) {
                formIdStarter =   jQtable.attr('id').split(/_(.+)?/)[0];
                var count,qty,rate,amount,add_ded,discount,net,count_hash;

                var other_additions = 0;
                var other_deductions = 0;
                var total = 0;
                var grand_total =   0;
                var total_vat_amount	= 0;
                var vat_percentage  = $('#Order_vat_percentage').val();
                
                jQtable.find('tr:gt(0)').each(function() {
                    net = 0;
                    qty =   $(this).find('[id $=_quantity]').val();
                    rate =   $(this).find('[id $=_rate]').val();
                    amount  =   (Number(qty)*Number(rate)).toFixed(2);
                    if(formIdStarter!='purchasingOrder' && formIdStarter !='productionGoodsReceipt'){
                        add_ded  =   $(this).find('[id $=_addition_percentage]').val();
                        discount  =   $(this).find('[id $=_deduction_percentage]').val();
                    if(add_ded === '-' || add_ded === '*'){
                        add_ded = '';
                    }
                    if(add_ded!=undefined)
                    {
                        count = add_ded.match(/%/g);
                        count_hash=add_ded.match(/#/g);
                        add_ded   =   add_ded.replace(/#/,'');
                        add_ded   =   add_ded.replace(/%/,'');              
                        var value = Number(add_ded)/100;
                    }                   
                    if(isNumber(add_ded)){
                        add_ded  =   (count!==null && count.length>0) ? (amount*value) : add_ded;
                        add_ded  =   (count_hash!==null && count_hash.length>0) ? (Number(add_ded)*qty) : add_ded;
                    }
                    if(discount!=undefined)

                    {

                        count = discount.match(/%/g);

                        discount   =   discount.replace(/%/,'');

                        var value = Number(discount)/100;

                    }

                    if(isNumber(discount))

                    discount  =  (count!==null && count.length>0) ? ((Number(add_ded)+Number(amount))*value) : discount;

                    net =   Number(add_ded) - Number(discount);

                }

                net =   (Number(net)+Number(amount)).toFixed(2);

                if(net != 0){

                    total   =   Number(total)+Number(net);

                }

                else{

                    total   =   Number(total);

                }
        	
    				
    					

                $(this).find('[id $=_amount]').val(Number(amount).toFixed(2));
        		
        		if($(this).find('[id $=_tax_vat_percentage]').length > 0)
    		        {
                         tax_percentage = $(this).find('[id $=_tax_vat_percentage]').val();
    		             var  tax_amount = (net * tax_percentage) / 100;
    					 $(this).find('[id $=_tax_vat_amount]').val(Number(tax_amount).toFixed(2));
                                       
    		             total_vat_amount+=tax_amount;
    		        }

                $(this).find('[id $=_addition_amount]').val(Number(add_ded).toFixed(2));

                $(this).find('[id $=_deduction_amount]').val(Number(discount).toFixed(2));

                $(this).find('[id $=_net_amount]').val(Number(net).toFixed(2));

            });

            other_additions    =   calculateExtra($('#'+formIdStarter+'_final_add_table'),total);

            other_deductions  =    calculateExtra($('#'+formIdStarter+'_final_ded_table'),total);


           

                grand_total =   Number(total)   +   Number(other_additions);

                grand_total -=  Number(other_deductions);
                
        		
        		
        		if($('.'+formIdStarter+'_grand_total .vat_total_val').length > 0){
    			$('.'+formIdStarter+'_grand_total .vat_total_val').text(Number(total_vat_amount).toFixed(2));
    			grand_total = parseFloat(grand_total) + parseFloat(total_vat_amount);
    		}
        		
                if(other_deductions > total && frm!=''){
                    $('#'+frm).val('');
                    calculateorderValue(jQtable,frm);
                }else{
                    $('.'+formIdStarter+'_total .total').html(Number(total).toFixed(2));
                    $('.'+formIdStarter+'_grand_total .grandtotal').text(Number(grand_total).toFixed(2));
                    $('#grnd_total_id').val(Number(grand_total).toFixed(2));
                }
                return false;
        }", CClientScript::POS_HEAD); */
        
         $cs->registerScript("calculateOrderTableDiscount", " function calculateOrderTableDiscount(jQtable,id) {
        
       
        formIdStarter =   jQtable.attr('id').split(/_(.+)?/)[0];
        var count,qty,rate,amount,add_ded,discount,net,count_hash;
        var total = 0;
        var total_discount_percentage = $('#Order_total_discount_percentage').val();
        jQtable.find('tr:gt(0)').each(function() {
            var model_id=this.id;
            var arr_fields= model_id.split('_');
            var row_field=arr_fields[1];
            net = 0;
            qtn_qty     =   $(this).find('[id $=_quantity]').val();
            qtn_rate    =   $(this).find('[id $=_rate]').val();
            qtn_amount  =   Number(qtn_qty) * Number(qtn_rate);
            item_discount = 0;
            if(total_discount_percentage > 0){
                item_discount = (qtn_amount * total_discount_percentage) / 100;
            }
            if(total_discount_percentage > 0 || total_discount_percentage!=''){
            $(this).find('[id $=_deduction_percentage]').val(total_discount_percentage+'%');
            }
            else{
                $(this).find('[id $=_deduction_percentage]').val('');
            }
            
        });
        //calculateorderValue($('#order_item_table'));
    
    }", CClientScript::POS_HEAD); 
     
        ?>
             
 

<script>
    $(function () {
               
                 var exp_date = $("#Order_delivery_date").val().split("/");
                 var current_2 = new Date(exp_date[2], exp_date[1] - 1, exp_date[0]);
                 $('#OrderItem_0_expected_delivery_date').datetimepicker({  
                    
                     minDate:current_2,
                     format: 'DD/MM/YYYY'
                 });
                  $("#Order_delivery_date").on("dp.change", function (e) {
                       
                          var d = new Date(e.date);
                          var duedate = new Date(d);
                          duedate.setDate(d.getDate() + 0);
                          var month = String(duedate.getMonth() + 1);
                          var day = String(duedate.getDate());
                          const year = String(duedate.getFullYear());

                          if (month.length < 2) month = '0' + month;
                          if (day.length < 2) day = '0' + day;

                          var final = `${day}/${month}/${year}`;
                          //$('#Contract_contract_date_to').val(final);
                            var i=0;
                            for(i=0;i<50;i++){
                                        try{
                                            $('#OrderItem_'+i+'_expected_delivery_date').val(final);
                                        }catch(e){}
                            }
                          
                  });

    });
   
</script>


<style type="text/css">
    body table .desc, body table .desc.go {
    min-width: 170px;
}
</style>

<script>
$(document).bind("keydown", function(event){
    
    var allclass = $(event.target).attr("class");
    var substring = 'en-text-area';
    var id = $(event.target).attr("id");
    
    if(allclass.indexOf(substring) !== -1){
     
        try{
            if (event.which == 13) {
                document.getElementById(id).value =document.getElementById(id).value;
            }
        }catch(e){}
    }else if (event.keyCode == 13) {
        return false;
    }
});
</script>
