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

    .hr-line-dashed {
        margin: 5px 0;
    }
</style>
<div class="row wrapper border-bottom white-bg page-heading">
    <div class="col-sm-4">
        <h2><?php echo ($invoice_id == '') ? 'New Payments' : 'Edit Payments';?></h2>
    </div>
</div>
<div class="wrapper wrapper-content">
    <div class="row text-center animated fadeInRightBig">
        
            <form method="post" class="form-horizontal" id="invoice_data">
			
                 <div class="ibox float-e-margins">
        <div class="ibox-content">
            <div class="col-lg-6">
                <div class="form-group">
                    <label class="col-lg-3 control-label" style="text-align: left;">Amount</label>
                    <div class="col-lg-8">
                        <input placeholder="Name" class="form-control pull-left name" type="text" name="name" value="<?php echo !empty($user_details->name) ? $user_details->name : '';?>"> 
                        <!-- <span class="help-block m-b-none">Example block-level help text here.</span> -->
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-3 control-label" style="text-align: left;">Payment Date</label>
                    <div class="col-lg-8">
                        <input placeholder="Email" class="form-control pull-left contact_email" type="email" name="contact_email" value="<?php echo !empty($user_details->contact_email) ? $user_details->contact_email : '';?>">
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-3 control-label" style="text-align: left;">Payment Mode</label>
                    <div class="col-lg-8">
                        <input placeholder="Phone" class="form-control pull-left contact_phone" type="text" name="contact_phone" value="<?php echo !empty($user_details->contact_phone) ? $user_details->contact_phone : '';?>">
                    </div>
                </div>
				<div class="form-group">
                    <label class="col-lg-3 control-label" style="text-align: left;">Reference#</label>
                    <div class="col-lg-8">
                        <input placeholder="Display Name" class="form-control pull-left contact_display_name" type="text" name="contact_display_name" value="<?php echo !empty($user_details->contact_display_name) ? $user_details->contact_display_name : '';?>">
                    </div>
                </div>
                               
            </div>
            <div class="col-lg-6">
                
            </div>
        </div>
    </div>

    <div class="ibox float-e-margins">
        <div class="ibox-content">
            <!-- ================================== BiLLING INFO ====================================================-->
            <div class="col-lg-12">
			
			
				<div class="ibox-content">

                        <table class="table">
                            <thead>
                            <tr>
                                <th>Date</th>
                                <th>Bill#</th>
                                <th>Bill Amount</th>
                                <th>Amount Due</th>
								<th>Payment</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr>
                                <td>07/07/17 <br/>Due Date: 07/07/17</td>
                                <td>INV-000003</td>
                                <td>25000</td>
                                <td>25000</td>
								<td><input type="checkbox" name="" value="" /></td>
                            </tr>
							<tr>
                                <td>07/07/17 <br/>Due Date: 07/07/17</td>
                                <td>INV-000003</td>
                                <td>25000</td>
                                <td>25000</td>
								<td><input type="checkbox" name="" value="" /></td>
                            </tr>
                           
                            </tbody>
                        </table>

                </div>
			
                
            </div>

            <!-- ================================== SHIPPING INFO ====================================================-->
           
        </div>
    </div>
    <div class="ibox float-e-margins">
        <div class="ibox-content">
            <div class="form-group">
                <div class="col-lg-3">
                    <button class="btn btn-sm btn-primary pull-right m-t-n-xs save_userData" type="submit"><strong>Save</strong></button>
					<button class="btn btn-sm btn-primary pull-right m-t-n-xs save_userData" type="submit"><strong>Cancel</strong></button>
                </div>
            </div>
        </div>
    </div>
			
                
            </form>
       
    </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();
        
        <?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;?>].quantity = <?php echo $value->qty;?>;
                items[<?php echo $key;?>].unit_price = <?php echo $value->rate;?>;
                items[<?php echo $key;?>].discount = <?php echo $value->discount;?>;
                items[<?php echo $key;?>].price = <?php echo $value->amount;?>;
            <?php }
        } else {?>
            items[trId].item_name = '';
            items[trId].quantity = 0;
            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: 60%;">';
                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" data-tr="'+trId+'">';
                tr +=       '</div>';
                tr +=   '</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%;"><input type="number" name="item_rate[]" 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);

            items[trId] = new Object();
            items[trId].item_name = '';
            items[trId].quantity = 0;
            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];
            invoice_calculation()
        }); 

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

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

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

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

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

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

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

        <?php    
        if(isset($invoice_data) && (count($invoice_data) > 0)){?>
            items_tot['sub_total'] = <?php echo $invoice_data['sub_total'];?>;
            items_tot['shipping_charge'] = 0;
            items_tot['cgst'] = <?php echo $invoice_data['cgst_total'];?>;
            items_tot['sgst'] = <?php echo $invoice_data['sgst_total'];?>;
            items_tot['igst'] = <?php echo $invoice_data['igst_total'];?>;
            items_tot['final_adjustment'] = 0;
            items_tot['final_total'] = <?php echo $invoice_data['total'];?>;
            <?php 
        }?>
       function invoice_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(items[index].price);
                
                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)) * 3) / 100));
                } else {
                    items_tot['cgst'] = (parseFloat(items_tot['cgst']) + (((parseFloat(value.quantity) * parseFloat(value.unit_price)) * 1.5) / 100));
                    items_tot['sgst'] = (parseFloat(items_tot['sgst']) + (((parseFloat(value.quantity) * parseFloat(value.unit_price)) * 1.5) / 100));
                }

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

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

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

                    $('#igst_cost').text('');
                    $('#igst_cost').text(items_tot['igst']);
                    //$('#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(items_tot['final_total']);
                    console.log(items_tot);
                }                
                i++;
            });
       }

        $('#choose_customer').on('change',function(){
            var user_id = $(this).val();
            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);

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

        $('.generate_invoice').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 ($('#invoice_no').val() == '') {
                $('#invoice_no').parent().parent().addClass('has-error');
                return false;
            } else {
                $('#invoice_no').parent().parent().removeClass('has-error');
            }

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

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

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

            var status = $(this).data('status');
            $.ajax({
                url: '<?php echo site_url('invoice/generate_invoice');?>',
                type: "POST",
                data:{
                    'invoice_basic' : $('#invoice_data').serializeArray(),
                    'items_tot'     : items_tot,
                    'items'         : items,
                    'userState'     : userState,
                    'status'        : status
                },
                success: function(data){ 
                    if (data != '') {
                        var print_url = '<?php echo site_url("invoice/invoice_print/'+data+'");?>';
                        console.log(print_url);
                        var newWindow = window.open(print_url,'_blank');                        
                        newWindow.blur();
                        window.focus();
                    }
                    window.location.href = '<?php echo site_url("invoice");?>';
                }
            });
        });
    });
</script>
