<?php
$this->load->view ( $left );
$this->load->view ( $header );
?>
<style type="text/css">
    .ibox-content {
        border-style : none;
    }

    .hr-line-dashed {
        margin: 5px 0;
    }

    .disabledbutton {
        pointer-events: none;
        opacity: 0.4;
    }
</style>
<div class="row wrapper border-bottom white-bg page-heading">
    <div class="col-sm-4">
        <h2><?php echo ($devid_note_edit_no == 0) ? 'New Debit Note' : 'Edit Debit Note';?></h2>
    </div>
</div>
<div class="wrapper wrapper-content">
    <div class="row text-center animated fadeInRightBig">
        <div class="col-lg-12">
            <form method="post" class="form-horizontal" id="debit_note_data">
                <div class="ibox float-e-margins">
                    <div class="ibox-content">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">Vendor</label>
                            <div class="col-sm-10">
                                <select class="form-control" name="vendor_id" id="choose_customer">
                                    <option value="">Select Customer</option>
                                    <?php if (count($customer_list) > 0) {
                                        foreach ($customer_list as $key => $value) {?>
                                            <option value="<?php echo $value->id;?>" <?php echo (!empty($devid_note_no) && isset($bill_data) && ($bill_data['vendor_id'] == $value->id)) ? 'selected="selected"' : '';?>><?php echo $value->name;?></option>
                                        <?php }
                                    }?>
                                </select>
                            </div>
                            <div class="col-sm-12" id="customer_address"></div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">Debit Note Number</label>
                            <div class="col-sm-10">
                                <input type="text" name="devid_note_no" id="devid_note_no" class="form-control" placeholder="Invoice Number" value="<?php echo $devid_note_no;?>">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">Bill No</label>
                            <div class="col-sm-10">
                                <select class="form-control" name="bill_no" id="bill_no_drop">
                                    <option value="">Select Bill No</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group date_calender">
                            <label class="col-sm-2 control-label">Bill Date</label>
                            <div class="col-sm-4">
                                <div class="input-group date">
                                    <span class="input-group-addon"><i class="fa fa-calendar"></i></span><input type="text" name="devid_date" id="devid_date" class="form-control" value="<?php echo (!empty($bill_id) && isset($bill_data) ? date('d/m/Y',strtotime(str_replace('-', '/', $bill_data['devid_date']))) : date('d/m/Y'));?>">
                                </div>
                            </div>
                        </div>
                        <div id="sell_item" class="form-group disabledbutton">
                            <div class="col-sm-12 table-responsive">
                                <table class="table table-bordered">
                                    <thead>
                                        <tr>
                                            <th>Item Details</th>
                                            <th>Hsn Code</th>
                                            <th>GST%</th>
                                            <th>Quantity</th>
                                            <th>Uom</th>
                                            <th>Rate</th>
                                            <!-- <th>Discount</th> -->
                                            <th>Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody id="products">
                                        <?php 
                                        if(isset($item_details) && count($item_details)){
                                            foreach ($item_details as $key => $value) {?>
                                                <tr class="tr_<?php echo $key;?>">
                                                    <td style="width: 40%;">
                                                        <div class="col-sm-1 no-padding">
                                                            <button type="button" class="btn btn-danger btn-circle btn-xxs remove_item" data-tr="<?php echo $key;?>"><i class="fa fa-times-circle-o fa-lg"></i></button>
                                                        </div>
                                                        <div class="col-sm-11 no-padding">
                                                            <input type="" name="item_name[]" class="form-control item_name" data-tr="<?php echo $key;?>" value="<?php echo !empty($value->item) ? $value->item : '';?>">
                                                            <span id="stock_0"></span>
                                                            <!-- <select class="form-control item_name" name="item_name[]" data-tr="0">
                                                                <option value="">Select Item</option>
                                                                <?php //if(count($item_list) > 0){
                                                                    //foreach($item_list as $key_item => $value_item){?>
                                                                    <option value="<?php //echo $value_item->item_id;?>" <?php //echo (!empty($value->item) && ($value_item->item_id == $value->item)) ? 'selected="selected"' : ''; ?>><?php //echo $value_item->item_name;?></option>
                                                                <?php //}
                                                                //}?>
                                                            </select> -->
                                                        </div>
                                                    </td>
                                                    <td style="width: 10%;"><input type="text" name="hsn_code" id="hsn_code0" class="form-control hsn_code" data-tr="0"></td>
                                                    <td style="width: 10%;"><input type="number" name="gst_rate" id="gst_rate0" class="form-control gst_rate" data-tr="0"></td>
                                                    <td style="width: 10%;"><input type="number" name="item_quantity[]" class="form-control quantity" data-tr="<?php echo $key;?>" value="<?php echo !empty($value->qty) ? $value->qty : '';?>"></td>
                                                    <td style="width: 10%;"><select name="uom[]" class="form-control uom" id="uom0" data-tr="0"><option value="Pice" <?php echo (!empty($value->uom) && ($value->uom == 'Pice')) ? 'slected="selected"' : '';?>>Pice</option><option value="Pair" <?php echo (!empty($value->uom) && ($value->uom == 'Pair')) ? 'slected="selected"' : '';?>>Pair</option><option value="Set" <?php echo (!empty($value->uom) && ($value->uom == 'Set')) ? 'slected="selected"' : '';?>>Set</option></select></td>
                                                    <td style="width: 10%;"><input type="number" name="item_rate[]" class="form-control unit_price" id="unit_price0" data-tr="<?php echo $key;?>" value="<?php echo !empty($value->rate) ? number_format((float)$value->rate, 2, '.', '') : '';?>"></td>
                                                    <!-- <td style="width: 10%;"><input type="number" name="item_discount[]" class="form-control discount" data-tr="<?php //echo $key;?>" value="<?php //echo !empty($value->discount) ? $value->discount : '';?>"></td> -->
                                                    <td style="width: 10%;"><span id="item_price_<?php echo $key;?>"><?php echo !empty($value->amount) ? number_format((float)$value->amount, 2, '.', '') : '';?></span></td>
                                                </tr>
                                            <?php }
                                        } else {?>
                                        <tr class="tr_0">
                                            <td style="width: 40%;">
                                                <div class="col-sm-1 no-padding">
                                                    <button type="button" class="btn btn-danger btn-circle btn-xxs remove_item" data-tr="0"><i class="fa fa-times-circle-o fa-lg"></i></button>
                                                </div>
                                                <div class="col-sm-11 no-padding">
                                                    <input type="" name="item_name[]" id="item_name_0" class="form-control item_name" data-tr="0">
                                                    <span id="stock_0"></span>
                                                    <!-- <select class="form-control item_name" name="item_name[]" data-tr="0">
                                                        <option value="">Select Item</option>
                                                        <?php //if(count($item_list) > 0){
                                                            //foreach($item_list as $key_item => $value_item){?>
                                                            <option value="<?php //echo $value_item->item_id;?>"><?php //echo $value_item->item_name;?></option>
                                                        <?php //}
                                                        //}?>
                                                    </select> -->
                                                </div>
                                            </td>
                                            <td style="width: 10%;"><input type="text" name="hsn_code" id="hsn_code0" class="form-control hsn_code" data-tr="0"></td>
                                            <td style="width: 10%;"><input type="number" name="gst_rate" id="gst_rate0" class="form-control gst_rate" data-tr="0"></td>
                                            <td style="width: 10%;"><input type="number" name="item_quantity[]" class="form-control quantity" data-tr="0"></td>
                                            <td style="width: 10%;"><select name="uom[]" class="form-control uom" id="uom0" data-tr="0"><option value="Pice">Pice</option><option value="Pair">Pair</option><option value="Set">Set</option></select></td>
                                            <td style="width: 10%;"><input type="number" name="item_rate[]" class="form-control unit_price" id="unit_price0" data-tr="0"></td>
                                            <!-- <td style="width: 10%;"><input type="number" name="item_discount[]" class="form-control discount" data-tr="0"></td> -->
                                            <td style="width: 10%;"><span id="item_price_0"></span></td>
                                        </tr>
                                    <?php }?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-lg-6">
                                <button type="button" class="btn btn-success additem"><i class="fa fa-plus-square"></i><span class="m-l-xs">Add Item</span></button>
                            </div>
                            <div class="col-lg-6">
                                <div class="form-group">
                                    <label class="col-sm-10 control-label text-left" style="text-align: left;">Sub Total</label>
                                    <div class="col-sm-2">
                                        <label id="sub_total"><?php echo (!empty($bill_id) && isset($bill_data) ? number_format((float)$bill_data['sub_total'], 2, '.', '') : '0.00');?></label>
                                    </div>
                                </div>
                                <!-- <div class="hr-line-dashed"></div>
                                <div class="form-group">
                                    <label class="col-sm-6 control-label" style="text-align: left;">Shipping Charges</label>
                                    <div class="col-sm-4">
                                        <input type="text" name="shipping_charge" id="shipping_charge" class="form-control" placeholder="Shipping">
                                    </div>
                                    <div class="col-sm-2">
                                        <label id="shipping_cost">0.00</label>
                                    </div>
                                </div> -->
                                <div class="hr-line-dashed gst_show <?php echo isset($customer_details) ? (((count($customer_details)>0) && ($customer_details->shipping_state == 19)) ? '' : 'hide') : '';?>"></div>
                                <div class="form-group gst_show <?php echo isset($customer_details) ? (((count($customer_details)>0) && ($customer_details->shipping_state == 19)) ? '' : 'hide') : '';?>">
                                    <label class="col-sm-10 control-label text-left" style="text-align: left;">CGST Total</label>
                                    <div class="col-sm-2">
                                        <label id="cgst_cost"><?php echo (!empty($bill_id) && isset($bill_data) ? number_format((float)$bill_data['cgst_total'], 2, '.', '') : '0.00');?></label>
                                    </div>
                                </div>
                                <div class="hr-line-dashed gst_show <?php echo isset($customer_details) ? (((count($customer_details)>0) && ($customer_details->shipping_state == 19)) ? '' : 'hide') : '';?>"></div>
                                <div class="form-group gst_show <?php echo isset($customer_details) ? (((count($customer_details)>0) && ($customer_details->shipping_state == 19)) ? '' : 'hide') : '';?>">
                                    <label class="col-sm-10 control-label text-left" style="text-align: left;">SGST Total</label>
                                    <div class="col-sm-2">
                                        <label id="sgst_cost"><?php echo (!empty($bill_id) && isset($bill_data) ? number_format((float)$bill_data['sgst_total'], 2, '.', '') : '0.00');?></label>
                                    </div>
                                </div>
                                <div class="hr-line-dashed igst_show <?php echo isset($customer_details) ? (((count($customer_details)>0) && ($customer_details->shipping_state != 19)) ? '' : 'hide') : 'hide';?>"></div>
                                <div class="form-group igst_show <?php echo isset($customer_details) ? (((count($customer_details)>0) && ($customer_details->shipping_state != 19)) ? '' : 'hide') : 'hide';?>">
                                    <label class="col-sm-10 control-label text-left" style="text-align: left;">IGST Total</label>
                                    <div class="col-sm-2">
                                        <label id="igst_cost"><?php echo (!empty($bill_id) && isset($bill_data) ? number_format((float)$bill_data['igst_total'], 2, '.', '') : '0.00');?></label>
                                    </div>
                                </div>
                                <!-- <div class="hr-line-dashed"></div>
                                <div class="form-group">
                                    <label class="col-sm-6 control-label" style="text-align: left;">Adjustment</label>
                                    <div class="col-sm-4">
                                        <input type="number" name="adjustment" class="form-control" placeholder="Adjustment" id="final_adjustment">
                                    </div>
                                    <div class="col-sm-2">
                                        <label id="adjustment_cost">0.00</label>
                                    </div>
                                </div> -->
                                <div class="hr-line-dashed"></div>
                                <div class="form-group">
                                    <label class="col-sm-10 control-label text-left" style="text-align: left;">Total ( ₹ )</label>
                                    <div class="col-sm-2">
                                        <label id="final_cost"><?php echo (!empty($bill_id) && isset($bill_data) ? number_format((float)$bill_data['total'], 2, '.', '') : '0.00');?></label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="ibox">
                    <div class="ibox-content">
                        <div class="row">
                            <div class="col-lg-8 pull-right">
                                <div class="form-group">
                                    <label class="col-sm-3 control-label" style="text-align: left;">Customer Note</label>
                                    <div class="col-sm-9">
                                        <textarea class="form-control" name="customer_note"></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="ibox">
                    <div class="ibox-content">
                        <div class="row">
                            <div class="col-lg-6 pull-right">
                                <div class="form-group">
                                    <div class="col-sm-12 col-sm-offset-2">
                                        <button class="btn btn-primary generate_debit_note" type="button" data-status="1"><i class="fa fa-download"></i><span class="m-l-xs">Save</span></button>
                                        <button class="btn btn-danger back_listing" type="button">Cancel</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<?php $this->load->view($footer); ?>
<script type="text/javascript">
    $(document).ready(function(){
        $('.date_calender .input-group.date').datepicker({
            todayBtn: "linked",
            keyboardNavigation: false,
            forceParse: false,
            calendarWeeks: true,
            language: 'en',
            autoclose: true
        });

        var trId =0;
        <?php if(isset($customer_details) && (count($customer_details)>0)){?>
            var userState =<?php echo $customer_details->shipping_state;?>;
        <?php } else {?>
            var userState =0;
        <?php }?>
        
        var items = new Object();
        var items_tot = new Object();
        items[trId] = new Object();

        var gst_list = JSON.parse('<?php echo $item_gst;?>');
        var item_purchase_price = JSON.parse('<?php echo $item_purchase_price;?>');
        var item_uom = JSON.parse('<?php echo $item_uom;?>');
        var item_hsn = JSON.parse('<?php echo $item_hsn;?>');
        var items_autocomplete = JSON.parse('<?php echo $items_autocomplete;?>');

        var $input = $("#item_name_0");
        $input.typeahead({
          source: items_autocomplete
          //autoSelect: true
        });

        <?php 
        if(isset($item_details) && (count($item_details)>0)){
            foreach ($item_details as $key => $value) {?>
                items[<?php echo $key;?>] = new Object();
                items[<?php echo $key;?>].item_name = '<?php echo $value->item;?>';
                items[<?php echo $key;?>].hsn_code = '<?php echo $value->hsn_code;?>';
                items[<?php echo $key;?>].item_gst = <?php echo $value->gst_rate;?>;
                items[<?php echo $key;?>].quantity = <?php echo $value->qty;?>;
                items[<?php echo $key;?>].uom = '<?php echo $value->uom;?>';
                items[<?php echo $key;?>].unit_price = <?php echo $value->rate;?>;
                items[<?php echo $key;?>].discount = 0;
                items[<?php echo $key;?>].price = <?php echo $value->amount;?>;
            <?php }
        } else {?>
            items[trId].item_name = '';
            items[trId].item_id = 0;
            items[trId].hsn_code = '';
            items[trId].item_gst = 0;
            items[trId].quantity = 0;
            items[trId].uom = 'Pice';
            items[trId].unit_price = 0;
            items[trId].discount = 0;
            items[trId].price = 0;
        <?php }?>

        $('.additem').on('click',function(){
            trId++;
            var tr = '<tr class="tr_'+trId+'">';
                tr +=   '<td style="width: 40%;">';
                tr +=       '<div class="col-sm-1 no-padding">';
                tr +=           '<button type="button" class="btn btn-danger btn-circle btn-xxs remove_item" data-tr="'+trId+'"><i class="fa fa-times-circle-o fa-lg"></i></button>';
                tr +=       '</div>'
                tr +=       '<div class="col-sm-11 no-padding">';
                tr +=           '<input type="" name="item_name[]" class="form-control item_name" id="item_name_'+trId+'" data-tr="'+trId+'">';
                tr +=           '<span id="stock_'+trId+'"></span>';
                // tr +=           '<select class="form-control item_name" name="item_name[]" data-tr="'+trId+'">';
                // tr +=               '<option value="">Select Item</option>';
                // tr +=               '<?php if(count($item_list) > 0){ foreach($item_list as $key_item => $value_item){?>';
                // tr +=               '<option value="<?php echo $value_item->item_id;?>"><?php echo $value_item->item_name;?></option>';
                // tr +=                '<?php } }?>';
                // tr +=           '</select>';
                tr +=       '</div>';
                tr +=   '</td>';
                tr +=   '<td style="width: 10%;"><input type="text" name="hsn_code" id="hsn_code'+trId+'" data-tr="'+trId+'" class="form-control hsn_code"></td>';
                tr +=   '<td style="width: 10%;"><input type="number" name="gst_rate" id="gst_rate'+trId+'" data-tr="'+trId+'" class="form-control gst_rate"></td>';
                tr +=   '<td style="width: 10%;"><input type="number" name="item_quantity[]" data-tr="'+trId+'" class="form-control quantity"></td>';
                tr +=   '<td style="width: 10%;"><select name="uom[]" class="form-control uom" id="uom'+trId+'" data-tr="'+trId+'"><option value="Pice">Pice</option><option value="Pair">Pair</option><option value="Set">Set</option></select></td>';
                tr +=   '<td style="width: 10%;"><input type="number" name="item_rate[]" id="unit_price'+trId+'" data-tr="'+trId+'" class="form-control unit_price"></td>';
                //tr +=   '<td style="width: 10%;"><input type="number" name="item_discount[]" data-tr="'+trId+'" class="form-control discount"></td>';
                tr +=   '<td style="width: 10%;"><span id="item_price_'+trId+'"></span></td>';
                tr += '</tr>';
            $('#products').append(tr);

            var $input = $("#item_name_"+trId);
            $input.typeahead({
              source: items_autocomplete
              //autoSelect: true
            });

            items[trId] = new Object();
            items[trId].item_id = 0;
            items[trId].item_name = '';
            items[trId].hsn_code = '';
            items[trId].item_gst = 0;
            items[trId].quantity = 0;
            items[trId].uom = 'Pice';
            items[trId].unit_price = 0;
            items[trId].discount = 0;
            items[trId].price = 0;
        });

       $(document).on('click','.remove_item',function(){
            var trId = $(this).data('tr');
            $('.tr_'+trId).remove();
            delete items[trId];
            bill_calculation()
        }); 

       //============================== CALCULATION ================================//

       $(document).on('change','.item_name',function(){
            var rowid = $(this).data('tr');
            var current = $(this).typeahead("getActive");
            if (current) {
                // Some item from your model is active!
                if (current.name == $(this).val()) {
                  // This means the exact match is found. Use toLowerCase() if you want case insensitive match.
                    items[rowid].item_id = current.id;
                    items[rowid].item_name = current.name;
                    items[rowid].hsn_code = item_hsn[current.id];
                    items[rowid].item_gst = gst_list[current.id];
                    items[rowid].unit_price = item_purchase_price[current.id];
                    items[rowid].uom = item_uom[current.id];

                    $('#unit_price'+rowid).val(items[rowid].unit_price);
                    $('#uom'+rowid).val(items[rowid].uom);
                    $('#hsn_code'+rowid).val(items[rowid].hsn_code);
                    $('#gst_rate'+rowid).val(items[rowid].item_gst);

                    get_item_stock(current.id,rowid);
                } else {
                  // This means it is only a partial match, you can either add a new item
                  // or take the active if you don't want new items
                   items[rowid].item_name = $(this).val();
                }
            } else {
              items[rowid].item_name = $(this).val();
            // Nothing is active so it is a new value (or maybe empty value)
            }
       });

       $(document).on('keyup change','.quantity',function(){
            var rowid = $(this).data('tr');
            items[rowid].quantity = parseInt($(this).val());
            bill_calculation();
       });

       $(document).on('keyup change','.gst_rate',function(){
            var rowid = $(this).data('tr');
            items[rowid].item_gst = parseInt($(this).val());
            bill_calculation();
       });

       $(document).on('keyup change','.hsn_code',function(){
            var rowid = $(this).data('tr');
            items[rowid].hsn_code = $(this).val();
       });

       $(document).on('keyup change','.unit_price',function(){
            var rowid = $(this).data('tr');
            items[rowid].unit_price = parseInt($(this).val());
            bill_calculation();
       });

       // $(document).on('keyup change','.discount',function(){
       //      var rowid = $(this).data('tr');
       //      items[rowid].discount = parseInt($(this).val());
       //      bill_calculation();
       // });

       $(document).on('change','.uom',function(){
            var rowid = $(this).data('tr');
            items[rowid].uom = $(this).val();
       });

       // $(document).on('keyup change','#shipping_charge',function(){
       //      items['shipping_charge'] = $(this).val();
       //      bill_calculation();
       // });

       // $(document).on('keyup change','#final_adjustment',function(){
       //      items['final_adjustment'] = $(this).val();
       //      bill_calculation();
       // });

        <?php    
        if(isset($bill_data) && (count($bill_data) > 0)){?>
            items_tot['sub_total'] = <?php echo $bill_data['sub_total'];?>;
            items_tot['shipping_charge'] = 0;
            items_tot['cgst'] = <?php echo $bill_data['cgst_total'];?>;
            items_tot['sgst'] = <?php echo $bill_data['sgst_total'];?>;
            items_tot['igst'] = <?php echo $bill_data['igst_total'];?>;
            items_tot['final_adjustment'] = 0;
            items_tot['final_total'] = <?php echo $bill_data['total'];?>;
            <?php 
        }?>

        function get_item_stock(itemId,trId){
            $.ajax({
                url: '<?php echo site_url('items/get_item_stock');?>',
                type: "POST",
                data:{
                    'item_id'  : itemId
                },
                success: function(data){ 
                    var stock_text = '<strong>Item Remain In Stock : '+data+'</strong>';
                    $('#stock_'+trId).html('');
                    $('#stock_'+trId).html(stock_text);
                }
            });
       }

        function bill_calculation(){
            items_tot['sub_total'] = 0;
            items_tot['shipping_charge'] = 0;
            items_tot['cgst'] = 0;
            items_tot['sgst'] = 0;
            items_tot['igst'] = 0;
            items_tot['final_adjustment'] = 0;
            items_tot['final_total'] = 0;

            var i=1;
            // console.log(items);
            $.each(items, function( index, value ) {
            
                items[index].price = ((parseInt(value.quantity) * parseFloat(value.unit_price)) - parseFloat(value.discount));
                $('#item_price_'+index).text(format(items[index].price,'cost'));
                
                if (typeof items[index].price == 'number') {
                    items_tot['sub_total'] = (items_tot['sub_total'] + items[index].price);
                }
                
                if (userState != 19) {
                    items_tot['igst'] = (parseFloat(items_tot['igst']) + (((parseFloat(value.quantity) * parseFloat(value.unit_price)) * value.item_gst) / 100));
                } else {
                    items_tot['cgst'] = (parseFloat(items_tot['cgst']) + (((parseFloat(value.quantity) * parseFloat(value.unit_price)) * (value.item_gst / 2)) / 100));
                    items_tot['sgst'] = (parseFloat(items_tot['sgst']) + (((parseFloat(value.quantity) * parseFloat(value.unit_price)) * (value.item_gst / 2)) / 100));
                }

                if (Object.keys(items).length == i) {
                    $('#sub_total').text('');
                    $('#sub_total').text(format(items_tot['sub_total'],'cost'));

                    $('#cgst_cost').text('');
                    $('#cgst_cost').text(format(items_tot['cgst'],'cost'));

                    $('#sgst_cost').text('');
                    $('#sgst_cost').text(format(items_tot['sgst'],'cost'));

                    $('#igst_cost').text('');
                    $('#igst_cost').text(format(items_tot['igst'],'cost'));
                    //$('#shipping_cost').text(items['shipping_charge']);
                    //$('#adjustment_cost').text(items['final_adjustment']);
                    items_tot['final_total'] = (parseFloat(items_tot['sub_total'])+parseFloat(items_tot['igst'])+parseFloat(items_tot['cgst'])+parseFloat(items_tot['sgst']));
                    $('#final_cost').text('');
                    $('#final_cost').text(format(items_tot['final_total'],'cost'));
                    //console.log(items_tot);
                }                
                i++;
            });
        }

        $('.back_listing').on('click',function(){
            window.location.href = '<?php echo site_url("invoice");?>';
        });

        $('#choose_customer').on('change',function(){
            var user_id = $(this).val();
            get_bill_list(user_id)
            if (user_id != '') {
                $.ajax({
                    url: '<?php echo site_url('user/user_basic_info');?>',
                    type: "POST",
                    data:{
                        'user_id'       : user_id,
                        'request_from'  : 'ajax'
                    },
                    success: function(data){ 
                        var user_data = JSON.parse(data);
                        userState = user_data.shipping_state;
                        var address_html = '<div class="col-lg-2"></div>';
                            address_html +=     '<div class="col-lg-4">';
                            address_html +=        '<div class="col-lg-12"><strong>Billing Adress</strong></div>';
                            address_html +=        '<div class="col-lg-12"><strong>Phone :</strong>'+user_data.contact_phone+'</div>';
                            address_html +=        '<div class="col-lg-12"><strong>Address :</strong>'+user_data.billing_address+'</div>';
                            address_html +=        '<div class="col-lg-12"><strong>City :</strong>'+user_data.billing_city+'</div>';
                            address_html +=        '<div class="col-lg-12"><strong>State-Zip :</strong>'+user_data.billing_state+' - '+user_data.billing_zip+'</div>';
                            address_html +=        '<div class="col-lg-12"><strong>Country :</strong>'+user_data.billing_country+'</div>';
                            address_html +=        '<div class="col-lg-12"><strong>Fax :</strong>'+user_data.billing_fax+'</div>';
                            address_html +=    '</div>';
                            address_html +=    '<div class="col-lg-4">';
                            address_html +=        '<div class="col-lg-12"><strong>Shipping Adress</strong></div>';
                            address_html +=        '<div class="col-lg-12"><strong>Phone :</strong>'+user_data.contact_phone+'</div>';
                            address_html +=        '<div class="col-lg-12"><strong>Address :</strong>'+user_data.shipping_address+'</div>';
                            address_html +=        '<div class="col-lg-12"><strong>City :</strong>'+user_data.shipping_city+'</div>';
                            address_html +=        '<div class="col-lg-12"><strong>State-Zip :</strong>'+user_data.shipping_state+' - '+user_data.shipping_zip+'</div>';
                            address_html +=        '<div class="col-lg-12"><strong>Country :</strong>'+user_data.shipping_country+'</div>';
                            address_html +=        '<div class="col-lg-12"><strong>Fax :</strong>'+user_data.   shipping_fax+'</div>';
                            address_html +=    '</div>';
                            address_html += '<div class="col-lg-2"></div>';
                        $('#customer_address').html(address_html);
                        $('#sell_item').removeClass('disabledbutton');

                        if (user_data.shipping_state != 19) {
                            $('.igst_show').removeClass('hide');
                            $('.gst_show').addClass('hide');
                        }
                    }
                });
            }
            
        });

        function get_bill_list(user_id){
            if (user_id != '') {
                $.ajax({
                    url: '<?php echo site_url('debit_note/user_bill_list');?>',
                    type: "POST",
                    data:{
                        'user_id'       : user_id
                    },
                    success: function(data){ 
                        $('#bill_no_drop').html('');
                        $('#bill_no_drop').html(data);
                    }
                });
            }
        }

        $('.generate_debit_note').on('click',function(){
            if ($('#choose_customer').val() == '') {
                $('#choose_customer').parent().parent().addClass('has-error');
                return false;
            } else {
                $('#choose_customer').parent().parent().removeClass('has-error');
            }

            if ($('#devid_note_no').val() == '') {
                $('#devid_note_no').parent().parent().addClass('has-error');
                return false;
            } else {
                $('#devid_note_no').parent().parent().removeClass('has-error');
            }

            if ($('#bill_no_drop').val() == '') {
                $('#bill_no_drop').parent().parent().addClass('has-error');
                return false;
            } else {
                $('#bill_no_drop').parent().parent().removeClass('has-error');
            }

            if ($('#devid_date').val() == '') {
                $('#devid_date').parent().parent().addClass('has-error');
                return false;
            } else {
                $('#devid_date').parent().parent().removeClass('has-error');
            }

            var status = $(this).data('status');
            $.ajax({
                url: '<?php echo site_url('Debit_note/generate_debit_note');?>',
                type: "POST",
                data:{
                    'debit_note_basic'  : $('#debit_note_data').serializeArray(),
                    'items_tot'         : items_tot,
                    'items'             : items,
                    'userState'         : userState,
                    'status'            : status
                },
                success: function(data){ 
                    // if (data != '') {
                    //     var print_url = '<?php //echo site_url("bill/bill_print/'+data+'");?>';
                    //     //console.log(print_url);
                    //     var newWindow = window.open(print_url,'_blank');                        
                    //     newWindow.blur();
                    //     window.focus();
                    // }
                    window.location.href = '<?php echo site_url("debit_note");?>';
                }
            });
        });

        function format(val, type) {
            if(type == 'cost' || type == 'per') {
                var va = parseFloat(val).toFixed(2);
            } else {
                var va = parseFloat(val);
            }
            var test = va.toString().replace('.', '.');
            String.prototype.reverse = function() {
                var s = "";
                var i = this.length;
                while (i>0) {
                    s += this.substring(i-1,i);
                    i--;
                }
                return s;
            };

            var n = test.reverse().replace(/(\d{3})/g, "$1 ").reverse();
            
            if(type == 'cost') {
                n = n;
            } else if(type == 'per') {
                n = n + ' %';
            } 
            return n;
        }

    });
</script>
