<?php $editable=false; if($order[0]['order_status']=='Open'){$editable=true;}?>
<style>                                    
    
    hr{
        border-top: 1px solid #188ae2;
    }
    #tblproducts tr td {
        border: 1px solid #188ae2;
        color: #000 !important;
    }
    #tblproducts tr th {
        background: #188ae2;
        border: 1px solid #188ae2;
        color: #000 !important;
    }
    p{
        margin: 0px !important;
        color: #000 !important;
    }
</style>
<div class="wrapper">
            <div class="container">
                <!-- Page-Title -->
                <div class="row">
                    <div class="col-sm-12">
                        <h4 class="page-title">Franchise Invoice</h4>
                    </div>
                    
                </div>
               
                <div class="row">
                    <div class="col-md-12">
                        <div class="panel panel-default">
                            <!-- <div class="panel-heading">
                                <h4>Invoice</h4>
                            </div> -->
                            <div class="panel-body">
                                <div class="clearfix">
                                    <div class="pull-left">
                                        <p><?php echo $business[0]['business_address'];?></p> 
                                        <p><?php echo $business[0]['business_phone1'];?></p> 
                                    </div>
                                    <div class="pull-right">
                                        <h3 class="logo invoice-logo"><?php if(isset($business)){ echo "<img style='width:150px;' src='".base_url().'assets/images/business/'.$business[0]['business_logo']."' alt='".$business[0]['business_name']."' />";} else {echo 'SalonPK';}?></h3>
                                    </div>
                                </div>
                                <hr>
                                <div class="row">
                                    <h1 style="text-align: center; color:#188ae2;"><strong>SALE INVOICE</strong></h1>
                                </div>
                                     
                                <div class="row">
                                    <div class="col-md-12">

                                        <div class="pull-left m-t-10">
                                            <input name="orderid" id="orderid"  type="hidden" value="<?php echo $order[0]['id_franchise_orders']; ?>"/>
                                            <input name="customerid" id="customerid" type="hidden"  value="<?php echo $franchise->id_franchises; ?>"/>
                                            <input name="customername" id="customername" type="hidden"  value="<?php echo$franchise->franchise_name; ?>">
                                            <input name="customerntn" id="customerntn" type="hidden"  value="<?php echo $franchise->franchise_ntn; ?>">
                                            <p style="background: #188ae2; color:#000 !important;"><strong>Bill To:</strong></p>
                                            <address>
                                                <strong>Company: <span id="companyname"><?php echo $franchise->franchise_name; ?> <?php echo $order[0]['franchise_order_extra'];?></span></strong><br>
                                              <strong>NTN: <?php echo $franchise->franchise_ntn; ?></strong><br>
                                              <strong>Address:<?php echo $franchise->franchise_address; ?></strong><br>
                                              <strong>Email:<?php echo $franchise->franchise_email; ?></stong><br>
                                              <strong>Phone:</strong><?php echo $franchise->franchise_office_phone; ?>
                                            </address>
                                        </div>
                                        <div class="pull-right m-t-10">
                                            <table>
                                                <tr><td><strong>CUSTOMER ID:</strong> </td><td style="float:right"><?php if(null!==$franchise->id_franchises){ echo $franchise->id_franchises;}else{echo '1';}?></td></tr>
                                                <td><strong>INVOICE DATE: </strong></td><td style="float:right"><?php if(null !==$order[0]['invoice_date'] && $order[0]['invoice_date']!==''){echo $order[0]['formatted_invoice_date'];} else{ echo date('d-m-Y');} ?></td></tr>
                                                <tr><td><input <?php if(null ==$order[0]['invoice_date'] || $order[0]['invoice_date']=='') {?>type="text"<?php }else{ ?>type="hidden"<?php }?> id="invoice_date" value = "<?php if(null !==$order[0]['invoice_date'] && $order[0]['invoice_date']!==''){echo $order[0]['invoice_date'];} else{ echo date('Y-m-d H-i-s');} ?>"></td><td></tr>
                                                <tr><td><strong>DUE DATE: </strong></td><td style="float:right"><?php if(null !==$order[0]['due_date'] && $order[0]['due_date']!==''){echo $order[0]['due_date'];} ?></td></tr>
                                                <tr><td><strong>INVOICE #:</strong> </td><td><input id="vendorseq" style="border:none; text-align: right; float:right; width:80px;" value="<?php echo $order[0]['id_franchise_orders']; ?>"></td></tr>
                                                <tr><td><strong>VENDOR INVOICE SEQ:</strong> </td><td><input id="invoicenumber" style="border:none; text-align: right; float:right; width:80px;" value="<?php if($editable==false){echo $order[0]['invoice_number']; }else{if(null!==$franchiseinvoicenumber->invoice_number){ echo $franchiseinvoicenumber->invoice_number;}else{echo '1';}}?>"></td></tr>
                                                
                                            </table>
                                        </div>
                                    </div><!-- end col -->
                                </div>
                                <!-- end row -->
                               
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="table-responsive">
                                        <table class="table m-t-10" id="tblproducts">
                                                <thead>
                                                    <tr>
                                                        <th class="hidden-print">#</th>
                                                        <th class="hidden-print">Brand</th>
                                                        <th>Item</th>
                                                        <th class="hidden-print">Batch</th>
                                                        <th class="hidden-print">Sold by</th>
                                                        
                                                        <th class="" style='text-align:right;'>Unit Price</th>
                                                        <th>Qty.</th>
                                                        <th style='text-align:right;'>Total Price</th>
                                                        <th class="" style='text-align:right;'>Total Discount</th>
                                                        <th class="hidden-print" style='text-align:right;'>Discount(%)</th>
                                                        <th style='text-align:right;'>Total Price</th>
                                                        <th style='text-align:right;'>Tax Rate</th>
                                                        <th class="hidden-print" style='text-align:right;'>Tax Value</th>
                                                        <th style='text-align:right;'>Value Inclusive of Tax</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php $subtotal=0; if(isset($order)){
                                                        $x=1; $total_price_bf_tax=0; $total_price_with_tax=0; $total_tax=0; $tax_perc=0; $totalproduct_discount=0;
                                                        foreach($order as $product){
                                                            $subtotal=$subtotal + ($product['unit_price']*$product['qty']);                                                            
                                                        ?>
                                                        <tr id="idtr">
                                                            <td fpid="<?php echo $product['id_franchise_order_products']; ?>" class="hidden-print"><input type="hidden" id="product_id" name="product_id" value="<?php echo $product['product_id'];?>"><?php echo $x;?></td>
                                                            <td class="hidden-print"><?php echo $product['business_brand_name']; ?></td>
                                                            <?php 
                                                                $dateObj   = DateTime::createFromFormat('!m', intval($product['order_month']));
                                                                $monthName = $dateObj->format('F');
                                                            ?>
                                                            <td><span class="productname"><?php echo $product['product_name']; ?> <?php echo $product['product_detail'];?></span>&nbsp;<span class="category"><?php echo $product['product_type']=='Subscription' ? $monthName.'-'.$product['order_year'] :  ' ';?></span></td>
                                                            <td class="hidden-print">
                                                                <input type="hidden" id="batch_id" name="batch_id" value="<?php echo $product['batch_id'];?>">
                                                                <input type="hidden" id="batch" name="batch" value="<?php echo $product['batch'];?>">
                                                                <input type="hidden" id="batch_amount" name="batch_amount" value="<?php echo $product['batch_amount'];?>">
                                                                <?php echo $product['batch']; ?>
                                                            </td>
                                                            <td class="hidden-print"><?php echo $product['staff_name']; ?></td>
                                                            
                                                            <td class="" style='text-align:right;'><?php echo $product['unit_price']; ?></td>
                                                            <td><?php echo $product['qty']; ?></td>
                                                            <td  style='text-align:right;'><?php echo $product['unit_price']*$product['qty']; ?></td>                                                            
                                                            <td class="" style='text-align:right;'><?php echo $product['unit_discount']*$product['qty']; ?></td>
                                                            <?php $totalproduct_discount = $totalproduct_discount + ($product['unit_discount']*$product['qty']);?>
                                                            <td class="hidden-print" style='text-align:right;'><span id="disc_perc"><?php if($product['unit_price']>0) {echo number_format((($product['unit_discount']*$product['qty'])*100)/($product['unit_price']*$product['qty']),2);} else{ echo '0';}?></span>%</td>
                                                            <td style='text-align:right;' combat = '<?php echo $product['discounted_price']; ?>'><?php echo CURRENCY_CODE;?>.<span class="combat" id="unitcost<?php echo $product['product_id']; ?>"><?php echo $product['discounted_price']; ?></span></td>
                                                           
                                                            <?php if(defined('FRANCHISE_TAX')){ if(FRANCHISE_TAX=="after"){?>
                                                                <td style='text-align:right;' class="tax_perc"><input onchange="document.getElementById(<?php echo $product['id_franchise_order_products'];?>).value=<?php echo $product['discounted_price']; ?>*this.value/100; updatetotal_new();" name='tax_perc' style="width:50px; border:none; text-align:right;" value="<?php if($order[0]['order_status']=='Open'){echo $product['product_sales_tax']; }else{echo round( ($product['product_tax'] *100)/$product['discounted_price'], 2);}?>"></td>
                                                            <?php } else {?>
                                                                <td style='text-align:right;' class="tax_perc"><input onchange="document.getElementById(<?php echo $product['id_franchise_order_products'];?>).value=<?php echo $product['discounted_price']; ?>*this.value/100; updatetotal_new();" name='tax_perc' style="width:50px; border:none; text-align:right;" value="<?php if($order[0]['order_status']=='Open'){echo $product['product_sales_tax']; }else{echo round( ($product['product_tax'] *100)/($product['unit_price']*$product['qty']), 2);}?>"></td>
                                                            <?php } } else { ?>  
                                                                <td style='text-align:right;' class="tax_perc"><input onchange="document.getElementById(<?php echo $product['id_franchise_order_products'];?>).value=<?php echo $product['discounted_price']; ?>*this.value/100; updatetotal_new();" name='tax_perc' style="width:50px; border:none; text-align:right;" value="<?php if($order[0]['order_status']=='Open'){echo $product['product_sales_tax']; }else{echo round( ($product['product_tax'] *100)/$product['discounted_price'], 2);}?>"></td>
                                                            <?php } ?>
                                                            <?php $total_price_bf_tax = $total_price_bf_tax + $product['discounted_price']; ?>
                                                            <?php if($order[0]['order_status']=='Open'){?>
                                                                <?php if(defined('FRANCHISE_TAX')){ if(FRANCHISE_TAX=="after"){?>
                                                                    <td class="hidden-print" style='text-align:right;'><input id="<?php echo $product['id_franchise_order_products'];?>" style="text-align:right; border:none; width:70px;" onchange="updatetotal_new();" name="product_tax" value="<?php  $product_price=($product['unit_price']-$product['unit_discount'])*$product['qty']; $product_tax = $product_price*$product['product_sales_tax']/100; echo $product_tax; ?>"> </td>
                                                                <?php } else {?>
                                                                    <td class="hidden-print" style='text-align:right;'><input id="<?php echo $product['id_franchise_order_products'];?>" style="text-align:right; border:none; width:70px;" onchange="updatetotal_new();" name="product_tax" value="<?php  $product_price= $product['unit_price']*$product['qty']; $product_tax = $product_price*$product['product_sales_tax']/100; echo $product_tax; ?>"> </td>
                                                                <?php } } else { ?>    
                                                                    <td class="hidden-print" style='text-align:right;'><input id="<?php echo $product['id_franchise_order_products'];?>" style="text-align:right; border:none; width:70px;" onchange="updatetotal_new();" name="product_tax" value="<?php  $product_price=($product['unit_price']-$product['unit_discount'])*$product['qty']; $product_tax = $product_price*$product['product_sales_tax']/100; echo $product_tax; ?>"> </td>
                                                                <?php } ?>
                                                            <?php } else { ?>
                                                                <td style='text-align:right;' class="hidden-print"><input style="text-align:right; border:none; width:70px;" readonly="readonly"  name="product_tax" value="<?php echo $product['product_tax']; ?>"></td>
                                                            <?php $product_tax =  $product['product_tax'];} ?>
                                                            <td style='text-align:right;'><?php echo number_format($product['discounted_price']+$product_tax,2);?></td>
                                                            <?php $total_tax=$total_tax + $product_tax;?>
                                                            <?php $total_price_with_tax = $total_price_with_tax + $product['discounted_price']+$product_tax;?>
                                                        </tr>
                                                        <?php $x++;}} ?>
                                                </tbody>
                                                <tfoot>
                                                    <th class="hidden-print" colspan=4></th>
                                                    <th colspan=4></th>                                                    
                                                    <th style='text-align:right;'><?php echo number_format($totalproduct_discount,2);?></th>
                                                    <th class="hidden-print"  ></th>
                                                    <th style='text-align:right;'><?php echo number_format($total_price_bf_tax,2);?></th>
                                                    <th ></th>
                                                    <th style='text-align:right;' class="taxtotal hidden-print"><?php echo number_format($total_tax,2);?></th>
                                                    <th  style='text-align:right;' ><?php echo number_format($total_price_with_tax,2);?></th>                                                    
                                                </tfoot>
                                            </table>                                           
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-sm-4 col-xs-4 col-md-4 col-lg-4 ">
                                        <div class="clearfix m-t-40">
                                            <h5 class="text-inverse font-600">Notes:</h5>
                                            <textarea style="border:none;" rows="8" id="txtremarks" class="form-control" ><?php echo $order[0]['invoice_remarks'];?></textarea>
                                        </div>                                        
                                    </div>
                                    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 col-md-offset-2 col-sm-offset-2 col-xs-offset-2">
                                        <p class="text-right"> <?php echo CURRENCY_CODE;?>. <input id="txt_org_subtotal" name="txt_org_subtotal" class="form-inline" readonly="readonly" style="text-align:right; width: 80px; border: none;" value='<?php if($subtotal!=null){ echo round($subtotal, 2); }else{echo $subtotal;}?>'></p>
                                        <p class="text-right">Product Discount <span id="txtloyalty"></span> <?php echo CURRENCY_CODE;?>.: <input readonly="readonly" class="numeric"  id="txtproductdiscount" class="form-inline " style="text-align:right;width: 80px; border: none;" value="<?php if($totalproduct_discount!=null){ echo $totalproduct_discount;} ?>"/></p>
                                        <p style="display: none;" class="text-right hidden-print"><b>After Product Discount: </b>   <?php echo CURRENCY_CODE;?>. <input id="txtsubtotal" class="form-inline" readonly="readonly" style="width: 80px; border: none;" value='<?php echo round(((float)$subtotal-(float)$totalproduct_discount+(float)$order[0]['invoice_other_charges']),2);?>'></p>
                                        
                                        <p class="text-right hidden">Discount %: <input <?php if($editable==false){echo " readonly='readonly' "; }?> class="numeric" id="discount_in_percent" class="form-inline " style="text-align:right;width: 80px; border: none;" value="<?php echo $order[0]['invoice_discount_perc']; ?>"/></p>
                                        <p class="text-right hidden">Discount <span id="txtloyalty"></span> <?php echo CURRENCY_CODE;?>.: <input <?php if($editable==false){echo " readonly='readonly' "; }?> class="numeric"  id="txtdiscount" class="form-inline " style="text-align:right;width: 80px; border: none;" value="<?php echo $order[0]['invoice_discount']; ?>"/></p>
                                        
                                        <p class="text-right">Other Charges <?php echo CURRENCY_CODE;?>.: <input <?php if($editable==false){echo " readonly='readonly' "; }?> class="numeric" onchange="updatetotal_new()" id="txtothercharges" class="form-inline " style="text-align:right;width: 80px; border: none;" value="<?php echo $order[0]['invoice_other_charges']; ?>"/></p>
                                        <hr> 
                                        
                                        <p class="text-right"><b>Amount Exclusive of Taxes: </b>:   <?php echo CURRENCY_CODE;?>. <input id="txtgross" readonly="readonly" class="form-inline " style="text-align:right;width: 80px; border: none;" value="<?php echo (float)$subtotal-(float)$totalproduct_discount+(float)$order[0]['invoice_other_charges'];?>"/></p>
                                        <div class="m-t-10 m-b-10" id="divtaxes">
                                            <p class="text-right">
                                                Amount of Product Sales Tax 
                                                <input readonly="readonly" class="numeric" id="txtsalestax"  class="form-inline " style="text-align:right; width: 80px; border: none;" value="<?php echo $total_tax; ?>"/></p>
                                        </div>
                                        <div class="m-t-10 m-b-10" id="divtaxes">
                                            <p class="text-right">
                                                Amount of Sales Taxes 
                                               
                                                <input class="decimal" <?php if($editable==false){ ?>readonly="readonly"<?php } ?> onchange="calctaxfromperc()" id="txttaxfromperc" class="form-inline " style="text-align:right; width: 50px; border: none;" value="<?php echo $order[0]['invoice_sales_tax_perc'];?>"/>%
                                               
                                                <input <?php if($editable==false){echo ' readonly="readonly" '; }?> class="numeric" onchange="updatetotal_new()" id="txtothersalestax" class="form-inline " style="text-align:right; width: 80px; border: none;" value="<?php echo $order[0]['invoice_sales_tax'];?>"/></p>
                                        </div>
                                        
                                        <hr>
                                        <p class="text-right"><b>Amount Inclusive of Taxes:  <?php echo CURRENCY_CODE;?>.</b> <input id="txttotalpayable" readonly="readonly" class="form-inline " style="text-align:right;width: 80px; border: none; font-weight: bold;" value="<?php echo $order[0]['invoice_total_receivable'];?>" /></p>
                                        
                                        <div id="witharrearsdiv" style="display:none;">    
                                            <p class="text-right">
                                                Arrears
                                                <input style="text-align: right; border:none;" readonly="readonly" class="decimal" id="arrears" class="form-inline" value="<?php if(isset($arrears)){echo $arrears->balance;}else{echo 0;}?>">
                                            </p>
                                            <hr>
                                            <p class="text-right" >
                                                Total Payable with Arrears
                                                <input style="text-align: right; border:none;" readonly="readonly" class="decimal" id="totalwitharrears" class="form-inline" value="">
                                            </p>
                                        </div>
                                        <!-- <p class="text-right"><strong>In Words: 
                                                <?//php// if(isset($arrears)){
                                                    //$words = convert_number_to_words(round($order[0]['invoice_total_receivable']+$arrears->balance));
                                                    //print_r(strtoupper($words));
                                                //}   else{                                        
                                                //    $words = convert_number_to_words(round($order[0]['invoice_total_receivable']));
                                                //    print_r(strtoupper($words));
                                                //}
                                                ?> RUPEES ONLY
                                                </strong>
                                         </p>-->
                                    </div>
                                </div>    
                                <div class="row" style="">
                                    <div class="col-md-4 col-sm-4 col-xs-4">                                           
                                        <p style="border-top:1px solid #000;">For <?php echo $business[0]['business_name'];?></p>
                                    </div>
                                    
                                </div>

                                <div class="row m-t-40">    
                                    <div class="clearfix m-t-5" style="text-align:center;">
                                        <p><i>Please make all checks payable to</i><strong> <?php echo $business[0]['business_name'];?></strong></p>
                                        <p><?php echo $business[0]['payment_terms'];?></p>
                                    </div>
                                    <div class="col-md-12 " style="text-align:center;">
                                                                                
                                        <p><strong>Thank You For Your Business!</strong></p>
                                        <p>For any queries, please email to <?php echo $business[0]['business_email'];?></p>
                                    </div>
                                </div>
                                
                                
                                <div class="hidden-print">
                                    <hr>
                                    <div class="pull-left">
                                        <div class="form-check">
                                            <input onclick="showhidearrears();" type="checkbox" class="form-check-input" id="showarrears" style="width: 16px; height:16px;">
                                            <label class="form-check-label" for="showarrears">Show Arrears</label>
                                        </div>
                                    </div>
                                    <div class="pull-right">
                                       
                                        
                                        <?php if($editable==true){?>
                                        <a href="javascript:void(0);" onclick="createinvoice();" class="btn btn-primary waves-effect waves-light" id="btnsubmit">Submit</a>
                                        <?php } else { ?>
                                        <a href="javascript:window.print()" class="btn btn-inverse waves-effect waves-light" id="btnprint"><i class="fa fa-print"></i></a>
                                         <?php if($order[0]['order_status']=='Invoiced'){?>
                                        <form id="cancelform" style="display:inline-block;" method="post" action='<?php echo base_url();?>franchise_controller/cancelorderinvoice'>
                                            <input type="hidden" name="csrf_test_name" id="order_cancel_csrf" value=""/>                                                
                                            <input type="hidden" name='order_id' value='<?php echo $order[0]['id_franchise_orders'];?>'>
                                            <input type="hidden" name='selected_franchise' value='<?php echo $order[0]['franchise_id'];?>'>
                                            <button type="submit" onclick="$('#order_cancel_csrf').val($('#cook').val());" class="btn btn-icon waves-effect waves-light btn-danger "> <i class="fa fa-trash"></i> Cancel </button>  
                                        </form>
                                         <?php } ?>
                                        <?php } ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>

                </div>
                <!-- end row -->
             
            </div> 
<script>
    $(document).ready(function(){
        
         $('#invoice_date').datepicker({
            default: today,
            autoclose: true,
            todayHighlight: true,
            format: 'yyyy-mm-dd'
        }).datepicker('setDate', new Date());
                
        
        $(".numeric").keypress(function (e) {
            //if the letter is not digit then display error and don't type anything
            if (e.which != 13 && e.which != 8 && e.which != 0  && e.which != 46 && (e.which < 48 || e.which > 57)) {
               return false;
           }
        });
        $(".multinumeric").keypress(function (e) {
            //if the letter is not digit then display error and don't type anything
            if (e.which != 13 && e.which != 8 && e.which != 0  && e.which != 46 && e.which != 44 && (e.which < 48 || e.which > 57)) {
               return false;
           }
        });
        $(".decimal").keypress(function(e) {
            //if the letter is not digit then display error and don't type anything
            if (e.which != 13 && e.which != 8 && e.which != 0  && e.which != 46 && (e.which < 48 || e.which > 57) ) {
                
                return false;
            }
        });
        
        <?php if($editable==true){?>        
            updatetotal_new();
        <?php } ?>
        
        toastr.options = {
            "closeButton": true,
            "debug": true,
            "newestOnTop": true,
            "progressBar": true,
            "positionClass": "toast-bottom-center",
            "preventDuplicates": true,
            "onclick": null,
            "showDuration": "100",
            "hideDuration": "500",
            "timeOut": "5000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        }
        
        $("#txtdiscount").change(function(){
            
            if($('#txtothercharges').val()===""){$('#txtothercharges').val(0);}
            var subtotalextra = parseFloat($('#txtsubtotal').val())+parseFloat($('#txtothercharges').val());
            var parcentage = (parseFloat($(this).val()) / subtotalextra) * 100;
            $('#discount_in_percent').val(parcentage.toFixed(2));
            //$("#paid").val($("#grandtotal").val());
            //$("#balanceamount").val(parseFloat($("#grandtotal").val()) - parseFloat($("#paid").val()));
            updatetotal_new();
            
        });
        $("#discount_in_percent").change(function(){
            
            if($('#txtothercharges').val()===""){$('#txtothercharges').val(0);}
            var subtotalextra = parseFloat($('#txtsubtotal').val())+parseFloat($('#txtothercharges').val());
            var discount = (parseFloat($(this).val()) * subtotalextra) / 100;
            $('#txtdiscount').val(Math.round(discount));
            //$("#paid").val($("#grandtotal").val());
            //$("#balanceamount").val(parseFloat($("#grandtotal").val()) - parseFloat($("#paid").val()));
            updatetotal_new();
            
        });
        $("#tax_in_perc").change(function(){
            
            var grosstotal = parseFloat($('#txtgross').val());
            var salestax = (parseFloat($(this).val()) * grosstotal) / 100;
            $('#txtothersalestax').val(Math.round(salestax));
            //$("#paid").val($("#grandtotal").val());
            //$("#balanceamount").val(parseFloat($("#grandtotal").val()) - parseFloat($("#paid").val()));
            updatetotal_new();
            
            
        });

        

    });   
    
       
    function updatetotal(){
        
        if($('#txtdiscount').val()===""){$('#txtdiscount').val('0');}
        if($('#txtothercharges').val()===""){$('#txtothercharges').val('0');}
        if($('#arrears').val()===""){$('#arrears').val('0');}
        
        
        var grosstotal=(parseFloat($("#txtsubtotal").val()) +  parseFloat($("#txtothercharges").val())) - parseFloat($("#txtdiscount").val());
        var taxabletotal=(parseFloat($("#txtsubtotal").val()) +  parseFloat($("#txtothercharges").val())) - parseFloat($("#txtdiscount").val());
        var orggrosstotal = parseFloat($("#txt_org_subtotal").val()) +  parseFloat($("#txtothercharges").val());
        var arrears = $('#arrears').val();
        
        
        $("#txtgross").val(grosstotal);
        
         var salestax = (parseFloat($('#tax_in_perc').val()) * grosstotal) / 100;
         $('#txtsalestax').val(Math.round(salestax));
       
        var totalpayable=grosstotal + parseFloat(salestax);
        $("#txttotalpayable").val(Math.round(totalpayable*100)/100);
        $("#grandtotal").val(Math.round(grosstotal));
        
        
        $("#totalwitharrears").val(Math.round(totalpayable+parseFloat(arrears)));
        
        $('#btnsubmit').removeClass('disabled');
        
        if(parseFloat($("#txtsalestax").val()) > 0){
            $("#saledtaxtag").show();
        }else {
            $("#saledtaxtag").hide();
        }
        
        showhidearrears();
    }
    
    function showhidearrears(){
        if($("#showarrears").is(":checked")){
           $("#witharrearsdiv").show();
           $("#totalwitharrears").val(Math.round(parseFloat($("#txttotalpayable").val()) + parseFloat($("#arrears").val())));
        }else{
            $("#witharrearsdiv").hide();
        }
        
    }
    
    function invoice_storeOTblValues(){
    
        var TableData = new Array();
        $('#tblproducts tr').each(function(row, tr) {
            TableData[row] = {
                "id_franchise_order_products": $(tr).find('td:eq(0)').attr('fpid')
                , "seq": $(tr).find('td:eq(0)').text()
                , "productid": $(tr).find('td:eq(0) input').val()
                , "brandname": $(tr).find('td:eq(1)').text()
                , "productname": $(tr).find('td:eq(2) .productname').text()
                , "category": $(tr).find('td:eq(2) .category').text()
                , "batch_id": $(tr).find('td:eq(3) #batch_id').val()
                , "batch": $(tr).find('td:eq(3) #batch').val()
                , "batch_amount": $(tr).find('td:eq(3) #batch_amount').val()
                
                , "staff_name": $(tr).find('td:eq(4)').text()
                , "unit_price": $(tr).find('td:eq(5)').text()
                , "qty": $(tr).find('td:eq(6)').text()
                , "product_price": $(tr).find('td:eq(7)').text()
                , "product_discount": $(tr).find('td:eq(8)').text()
                , "discount_perc": $(tr).find('td:eq(9) #disc_perc').text()
                , "discounted_price": $(tr).find('td:eq(10) .combat').text()
                , "product_tax": $(tr).find('td:eq(12)').find('input[name=product_tax]').val()
                , "final_price": $(tr).find('td:eq(13)').text()
            }
        });
        TableData.shift();  // first row will be empty - so remove
        TableData.pop();  // last row will be empty - so remove
        //console.log(TableData); 
        return TableData;
    }
    
    function createinvoice(){
    
            create_new_invoice();   
        
    }

    function create_new_invoice(){
        
        var TableData;
            TableData = invoice_storeOTblValues();
            TableData = $.toJSON(TableData);
       
        
        $('#btnsubmit').addClass('disabled');
        $('#btnsubmit').html('<i class="fa fa-spin fa-spinner"></i> Please wait');
    
        $.ajax({
            type: 'POST',
            url: '<?php echo base_url();?>franchise_controller/updateorderinvoice',
            data: {
                tabledata: TableData,
                orderid: $("#orderid").val(),
                customerid:$("#customerid").val(),
                customername:$("#customername").val(),
                customercell:$("#customercell").val(),
                customerntn: $("#customerntn").val(),
                companyname:$("#companyname").html(),
                
                orgsubtotal:$("#txt_org_subtotal").val(),
                discount:$("#txtdiscount").val(),                
                discount_perc: $('#discount_in_percent').val(),
                product_discount: $("#txtproductdiscount").val(),
                other_charges: $('#txtothercharges').val(),
                
                grosstotal:$("#txtgross").val(),
                
                tax_in_perc:$("#txttaxfromperc").val(), 
                salestax:$("#txtsalestax").val(),    
                othertax:$("#txtothersalestax").val(),    

                grandtotal:$("#grandtotal").val(),
                totalpayable:$("#txttotalpayable").val(),
                
                
                remarks: $("#txtremarks").val(),
                invoicedate: $("#invoice_date").val(),
                invoicenumber : $("#invoicenumber").val()
            },
            success: function(data) {
                var result = data.split("|");
                if (result[0] === "Success") {
//                    $("#txtinvoiceid").val(result[1]);
//                    toastr.success('Order Invoiced!', 'Print the invoice');
//                    $('#btnsubmit').html('Done');
                    location.reload();
                } else {
                    swal({
                        title: "Check Available Stock",
                        text: result[1],
                        type: "error",
                        confirmButtonText: 'OK!'
                    });
                    $('#btnsubmit').removeClass('disabled');
                    $('#btnsubmit').html('Submit');
                }

            }
        });
        
        $("#txtdiscount").attr("readonly",true);
        $("#discount_in_percent").attr("readonly",true);
        $(".discount_by_product").attr("readonly",true);
        $(".perc_discount_product").attr("readonly",true);
        
        
    }

    
    
    function updatetotal_new(){
       
        var totalproductdiscount=0;
        var totalorgtotal=0;
        var totaltax=0;
        var totalwithtax=0;
        $('#tblproducts tr').each(function(row, tr) {   
            if($(tr).find('td:eq(0)').text() != '#' && $(tr).find('td:eq(0)').text() != ''){
                
                totalproductdiscount = totalproductdiscount + parseFloat($(tr).find('td:eq(8)').text());            
                totalorgtotal = totalorgtotal + parseFloat($(tr).find('td:eq(7)').text());
                totalorgtotal=Math.round(totalorgtotal * 100)/100;
                var thisprice = parseFloat( $(tr).find('td:eq(10)').find('span[class=combat]').html());
                var thistax = parseFloat( $(tr).find('td:eq(12)').find('input[name=product_tax]').val())
                totaltax = totaltax + thistax;

                var thisperc =  Math.round((100 * thistax / thisprice)*100)/100;
                $(tr).find('td:eq(11)').find('input[name=tax_perc]').val(thisperc);

                totalwithtax =totalwithtax + $(tr).find('td:eq(13)').text();
            }
        });
        $(".taxtotal").html(Math.round(totaltax*100)/100);

        $("#txt_org_subtotal").val(Math.round(totalorgtotal * 100)/100 );
        
        var subtotal = parseFloat($("#txt_org_subtotal").val(totalorgtotal));
        $("#txtproductdiscount").val(totalproductdiscount);
        var additional_discount = parseFloat($("#txtdiscount").val());
        var other_charges =  parseFloat($("#txtothercharges").val());

        $("#txtsalestax").val(Math.round(totaltax*100)/100);   
        //amount exclusive of taxes
        $("#txtgross").val(Math.round((totalorgtotal - totalproductdiscount - additional_discount + other_charges) *100)/100);
        var totalbeforetax = totalorgtotal - totalproductdiscount - additional_discount + other_charges;

        var othertaxes = parseFloat($("#txtothersalestax").val());

        $("#txttotalpayable").val(Math.round((totalbeforetax + totaltax + othertaxes)*100)/100);
        $('#btnsubmit').removeClass('disabled');
        showhidearrears();
    }
 
    function calctaxfromperc(){
         $('#txtothersalestax').val( Math.round(($("#txtgross").val() * $("#txttaxfromperc").val()/100) ) );
        updatetotal_new();
    }
 
</script>